diff --git a/picard/webservice/__init__.py b/picard/webservice/__init__.py index fd43304ec..1a277ccba 100644 --- a/picard/webservice/__init__.py +++ b/picard/webservice/__init__.py @@ -105,6 +105,28 @@ def hostkey_from_url(url): return (url.host(), port_from_qurl(url)) +def host_port_to_url(host, port, path=None, scheme=None, as_string=False): + """Convert host & port (with optional path and scheme) to an URL""" + url = QUrl() + if scheme is None: + if port == 443: + scheme = 'https' + else: + scheme = 'http' + url.setScheme(scheme) + + if ((scheme == 'https' and port != 443) + or (scheme == 'http' and port != 80)): + url.setPort(port) + + url.setHost(host) + + if path is not None: + url.setPath(path) + + return url.toString() if as_string else url + + class WSRequest(QNetworkRequest): """Represents a single HTTP request.""" _access_token = None diff --git a/test/test_webservice.py b/test/test_webservice.py index 447bffc70..ff0bf55ea 100644 --- a/test/test_webservice.py +++ b/test/test_webservice.py @@ -44,6 +44,7 @@ from picard.webservice import ( UnknownResponseParserError, WebService, WSRequest, + host_port_to_url, hostkey_from_url, port_from_qurl, ratecontrol, @@ -558,3 +559,18 @@ class MiscWebServiceTest(PicardTestCase): def test_hostkey_from_url_https_other(self): self.assertEqual(hostkey_from_url('https://example.org:666'), ('example.org', 666)) + + def test_host_port_to_url_http_80(self): + self.assertEqual(host_port_to_url('example.org', 80, as_string=True), 'http://example.org') + + def test_host_port_to_url_http_80_qurl(self): + self.assertEqual(host_port_to_url('example.org', 80).toString(), 'http://example.org') + + def test_host_port_to_url_https_443(self): + self.assertEqual(host_port_to_url('example.org', 443, as_string=True), 'https://example.org') + + def test_host_port_to_url_https_scheme_80(self): + self.assertEqual(host_port_to_url('example.org', 80, scheme='https', as_string=True), 'https://example.org:80') + + def test_host_port_to_url_http_666_with_path(self): + self.assertEqual(host_port_to_url('example.org', 666, path='/abc', as_string=True), 'http://example.org:666/abc')