Skip to content

Commit

Permalink
Url fix (#5472) (#5473)
Browse files Browse the repository at this point in the history
* Use urljoin function to construct absolute URL

* Add unit test

(cherry picked from commit 8da5d62)

Co-authored-by: Oliver <oliver.henry.walters@gmail.com>
  • Loading branch information
github-actions[bot] and SchrodingersGat committed Aug 24, 2023
1 parent 942bc53 commit 72464c5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
10 changes: 2 additions & 8 deletions InvenTree/InvenTree/helpers_model.py
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
28 changes: 28 additions & 0 deletions InvenTree/InvenTree/tests.py
Expand Up @@ -233,6 +233,34 @@ def test_extract_value(self):
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']:
Expand Down

0 comments on commit 72464c5

Please sign in to comment.