From 5153d9e19fd890c174be51cc0ac6ae807f54f2b2 Mon Sep 17 00:00:00 2001 From: Thomas Adamcik Date: Tue, 28 Apr 2015 23:51:19 +0200 Subject: [PATCH] utils: Add format_user_agent helper --- mopidy/utils/http.py | 20 ++++++++++++++++++++ tests/utils/test_http.py | 11 +++++++++++ 2 files changed, 31 insertions(+) diff --git a/mopidy/utils/http.py b/mopidy/utils/http.py index bc6d38f4..f0c658e7 100644 --- a/mopidy/utils/http.py +++ b/mopidy/utils/http.py @@ -1,5 +1,11 @@ from __future__ import unicode_literals +import platform + +import mopidy + +"Helpers for configuring HTTP clients used in Mopidy extensions." + def format_proxy(proxy_config): """Convert a Mopidy proxy config to the commonly used proxy string format. @@ -23,3 +29,17 @@ def format_proxy(proxy_config): username=proxy_config.get('username'), password=proxy_config.get('password'), hostname=proxy_config['hostname'], port=port) + + +def format_user_agent(name=None): + """Construct a User-Agent suitable for use in client code. + + This will identify use by the provided name (which should be + ``dist_name/version``), Mopidy version and Python version. + """ + parts = ['Mopidy/%s' % (mopidy.__version__), + '%s/%s' % (platform.python_implementation(), + platform.python_version())] + if name: + parts.insert(0, name) + return ' '.join(parts) diff --git a/tests/utils/test_http.py b/tests/utils/test_http.py index b63ebf31..cf97e57c 100644 --- a/tests/utils/test_http.py +++ b/tests/utils/test_http.py @@ -1,5 +1,7 @@ from __future__ import unicode_literals +import re + import pytest from mopidy.utils import http @@ -18,3 +20,12 @@ from mopidy.utils import http ]) def test_format_proxy(config, expected): assert http.format_proxy(config) == expected + + +@pytest.mark.parametrize("name,expected", [ + (None, r'^Mopidy/[^ ]+ CPython|/[^ ]+$'), + ('Foo', r'^Foo Mopidy/[^ ]+ CPython|/[^ ]+$'), + ('Foo/1.2.3', r'^Foo/1.2.3 Mopidy/[^ ]+ CPython|/[^ ]+$'), +]) +def test_format_user_agent(name, expected): + assert re.match(expected, http.format_user_agent(name))