2
0
mirror of https://github.com/inventree/InvenTree.git synced 2025-04-30 12:36:45 +00:00
* Use urljoin function to construct absolute URL

* Add unit test

(cherry picked from commit 8da5d62c6983addbe04a4c0aae4eddac91d873d1)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
This commit is contained in:
github-actions[bot] 2023-08-24 16:04:42 +10:00 committed by GitHub
parent 942bc5350d
commit 72464c50cc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 8 deletions

View File

@ -3,6 +3,7 @@
import io import io
import logging import logging
from decimal import Decimal from decimal import Decimal
from urllib.parse import urljoin
from django.conf import settings from django.conf import settings
from django.core.validators import URLValidator from django.core.validators import URLValidator
@ -64,14 +65,7 @@ def construct_absolute_url(*arg, **kwargs):
# No site URL available, return the relative URL # No site URL available, return the relative URL
return relative_url return relative_url
# Strip trailing slash from base url return urljoin(site_url, relative_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}"
def get_base_url(**kwargs): def get_base_url(**kwargs):

View File

@ -233,6 +233,34 @@ class FormatTest(TestCase):
class TestHelpers(TestCase): class TestHelpers(TestCase):
"""Tests for InvenTree helper functions.""" """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): def test_image_url(self):
"""Test if a filename looks like an image.""" """Test if a filename looks like an image."""
for name in ['ape.png', 'bat.GiF', 'apple.WeBP', 'BiTMap.Bmp']: for name in ['ape.png', 'bat.GiF', 'apple.WeBP', 'BiTMap.Bmp']: