diff --git a/starlette/templating.py b/starlette/templating.py index 2dc3a5930..01af5e9bb 100644 --- a/starlette/templating.py +++ b/starlette/templating.py @@ -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) diff --git a/tests/test_templates.py b/tests/test_templates.py index 95e392ed5..10a1366bc 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -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: