From 965e722ab492d19524c2a0db0da77b30879bbb77 Mon Sep 17 00:00:00 2001 From: Parvez Ahmed Date: Tue, 5 Apr 2016 19:03:26 +0530 Subject: [PATCH 1/5] Adding a method in the AzureClientExtensions to handle the PutOrPatch async calls with 202 responses which have no body and no specific headers --- .../AzureClientExtensions.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs index 57bbd064b95c2..9a38463a88e08 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs @@ -122,6 +122,38 @@ await UpdateStateFromGetResourceOperation(client, pollingState, getOperationUrl, return pollingState.AzureOperationResponse; } + /// + /// Gets operation result for PUT and PATCH operations. + /// + /// IAzureClient + /// Response from the begin operation + /// Headers that will be added to request + /// Cancellation token + /// Operation response + public static async Task GetPutOrPatchOperationResultAsync( + this IAzureClient client, + AzureOperationResponse response, + Dictionary> customHeaders, + CancellationToken cancellationToken) + { + var newResponse = new AzureOperationResponse + { + Request = response.Request, + Response = response.Response, + RequestId = response.RequestId + }; + + var azureOperationResponse = await client.GetPutOrPatchOperationResultAsync( + newResponse, customHeaders, cancellationToken); + + return new AzureOperationResponse + { + Request = azureOperationResponse.Request, + Response = azureOperationResponse.Response, + RequestId = azureOperationResponse.RequestId + }; + } + /// /// Gets operation result for DELETE and POST operations. /// From 296bb25496b473dceb167a807ffb4ff5a7704d79 Mon Sep 17 00:00:00 2001 From: Brody Berg Date: Wed, 13 Apr 2016 09:46:39 -0700 Subject: [PATCH 2/5] Correct bug link re: multi (#939) --- AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs b/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs index edfba8a2c1340..f9ee08f3c57f6 100644 --- a/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs +++ b/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs @@ -80,7 +80,7 @@ private static void AddCollectionFormat(SwaggerParameter swaggerParameter, Strin break; case CollectionFormat.Multi: - // TODO multi is not supported yet: http://vstfrd:8080/Azure/RD/_workitems/edit/3172867 + // TODO multi is not supported yet: https://github.com/Azure/autorest/issues/717 throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Resources.MultiCollectionFormatNotSupported, swaggerParameter.Name)); From cd746ab36777f6b827d95517c43c01fb1620bbd7 Mon Sep 17 00:00:00 2001 From: Jianghao Lu Date: Fri, 15 Apr 2016 09:45:37 -0700 Subject: [PATCH 3/5] Okio 1.7.0 --- ClientRuntimes/Java/client-runtime/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ClientRuntimes/Java/client-runtime/build.gradle b/ClientRuntimes/Java/client-runtime/build.gradle index 47cbaf08c6397..b734d33608eaf 100644 --- a/ClientRuntimes/Java/client-runtime/build.gradle +++ b/ClientRuntimes/Java/client-runtime/build.gradle @@ -25,7 +25,7 @@ dependencies { compile 'com.google.guava:guava:18.0' compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' compile 'com.squareup.okhttp3:okhttp:3.2.0' - compile ('com.squareup.okio:okio:1.7.0-SNAPSHOT') { changing = true } + compile 'com.squareup.okio:okio:1.7.0' compile 'com.squareup.okhttp3:logging-interceptor:3.1.1' compile 'com.squareup.okhttp3:okhttp-urlconnection:3.1.1' compile 'com.squareup.retrofit2:converter-jackson:2.0.0-beta4' From 29dc46d8d25b5509c5883688a5475cdb1da379e2 Mon Sep 17 00:00:00 2001 From: annatisch Date: Fri, 15 Apr 2016 13:22:00 -0700 Subject: [PATCH 4/5] Python Bug Fixes (#928) * Fix serializing lists into paths * Fix for streaming bug * Generated Python config type checking * Regenerated tests * fixed streaming bug * regenerated samples * Fixed runtime tests * Test server debuging * removed stream connection closing * ping build server --- .../auto_rest_duration_test_service.py | 4 +- ...to_rest_parameter_grouping_test_service.py | 4 +- .../auto_rest_report_service_for_azure.py | 4 +- ...o_rest_resource_flattening_test_service.py | 4 +- ...st_azure_special_parameters_test_client.py | 10 ++- ...uto_rest_parameterized_host_test_client.py | 8 ++- .../auto_rest_head_test_service.py | 4 +- .../auto_rest_head_exception_test_service.py | 4 +- ...est_long_running_operation_test_service.py | 4 +- .../auto_rest_paging_test_service.py | 4 +- .../storage_management_client.py | 10 ++- .../microsoft_azure_test_url.py | 10 ++- .../AcceptanceTests/file_tests.py | 61 ++++++------------- .../AcceptanceTests/form_data_tests.py | 1 - .../Python.Tests/AcceptanceTests/url_tests.py | 5 +- .../Python.Tests/AcceptanceTests/zzz_tests.py | 43 +++++++------ .../auto_rest_complex_test_service.py | 4 +- ...uto_rest_parameterized_host_test_client.py | 4 +- ...uto_rest_required_optional_test_service.py | 8 ++- .../auto_rest_url_test_service.py | 6 +- .../operations/paths.py | 2 +- .../auto_rest_validation_test.py | 8 ++- .../TemplateModels/MethodTemplateModel.cs | 7 +++ .../ServiceClientTemplateModel.cs | 29 ++++++++- .../Python/msrest/msrest/http_logger.py | 4 +- .../Python/msrest/msrest/serialization.py | 3 +- .../Python/msrest/msrest/service_client.py | 7 ++- .../Python/msrest/test/unittest_runtime.py | 8 ++- .../storage_management_client.py | 10 ++- 29 files changed, 181 insertions(+), 99 deletions(-) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py index bceee986fdda8..668b135381e1f 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py @@ -43,7 +43,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py index b8bae0b1b5228..13e63f9569c81 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py @@ -43,7 +43,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py index b37530e7d7985..c02088e43b1a4 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py @@ -44,7 +44,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py index 3a806d13f53fc..74f09db9d3400 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py @@ -44,7 +44,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py index cc2d96c0ce719..95f2d47d0fb58 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py @@ -56,9 +56,15 @@ def __init__( self, credentials, subscription_id, api_version='2015-07-01-preview', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py index ce9c7112afaf5..79e862f82db73 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py @@ -45,9 +45,13 @@ def __init__( self, credentials, host, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if host is None: - raise ValueError('host must not be None.') + raise ValueError("Parameter 'host' must not be None.") + if not isinstance(host, str): + raise TypeError("Parameter 'host' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") base_url = 'http://{accountName}{host}' super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(base_url, filepath) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py index 85044ec1cbcc4..fc86a3308cb2e 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py @@ -42,7 +42,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py index e7531777378d2..d9745572729ef 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py @@ -42,7 +42,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py index 718b1114d10af..be1ddc0cc63c0 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py @@ -46,7 +46,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py index 532adc38d5acc..e3cf9310642ed 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py @@ -43,7 +43,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py index cd2c457915195..1334ec94142ec 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py @@ -50,9 +50,15 @@ def __init__( self, credentials, subscription_id, api_version='2015-05-01-preview', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://management.azure.com' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py index 99e3bc1f4ce98..d16f3f25706a6 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py @@ -47,9 +47,15 @@ def __init__( self, credentials, subscription_id, api_version='2014-04-01-preview', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://management.azure.com/' diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py index cc7fb8d0f5eb7..22511e8de15c7 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py @@ -53,24 +53,21 @@ class FileTests(unittest.TestCase): def test_files(self): config = AutoRestSwaggerBATFileServiceConfiguration(base_url="http://localhost:3000") - config.log_level = log_level config.connection.data_block_size = 1000 client = AutoRestSwaggerBATFileService(config) - def test_callback(data, response, progress = [0], is_response_streamed=None): + def test_callback(data, response, progress=[0]): self.assertTrue(len(data) > 0) - if not is_response_streamed: - self.assertFalse(response._content_consumed) + self.assertIsNotNone(response) + self.assertFalse(response._content_consumed) + total = float(response.headers.get('Content-Length', 0)) + if total: progress[0] += len(data) - total = float(response.headers['Content-Length']) print("Downloading... {}%".format(int(progress[0]*100/total))) - self.assertIsNotNone(response) file_length = 0 with io.BytesIO() as file_handle: - - stream = client.files.get_file(callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + stream = client.files.get_file(callback=test_callback) for data in stream: file_length += len(data) @@ -86,11 +83,10 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): sample_data = hash(data.read()) self.assertEqual(sample_data, hash(file_handle.getvalue())) + config.connection.data_block_size = 4096 file_length = 0 with io.BytesIO() as file_handle: - - stream = client.files.get_empty_file(callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + stream = client.files.get_empty_file(callback=test_callback) for data in stream: file_length += len(data) @@ -98,34 +94,30 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): self.assertEqual(file_length, 0) - #file_length = 0 - #stream = client.files.get_file_large(callback=lambda x, response, progress=[0] : - # test_callback(x, response, progress, True)) - #for data in stream: - # file_length += len(data) + file_length = 0 + stream = client.files.get_file_large(callback=test_callback) + for data in stream: + file_length += len(data) - #self.assertEqual(file_length, 3000 * 1024 * 1024) + self.assertEqual(file_length, 3000 * 1024 * 1024) def test_files_raw(self): - def test_callback(data, response, progress = [0], is_response_streamed=None): + def test_callback(data, response, progress=[0]): self.assertTrue(len(data) > 0) - if not is_response_streamed: - self.assertFalse(response._content_consumed) + self.assertIsNotNone(response) + self.assertFalse(response._content_consumed) + total = float(response.headers.get('Content-Length', 0)) + if total: progress[0] += len(data) - total = float(response.headers['Content-Length']) print("Downloading... {}%".format(int(progress[0]*100/total))) - self.assertIsNotNone(response) config = AutoRestSwaggerBATFileServiceConfiguration(base_url="http://localhost:3000") - config.log_level = log_level client = AutoRestSwaggerBATFileService(config) file_length = 0 with io.BytesIO() as file_handle: - - response = client.files.get_file(raw=True, callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + response = client.files.get_file(raw=True, callback=test_callback) stream = response.output for data in stream: @@ -144,9 +136,7 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): file_length = 0 with io.BytesIO() as file_handle: - - response = client.files.get_empty_file(raw=True, callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + response = client.files.get_empty_file(raw=True, callback=test_callback) stream = response.output for data in stream: @@ -155,16 +145,5 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): self.assertEqual(file_length, 0) - #file_length = 0 - #response = client.files.get_file_large(raw=True, callback=lambda x, response, progress=[0] : - # test_callback(x, response, progress, True)) - - #stream = response.output - - #for data in stream: - # file_length += len(data) - - #self.assertEqual(file_length, 3000 * 1024 * 1024) - if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py index f18bfdb92aa05..ea1ed1a726f9e 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py @@ -174,7 +174,6 @@ def test_callback(data, response, progress = [0]): with open(self.dummy_file, 'rb') as upload_data: resp = client.formdata.upload_file_via_body(upload_data, callback=test_callback) for r in resp: - print(r) result.write(r) self.assertEqual(result.getvalue().decode(), "Test file") diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py index 05f7b4dcdba4f..3204669e8568c 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py @@ -90,8 +90,9 @@ def test_url_path(self): self.client.paths.get_negative_ten_billion(-10000000000) self.client.paths.get_ten_billion(10000000000) self.client.paths.string_empty("") - #test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] - #self.client.paths.array_csv_in_path(test_array) + + test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] + self.client.paths.array_csv_in_path(test_array) with self.assertRaises(ValidationError): self.client.paths.string_null(None) diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py index b54157497620c..ccafa013129b1 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py @@ -54,33 +54,38 @@ def test_ensure_coverage(self): client = AutoRestReportService(config) report = client.get_report() - # These will not be supported in Python - report['getIntegerOverflow']=1 - report['getIntegerUnderflow']=1 - report['getLongOverflow']=1 - report['getLongUnderflow']=1 - report['getDateInvalid']=1 - report['getDictionaryNullkey']=1 - report['HttpRedirect300Get']=1 - - # TODO: Support large file streams - report['FileStreamVeryLarge']=1 + not_supported = { + 'getIntegerOverflow': 1, + 'getIntegerUnderflow': 1, + 'getLongOverflow': 1, + 'getLongUnderflow': 1, + 'getDateInvalid': 1, + 'getDictionaryNullkey': 1, + 'HttpRedirect300Get': 1, + } # TODO: Support ignore readonly property in http put - report['putComplexReadOnlyPropertyValid']=1 + missing_features_or_bugs = { + 'putComplexReadOnlyPropertyValid': 1, + } - skipped = [k for k, v in report.items() if v == 0] - manually_marked_successful = [k for k, v in report.items() if v == 2] - for s in manually_marked_successful: - print("SKIPPED {0}".format(s)) + report.update(not_supported) + report.update(missing_features_or_bugs) + failed = [k for k, v in report.items() if v == 0] - for s in skipped: + for s in not_supported.keys(): + print("IGNORING {0}".format(s)) + + for s in missing_features_or_bugs.keys(): + print("PENDING {0}".format(s)) + + for s in failed: print("FAILED TO EXECUTE {0}".format(s)) totalTests = len(report) - print ("The test coverage is {0}/{1}.".format(totalTests - len(skipped), totalTests)) + print ("The test coverage is {0}/{1}.".format(totalTests - len(failed), totalTests)) - self.assertEqual(0, len(skipped)) + self.assertEqual(0, len(failed)) if __name__ == '__main__': unittest.main() diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py index 8ff86db017bbd..3887687ac962c 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py @@ -38,7 +38,9 @@ def __init__( self, api_version, base_url=None, filepath=None): if api_version is None: - raise ValueError('api_version must not be None.') + raise ValueError("Parameter 'api_version' must not be None.") + if not isinstance(api_version, str): + raise TypeError("Parameter 'api_version' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py index 570afdaa95129..5839338b5a2d2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py @@ -31,7 +31,9 @@ def __init__( self, host, filepath=None): if host is None: - raise ValueError('host must not be None.') + raise ValueError("Parameter 'host' must not be None.") + if not isinstance(host, str): + raise TypeError("Parameter 'host' must be str.") base_url = 'http://{accountName}{host}' super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(base_url, filepath) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py index d9a36a8ffd5b0..7dcce131d92ad 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py @@ -36,9 +36,13 @@ def __init__( self, required_global_path, required_global_query, optional_global_query=None, base_url=None, filepath=None): if required_global_path is None: - raise ValueError('required_global_path must not be None.') + raise ValueError("Parameter 'required_global_path' must not be None.") + if not isinstance(required_global_path, str): + raise TypeError("Parameter 'required_global_path' must be str.") if required_global_query is None: - raise ValueError('required_global_query must not be None.') + raise ValueError("Parameter 'required_global_query' must not be None.") + if not isinstance(required_global_query, str): + raise TypeError("Parameter 'required_global_query' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py index 31c1880929875..34efde192fd6b 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py @@ -36,7 +36,11 @@ def __init__( self, global_string_path, global_string_query=None, base_url=None, filepath=None): if global_string_path is None: - raise ValueError('global_string_path must not be None.') + raise ValueError("Parameter 'global_string_path' must not be None.") + if not isinstance(global_string_path, str): + raise TypeError("Parameter 'global_string_path' must be str.") + if global_string_query is not None and not isinstance(global_string_query, str): + raise TypeError("Optional parameter 'global_string_query' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py index 46bface0d9375..97cd8878c0e6a 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py @@ -1089,7 +1089,7 @@ def array_csv_in_path( if raw=true """ # 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:commaSeparated}' + 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': self._serialize.url("array_path", array_path, '[str]', div=',') } diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py index 7fd4093d00b6e..f9a6b88ede469 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py @@ -34,9 +34,13 @@ def __init__( self, subscription_id, api_version, base_url=None, filepath=None): if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") if api_version is None: - raise ValueError('api_version must not be None.') + raise ValueError("Parameter 'api_version' must not be None.") + if not isinstance(api_version, str): + raise TypeError("Parameter 'api_version' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs index 5c47e7be1f83c..0555d5cd4434e 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs @@ -6,6 +6,7 @@ using System.Globalization; using System.Linq; using System.Net; +using System.Text.RegularExpressions; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Python.TemplateModels; using Microsoft.Rest.Generator.Utilities; @@ -31,6 +32,12 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) OperationName = serviceClient.Name; } AddCustomHeader = true; + string formatter; + foreach (Match m in Regex.Matches(Url, @"\{[\w]+:[\w]+\}")) + { + formatter = m.Value.Split(':').First() + '}'; + Url = Url.Replace(m.Value, formatter); + } } public bool AddCustomHeader { get; private set; } diff --git a/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs index 4eb487cdfdee5..60629ea26ca28 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs @@ -105,7 +105,10 @@ public virtual string RequiredConstructorParameters } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ValueError"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ValueError"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TypeError"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "str"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)")] public virtual string ValidateRequiredParameters { get @@ -118,9 +121,31 @@ public virtual string ValidateRequiredParameters builder. AppendFormat("if {0} is None:", property.Name.ToPythonCase()).AppendLine(). Indent(). - AppendLine(string.Format(CultureInfo.InvariantCulture, "raise ValueError('{0} must not be None.')", property.Name.ToPythonCase())). + AppendLine(string.Format(CultureInfo.InvariantCulture, "raise ValueError(\"Parameter '{0}' must not be None.\")", property.Name.ToPythonCase())). Outdent(); + if (property.Type.IsPrimaryType(KnownPrimaryType.String)) + { + builder. + AppendFormat("if not isinstance({0}, str):", property.Name.ToPythonCase()).AppendLine(). + Indent(). + AppendLine(string.Format(CultureInfo.InvariantCulture, "raise TypeError(\"Parameter '{0}' must be str.\")", property.Name.ToPythonCase())). + Outdent(); + } } + else + { + if (property.Type.IsPrimaryType(KnownPrimaryType.String)) + { + builder. + AppendFormat("if {0} is not None and not isinstance({0}, str):", property.Name.ToPythonCase()).AppendLine(). + Indent(). + AppendLine(string.Format(CultureInfo.InvariantCulture, "raise TypeError(\"Optional parameter '{0}' must be str.\")", property.Name.ToPythonCase())). + Outdent(); + } + + } + + } return builder.ToString(); } diff --git a/ClientRuntimes/Python/msrest/msrest/http_logger.py b/ClientRuntimes/Python/msrest/msrest/http_logger.py index b19405528cf96..5159a996a6e8f 100644 --- a/ClientRuntimes/Python/msrest/msrest/http_logger.py +++ b/ClientRuntimes/Python/msrest/msrest/http_logger.py @@ -81,8 +81,8 @@ def log_response(adapter, request, response, *args, **kwargs): _LOGGER.debug("Body contains binary data.") elif result.headers.get("content-type", "").startswith("image"): _LOGGER.debug("Body contains image data.") - # elif result.headers.get("transfer-encoding") == 'chunked': - # LOGGER.debug("Body contains chunked data.") + elif result.headers.get("transfer-encoding") == 'chunked': + _LOGGER.debug("Body contains chunked data.") else: _LOGGER.debug(str(result.content)) return result diff --git a/ClientRuntimes/Python/msrest/msrest/serialization.py b/ClientRuntimes/Python/msrest/msrest/serialization.py index 40f4c88578686..25aff136d1538 100644 --- a/ClientRuntimes/Python/msrest/msrest/serialization.py +++ b/ClientRuntimes/Python/msrest/msrest/serialization.py @@ -406,7 +406,8 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialized.append(None) if div: - return div.join(serialized) + serialized = ['' if s is None else s for s in serialized] + serialized = div.join(serialized) return serialized def serialize_dict(self, attr, dict_type, **kwargs): diff --git a/ClientRuntimes/Python/msrest/msrest/service_client.py b/ClientRuntimes/Python/msrest/msrest/service_client.py index 523c6648582f1..6c27b017e111a 100644 --- a/ClientRuntimes/Python/msrest/msrest/service_client.py +++ b/ClientRuntimes/Python/msrest/msrest/service_client.py @@ -146,7 +146,7 @@ def send_formdata(self, request, headers={}, content={}, **config): :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param dict content: Dictionary of the fields of the formdata. - :param config: Any specific config overrides + :param config: Any specific config overrides. """ file_data = {f: self._format_data(d) for f, d in content.items()} try: @@ -163,6 +163,7 @@ def send(self, request, headers=None, content=None, **config): :param content: Any body data to add to the request. :param config: Any specific config overrides """ + response = None session = self.creds.signed_session() kwargs = self._configure_session(session, **config) @@ -204,7 +205,8 @@ def send(self, request, headers=None, content=None, **config): msg = "Error occurred in request." raise_with_traceback(ClientRequestError, msg, err) finally: - session.close() + if not response or response._content_consumed: + session.close() def stream_download(self, data, callback): """Generator for streaming request body data. @@ -228,7 +230,6 @@ def stream_download(self, data, callback): if callback and callable(callback): callback(chunk, response=data) yield chunk - data.close() def stream_upload(self, data, callback): """Generator for streaming request body data. diff --git a/ClientRuntimes/Python/msrest/test/unittest_runtime.py b/ClientRuntimes/Python/msrest/test/unittest_runtime.py index 7bb798d5af6d4..fbdad6791f772 100644 --- a/ClientRuntimes/Python/msrest/test/unittest_runtime.py +++ b/ClientRuntimes/Python/msrest/test/unittest_runtime.py @@ -101,7 +101,7 @@ def hook(aptr, req, *args, **kwargs): @mock.patch.object(requests, 'Session') def test_request_fail(self, mock_requests): - mock_requests.return_value.request.return_value = "test" + mock_requests.return_value.request.return_value = mock.Mock(_content_consumed=True) cfg = Configuration("https://my_service.com") creds = Authentication() @@ -113,7 +113,7 @@ def test_request_fail(self, mock_requests): check = httpretty.last_request() - self.assertEqual(response, "test") + self.assertTrue(response._content_consumed) mock_requests.return_value.request.side_effect = requests.RequestException with self.assertRaises(ClientRequestError): @@ -127,6 +127,8 @@ def test_request_proxy(self): def hook(adptr, request, *args, **kwargs): self.assertEqual(kwargs.get('proxies'), {"http://my_service.com":'http://localhost:57979'}) + kwargs['result']._content_consumed = True + kwargs['result'].status_code = 200 return kwargs['result'] client = ServiceClient(creds, cfg) @@ -139,6 +141,8 @@ def hook(adptr, request, *args, **kwargs): def hook2(adptr, request, *args, **kwargs): self.assertEqual(kwargs.get('proxies')['https'], "http://localhost:1987") + kwargs['result']._content_consumed = True + kwargs['result'].status_code = 200 return kwargs['result'] cfg = Configuration("http://my_service.com") diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py index 732eb30e70fb2..00031c87fca75 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py @@ -43,9 +43,15 @@ def __init__( self, credentials, subscription_id, api_version='2015-06-15', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://management.azure.com' From 91d73c6bd81deebe2fd83090d60d63f38a08932a Mon Sep 17 00:00:00 2001 From: annatisch Date: Fri, 15 Apr 2016 16:19:30 -0700 Subject: [PATCH 5/5] Python Streaming Test Fix (#953) * Debugging test failure * testing without header * Adding header back again --- .../Python/Python.Tests/AcceptanceTests/file_tests.py | 8 ++++++-- ClientRuntimes/Python/msrest/msrest/service_client.py | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py index 22511e8de15c7..c45c3e0db6836 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py @@ -60,8 +60,8 @@ def test_callback(data, response, progress=[0]): self.assertTrue(len(data) > 0) self.assertIsNotNone(response) self.assertFalse(response._content_consumed) - total = float(response.headers.get('Content-Length', 0)) - if total: + total = float(response.headers['Content-Length']) + if total < 4096: progress[0] += len(data) print("Downloading... {}%".format(int(progress[0]*100/total))) @@ -94,7 +94,11 @@ def test_callback(data, response, progress=[0]): self.assertEqual(file_length, 0) + def add_headers(adapter, request, response, *args, **kwargs): + response.headers['Content-Length'] = str(3000 * 1024 * 1024) + file_length = 0 + client._client.add_hook('response', add_headers) stream = client.files.get_file_large(callback=test_callback) for data in stream: file_length += len(data) diff --git a/ClientRuntimes/Python/msrest/msrest/service_client.py b/ClientRuntimes/Python/msrest/msrest/service_client.py index 6c27b017e111a..a204089838ddc 100644 --- a/ClientRuntimes/Python/msrest/msrest/service_client.py +++ b/ClientRuntimes/Python/msrest/msrest/service_client.py @@ -230,6 +230,8 @@ def stream_download(self, data, callback): if callback and callable(callback): callback(chunk, response=data) yield chunk + data.close() + self._adapter.close() def stream_upload(self, data, callback): """Generator for streaming request body data.