]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Fail fast on invalid `Jinja2Template` instantiation parameters (#2568)
authorPierre Delagrave <pierre.delagrave@dialogue.co>
Sat, 20 Apr 2024 07:54:26 +0000 (03:54 -0400)
committerGitHub <noreply@github.com>
Sat, 20 Apr 2024 07:54:26 +0000 (07:54 +0000)
Calling `Jinja2Template()` with both `directory` and `env` shouldn't be allowed. When both parameters were used, the passed `env` was silently ignored in favor of creating a new one with the provided `directory` and the deprecated `env_options`.

starlette/templating.py
tests/test_templates.py

index 2dc3a5930d2a28a372eb7d8b642191038b427750..01af5e9bb01f8ab579954064d87ea946114716f3 100644 (file)
@@ -104,7 +104,9 @@ class Jinja2Templates:
                 DeprecationWarning,
             )
         assert jinja2 is not None, "jinja2 must be installed to use Jinja2Templates"
-        assert directory or env, "either 'directory' or 'env' arguments must be passed"
+        assert bool(directory) ^ bool(
+            env
+        ), "either 'directory' or 'env' arguments must be passed"
         self.context_processors = context_processors or []
         if directory is not None:
             self.env = self._create_env(directory, **env_options)
index 95e392ed5a7e988c935b9d2dc594ab4f50b1266d..10a1366bc00184ca0ade9ced958501c1b0f1bd75 100644 (file)
@@ -143,6 +143,13 @@ def test_templates_require_directory_or_environment() -> None:
         Jinja2Templates()  # type: ignore[call-overload]
 
 
+def test_templates_require_directory_or_enviroment_not_both() -> None:
+    with pytest.raises(
+        AssertionError, match="either 'directory' or 'env' arguments must be passed"
+    ):
+        Jinja2Templates(directory="dir", env=jinja2.Environment())
+
+
 def test_templates_with_directory(tmpdir: Path) -> None:
     path = os.path.join(tmpdir, "index.html")
     with open(path, "w") as file: