utils: Add basic format proxy helper

This commit is contained in:
Thomas Adamcik 2015-04-28 23:29:55 +02:00
parent 8851fb151c
commit a48aadaaed
2 changed files with 45 additions and 0 deletions

25
mopidy/utils/http.py Normal file
View File

@ -0,0 +1,25 @@
from __future__ import unicode_literals
def format_proxy(proxy_config):
"""Convert a Mopidy proxy config to the commonly used proxy string format.
Outputs ``scheme://host:port``, ``scheme://user:pass@host:port`` or
:class:`None` depending on the proxy config provided.
"""
if not proxy_config.get('hostname'):
return None
if proxy_config.get('username') and proxy_config.get('password'):
template = '{scheme}://{username}:{password}@{hostname}:{port}'
else:
template = '{scheme}://{hostname}:{port}'
port = proxy_config.get('port', 80)
if port < 0:
port = 80
return template.format(scheme=proxy_config.get('scheme', 'http'),
username=proxy_config.get('username'),
password=proxy_config.get('password'),
hostname=proxy_config['hostname'], port=port)

20
tests/utils/test_http.py Normal file
View File

@ -0,0 +1,20 @@
from __future__ import unicode_literals
import pytest
from mopidy.utils import http
@pytest.mark.parametrize("config,expected", [
({}, None),
({'hostname': 'proxy.lan'}, 'http://proxy.lan:80'),
({'scheme': 'https', 'hostname': 'proxy.lan'}, 'https://proxy.lan:80'),
({'username': 'user', 'hostname': 'proxy.lan'}, 'http://proxy.lan:80'),
({'password': 'pass', 'hostname': 'proxy.lan'}, 'http://proxy.lan:80'),
({'hostname': 'proxy.lan', 'port': 8080}, 'http://proxy.lan:8080'),
({'hostname': 'proxy.lan', 'port': -1}, 'http://proxy.lan:80'),
({'username': 'user', 'password': 'pass', 'hostname': 'proxy.lan'},
'http://user:pass@proxy.lan:80'),
])
def test_format_proxy(config, expected):
assert http.format_proxy(config) == expected