Skip to content

Commit

Permalink
Fail fast on invalid Jinja2Template instantiation parameters (#2568)
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
pdelagrave committed Apr 20, 2024
1 parent 9bd1b81 commit 9cf26ee
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
4 changes: 3 additions & 1 deletion starlette/templating.py
Expand Up @@ -104,7 +104,9 @@ def __init__(
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)
Expand Down
7 changes: 7 additions & 0 deletions tests/test_templates.py
Expand Up @@ -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:
Expand Down

0 comments on commit 9cf26ee

Please sign in to comment.