Skip to content

Commit

Permalink
Add custom user agent
Browse files Browse the repository at this point in the history
  • Loading branch information
vkWeb committed Sep 11, 2023
1 parent 7ed1215 commit 0a9133d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,9 @@ target/
# celery beat schedule file
celerybeat-schedule

# dotenv
# dotenv, envrc
.env
.envrc

# virtualenv
venv/
Expand Down
11 changes: 11 additions & 0 deletions morango/sync/session.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import logging

from requests import exceptions
from morango import __version__
from requests.sessions import Session
from requests.utils import super_len
from requests.packages.urllib3.util.url import parse_url

from morango.utils import serialize_capabilities_to_client_request
from morango.utils import SETTINGS


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -35,6 +37,15 @@ class SessionWrapper(Session):
bytes_sent = 0
bytes_received = 0

def __init__(self):
super(SessionWrapper, self).__init__()
user_agent_header = "morango/{}".format(__version__)
if SETTINGS.CUSTOM_INSTANCE_INFO is not None:
instances = list(SETTINGS.CUSTOM_INSTANCE_INFO)
if instances:
user_agent_header += " " + "{}/{}".format(instances[0], SETTINGS.CUSTOM_INSTANCE_INFO.get(instances[0]))
self.headers["User-Agent"] = "{} {}".format(user_agent_header, self.headers["User-Agent"])

def request(self, method, url, **kwargs):
response = None
try:
Expand Down
13 changes: 13 additions & 0 deletions tests/testapp/tests/sync/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@ def test_request(self, mocked_super_request):
head_length = len("HTTP/1.1 200 OK") + _length_of_headers(headers)
self.assertEqual(wrapper.bytes_received, 1024 + head_length)

def test_request_user_agent(self):
from morango import __version__ as morango_version
from requests import __version__ as requests_version

wrapper = SessionWrapper()
expected_user_agent = "morango/{} python-requests/{}".format(morango_version, requests_version)
self.assertEqual(wrapper.headers["User-Agent"], expected_user_agent)

with self.settings(CUSTOM_INSTANCE_INFO={"kolibri": "0.16.0"}):
wrapper = SessionWrapper()
expected_user_agent = "morango/{} kolibri/0.16.0 python-requests/{}".format(morango_version, requests_version)
self.assertEqual(wrapper.headers["User-Agent"], expected_user_agent)

@mock.patch("morango.sync.session.logger")
@mock.patch("morango.sync.session.Session.request")
def test_request__not_ok(self, mocked_super_request, mocked_logger):
Expand Down

0 comments on commit 0a9133d

Please sign in to comment.