diff --git a/InvenTree/InvenTree/helpers_model.py b/InvenTree/InvenTree/helpers_model.py index 9a2f8fb77a..f0d797b2c2 100644 --- a/InvenTree/InvenTree/helpers_model.py +++ b/InvenTree/InvenTree/helpers_model.py @@ -3,6 +3,7 @@ import io import logging from decimal import Decimal +from urllib.parse import urljoin from django.conf import settings from django.core.validators import URLValidator @@ -64,14 +65,7 @@ def construct_absolute_url(*arg, **kwargs): # No site URL available, return the relative URL return relative_url - # Strip trailing slash from base url - if site_url.endswith('/'): - site_url = site_url[:-1] - - if relative_url.startswith('/'): - relative_url = relative_url[1:] - - return f"{site_url}/{relative_url}" + return urljoin(site_url, relative_url) def get_base_url(**kwargs): diff --git a/InvenTree/InvenTree/tests.py b/InvenTree/InvenTree/tests.py index a68f7c4739..fd6f4f3693 100644 --- a/InvenTree/InvenTree/tests.py +++ b/InvenTree/InvenTree/tests.py @@ -233,6 +233,34 @@ class FormatTest(TestCase): class TestHelpers(TestCase): """Tests for InvenTree helper functions.""" + def test_absolute_url(self): + """Test helper function for generating an absolute URL""" + + base = "https://demo.inventree.org:12345" + + InvenTreeSetting.set_setting('INVENTREE_BASE_URL', base, change_user=None) + + tests = { + "": base, + "api/": base + "/api/", + "/api/": base + "/api/", + "api": base + "/api", + "media/label/output/": base + "/media/label/output/", + "static/logo.png": base + "/static/logo.png", + "https://www.google.com": "https://www.google.com", + "https://demo.inventree.org:12345/out.html": "https://demo.inventree.org:12345/out.html", + "https://demo.inventree.org/test.html": "https://demo.inventree.org/test.html", + "http://www.cwi.nl:80/%7Eguido/Python.html": "http://www.cwi.nl:80/%7Eguido/Python.html", + "test.org": base + "/test.org", + } + + for url, expected in tests.items(): + # Test with supplied base URL + self.assertEqual(InvenTree.helpers_model.construct_absolute_url(url, site_url=base), expected) + + # Test without supplied base URL + self.assertEqual(InvenTree.helpers_model.construct_absolute_url(url), expected) + def test_image_url(self): """Test if a filename looks like an image.""" for name in ['ape.png', 'bat.GiF', 'apple.WeBP', 'BiTMap.Bmp']: