Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fail fast on invalid Jinja2Template instantiation parameters #2568

Merged
merged 2 commits into from
Apr 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion starlette/templating.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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