Skip to content

Commit

Permalink
Test for jinja2_environment_from_request, refs #2225
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Jan 5, 2024
1 parent 8beff57 commit 17993a3
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions tests/test_plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from datasette.utils.sqlite import sqlite3
from datasette.utils import CustomRow, StartupError
from jinja2.environment import Template
from jinja2 import ChoiceLoader, FileSystemLoader
import base64
import importlib
import json
Expand Down Expand Up @@ -1298,5 +1299,38 @@ def actors_from_ids(self, datasette, actor_ids):


@pytest.mark.asyncio
async def test_hook_jinja2_environment_from_request():
pass
async def test_hook_jinja2_environment_from_request(tmpdir):
templates = pathlib.Path(tmpdir / "templates")
templates.mkdir()
(templates / "index.html").write_text("Hello museums!", "utf-8")

class EnvironmentPlugin:
@hookimpl
def jinja2_environment_from_request(self, request, env):
if request and request.host == "www.niche-museums.com":
return env.overlay(
loader=ChoiceLoader(
[
FileSystemLoader(str(templates)),
env.loader,
]
),
enable_async=True,
)
return env

datasette = Datasette(memory=True)

try:
pm.register(EnvironmentPlugin(), name="EnvironmentPlugin")
response = await datasette.client.get("/")
assert response.status_code == 200
assert "Hello museums!" not in response.text
# Try again with the hostname
response2 = await datasette.client.get(
"/", headers={"host": "www.niche-museums.com"}
)
assert response2.status_code == 200
assert "Hello museums!" in response2.text
finally:
pm.unregister(name="EnvironmentPlugin")

0 comments on commit 17993a3

Please sign in to comment.