Skip to content

Commit

Permalink
fix(user-agent): Add user agent header only if not set
Browse files Browse the repository at this point in the history
  • Loading branch information
ehdsouza committed Mar 15, 2019
1 parent 416dd82 commit 49ed7eb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
11 changes: 7 additions & 4 deletions ibm_cloud_sdk_core/base_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions test/test_base_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']

0 comments on commit 49ed7eb

Please sign in to comment.