forked from encode/starlette
/
test_templates.py
62 lines (47 loc) · 1.87 KB
/
test_templates.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import os
import pytest
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.templating import Jinja2Templates
def test_templates(tmpdir, test_client_factory):
path = os.path.join(tmpdir, "index.html")
with open(path, "w") as file:
file.write("<html>Hello, <a href='{{ url_for('homepage') }}'>world</a></html>")
async def homepage(request):
return templates.TemplateResponse("index.html", {"request": request})
app = Starlette(
debug=True,
routes=[Route("/", endpoint=homepage)],
)
templates = Jinja2Templates(directory=str(tmpdir))
client = test_client_factory(app)
response = client.get("/")
assert response.text == "<html>Hello, <a href='http://testserver/'>world</a></html>"
assert response.template.name == "index.html"
assert set(response.context.keys()) == {"request"}
def test_template_response_requires_request(tmpdir):
templates = Jinja2Templates(str(tmpdir))
with pytest.raises(ValueError):
templates.TemplateResponse("", {})
def test_calls_context_processors(tmp_path, test_client_factory, tmpdir):
path = tmp_path / "index.html"
path.write_text("<html>Hello {{ username }}</html>")
async def homepage(request):
return templates.TemplateResponse("index.html", {"request": request})
def hello_world_processor(request):
return {"username": "World"}
app = Starlette(
debug=True,
routes=[Route("/", endpoint=homepage)],
)
templates = Jinja2Templates(
directory=tmp_path,
context_processors=[
hello_world_processor,
],
)
client = test_client_factory(app)
response = client.get("/")
assert response.text == "<html>Hello World</html>"
assert response.template.name == "index.html"
assert set(response.context.keys()) == {"request", "username"}