From d18aefc629b73586a2fc11a081c64073b3ee3d1e Mon Sep 17 00:00:00 2001 From: "Alex Martin (Contexte)" <32698524+alexandreMartinEcl@users.noreply.github.com> Date: Tue, 7 May 2024 21:41:46 +0200 Subject: [PATCH] fix: make template_loader consider tuples for STATICFILES_DIRS (#489) Co-authored-by: Juro Oravec --- src/django_components/template_loader.py | 10 ++++++++++ tests/test_autodiscover.py | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/django_components/template_loader.py b/src/django_components/template_loader.py index ea897b88..ae8ab3f1 100644 --- a/src/django_components/template_loader.py +++ b/src/django_components/template_loader.py @@ -37,6 +37,16 @@ class Loader(FilesystemLoader): directories: Set[Path] = set() for component_dir in component_dirs: + if isinstance(component_dir, (tuple, list)) and len(component_dir) == 2: + component_dir = component_dir[1] + try: + Path(component_dir) + except TypeError: + logger.warning( + f"STATICFILES_DIRS expected str, bytes or os.PathLike object, or tuple/list of length 2. " + f"See Django documentation. Got {type(component_dir)} : {component_dir}" + ) + continue curr_directories: Set[Path] = set() # For each dir in `settings.STATICFILES_DIRS`, we go over all Django apps diff --git a/tests/test_autodiscover.py b/tests/test_autodiscover.py index 9abde896..ff06eb54 100644 --- a/tests/test_autodiscover.py +++ b/tests/test_autodiscover.py @@ -1,5 +1,6 @@ from pathlib import Path from unittest import mock +from unittest.mock import MagicMock, patch from django.template.engine import Engine from django.urls import include, path @@ -125,6 +126,29 @@ class TestBaseDir(BaseTestCase): self.assertEqual(sorted(dirs), sorted(expected)) +class TestStaticFilesDirs(BaseTestCase): + def setUp(self): + settings.STATICFILES_DIRS = [ + "components", + ("with_alias", "components"), + ("too_many", "items", "components"), + ("with_not_str_alias", 3), + ] # noqa + + def tearDown(self) -> None: + del settings.STATICFILES_DIRS # noqa + + @patch("django_components.template_loader.logger.warning") + def test_static_files_dirs(self, mock_warning: MagicMock): + mock_warning.reset_mock() + current_engine = Engine.get_default() + Loader(current_engine).get_dirs() + + warn_inputs = [warn.args[0] for warn in mock_warning.call_args_list] + assert "Got : ('too_many', 'items', 'components')" in warn_inputs[0] + assert "Got : 3" in warn_inputs[1] + + class TestFilepathToPythonModule(BaseTestCase): def test_prepares_path(self): self.assertEqual(