From 49ed7eb64d092684dbb3f6666d0518b4a1db6a09 Mon Sep 17 00:00:00 2001 From: Erika-Dsouza Date: Fri, 15 Mar 2019 15:26:09 -0400 Subject: [PATCH] fix(user-agent): Add user agent header only if not set --- ibm_cloud_sdk_core/base_service.py | 11 +++++++---- test/test_base_service.py | 12 ++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/ibm_cloud_sdk_core/base_service.py b/ibm_cloud_sdk_core/base_service.py index 6018c2c..b2a410b 100644 --- a/ibm_cloud_sdk_core/base_service.py +++ b/ibm_cloud_sdk_core/base_service.py @@ -276,15 +276,18 @@ def set_http_config(self, http_config): def request(self, method, url, accept_json=False, headers=None, params=None, json=None, data=None, files=None, **kwargs): full_url = self.url + url - input_headers = remove_null_values(headers) if headers else {} - input_headers = cleanup_values(input_headers) - headers = CaseInsensitiveDict(self.user_agent_header) + headers = CaseInsensitiveDict(headers) + headers = remove_null_values(headers) + headers = cleanup_values(headers) + if self.default_headers is not None: headers.update(self.default_headers) if accept_json: headers['accept'] = 'application/json' - headers.update(input_headers) + + if not any(key in headers for key in ['user-agent', 'User-Agent']): + headers.update(self.user_agent_header) # Remove keys with None values params = remove_null_values(params) diff --git a/test/test_base_service.py b/test/test_base_service.py index e51dcb0..14d7c07 100644 --- a/test/test_base_service.py +++ b/test/test_base_service.py @@ -356,8 +356,20 @@ def test_default_headers(): with pytest.raises(TypeError): service.set_default_headers('xxx') +@responses.activate def test_user_agent_header(): service = AnyServiceV1('2018-11-20', username='username', password='password') user_agent_header = service.get_user_agent_header() assert user_agent_header is not None assert user_agent_header['User-Agent'] is not None + + responses.add(responses.GET, + 'https://gateway.watsonplatform.net/test/api', + status=200, + body=json.dumps({'foo': 'bar'}), + content_type='application/json') + response = service.request('GET', url='', headers={'user-agent': 'my_user_agent'}) + assert response.get_result().request.headers.__getitem__('user-agent') == 'my_user_agent' + + response = service.request('GET', url='', headers=None) + assert response.get_result().request.headers.__getitem__('user-agent') == user_agent_header['User-Agent']