Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core add user agent #9355

Merged
merged 11 commits into from
Jan 14, 2020
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions sdk/core/azure-core/azure/core/pipeline/policies/_universal.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,9 @@ class UserAgentPolicy(SansIOHTTPPolicy):

:keyword bool user_agent_overwrite: Overwrites User-Agent when True. Defaults to False.
:keyword bool user_agent_use_env: Gets user-agent from environment. Defaults to True.
:keyword str user_agent: If specified, this will be added in front of the user agent string.
:keyword str sdk_moniker: If specified, the user agent string will be
azsdk-python-[sdk_moniker] Python/[python_version] ([platform_version])

.. admonition:: Example:

Expand All @@ -178,18 +181,23 @@ class UserAgentPolicy(SansIOHTTPPolicy):
_ENV_ADDITIONAL_USER_AGENT = 'AZURE_HTTP_USER_AGENT'

def __init__(self, base_user_agent=None, **kwargs): # pylint: disable=super-init-not-called
# type: (Optional[str], bool) -> None
# type: (Optional[str], **Any) -> None
self.overwrite = kwargs.pop('user_agent_overwrite', False)
self.use_env = kwargs.pop('user_agent_use_env', True)
application_id = kwargs.pop('user_agent', None)
sdk_moniker = kwargs.pop('sdk_moniker', 'core/{}'.format(azcore_version))
johanste marked this conversation as resolved.
Show resolved Hide resolved

if base_user_agent is None:
self._user_agent = "azsdk-python-core/{} Python/{} ({})".format(
azcore_version,
if base_user_agent:
self._user_agent = base_user_agent
else:
self._user_agent = "azsdk-python-{} Python/{} ({})".format(
sdk_moniker,
platform.python_version(),
platform.platform()
)
else:
self._user_agent = base_user_agent

if application_id:
self._user_agent = "{} {}".format(application_id, self._user_agent)

@property
def user_agent(self):
Expand Down Expand Up @@ -222,7 +230,7 @@ def on_request(self, request):
if options_dict.pop('user_agent_overwrite', self.overwrite):
http_request.headers[self._USERAGENT] = user_agent
else:
user_agent = "{} {}".format(self.user_agent, user_agent)
user_agent = "{} {}".format(user_agent, self.user_agent)
bryevdv marked this conversation as resolved.
Show resolved Hide resolved
http_request.headers[self._USERAGENT] = user_agent

elif self.overwrite or self._USERAGENT not in http_request.headers:
Expand Down
10 changes: 0 additions & 10 deletions sdk/core/azure-core/tests/test_universal_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,6 @@
HTTPPolicy,
)

def test_user_agent():

with mock.patch.dict('os.environ', {'AZURE_HTTP_USER_AGENT': "mytools"}):
policy = UserAgentPolicy(None)
assert policy.user_agent.endswith("mytools")

request = HttpRequest('GET', 'http://127.0.0.1/')
policy.on_request(PipelineRequest(request, PipelineContext(None)))
assert request.headers["user-agent"].endswith("mytools")

def test_request_history():
class Non_deep_copiable(object):
def __deepcopy__(self, memodict={}):
Expand Down
40 changes: 40 additions & 0 deletions sdk/core/azure-core/tests/test_user_agent_policy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
"""Tests for the user agent policy."""
from azure.core.pipeline.policies import UserAgentPolicy
from azure.core.pipeline.transport import HttpRequest
from azure.core.pipeline import PipelineRequest, PipelineContext
try:
from unittest import mock
except ImportError:
import mock

def test_user_agent_policy():
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved
user_agent = UserAgentPolicy(base_user_agent='foo')
assert user_agent._user_agent == 'foo'

user_agent = UserAgentPolicy(sdk_moniker='foosdk/1.0.0')
assert user_agent._user_agent.startswith('azsdk-python-foosdk/1.0.0 Python')

user_agent = UserAgentPolicy(base_user_agent='foo', user_agent='bar', user_agent_use_env=False)
assert user_agent._user_agent == 'bar foo'

request = HttpRequest('GET', 'http://127.0.0.1/')
pipeline_request = PipelineRequest(request, PipelineContext(None))

pipeline_request.context.options['user_agent'] = 'xyz'
user_agent.on_request(pipeline_request)
assert request.headers['User-Agent'] == 'xyz bar foo'
xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved


def test_user_agent_environ():

with mock.patch.dict('os.environ', {'AZURE_HTTP_USER_AGENT': "mytools"}):
policy = UserAgentPolicy(None)
assert policy.user_agent.endswith("mytools")

request = HttpRequest('GET', 'http://127.0.0.1/')
policy.on_request(PipelineRequest(request, PipelineContext(None)))
assert request.headers["user-agent"].endswith("mytools")