From 72464c50cc0ca176c304718b19ebb825bad4836a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Thu, 24 Aug 2023 16:04:42 +1000 Subject: [PATCH] Url fix (#5472) (#5473) * Use urljoin function to construct absolute URL * Add unit test (cherry picked from commit 8da5d62c6983addbe04a4c0aae4eddac91d873d1) Co-authored-by: Oliver --- InvenTree/InvenTree/helpers_model.py | 10 ++-------- InvenTree/InvenTree/tests.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) 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']: