-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
107 lines (73 loc) · 2.75 KB
/
tests.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
from typing import TYPE_CHECKING
import muffin
import muffin_jinja2
import pytest
if TYPE_CHECKING:
from muffin_babel import Plugin as Babel
@pytest.fixture()
def app():
return muffin.Application(
debug=True,
babel_configure_jinja2=True,
babel_locale_folders=["example/locales"],
)
@pytest.fixture()
def jinja2(app):
return muffin_jinja2.Plugin(app)
@pytest.fixture()
def babel(app):
from muffin_babel import Plugin as Babel
return Babel(app)
async def test_babel(app, jinja2, babel):
await app.lifespan.run("startup")
@app.route("/")
async def index(request):
assert babel.current_locale
return babel.gettext("Hello World!")
client = muffin.TestClient(app)
res = await client.get(
"/", headers={"accept-language": "ru-RU, ru;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5"}
)
assert await res.text() == "Привет, Мир!"
@babel.locale_selector
async def get_locale_from_request(request):
return request.url.query.get("lang")
res = await client.get("/")
assert await res.text() == "Hello World!"
res = await client.get("/?lang=ru")
assert await res.text() == "Привет, Мир!"
from jinja2 import Template
template = Template("""{{ gettext('Hello World!') }}""")
@app.route("/jinja")
async def jinja(request):
return await jinja2.render(template)
res = await client.get("/jinja")
assert await res.text() == "Hello World!"
res = await client.get("/jinja?lang=ru")
assert await res.text() == "Привет, Мир!"
async def test_babel_middleware(app, babel: "Babel"):
@app.middleware
async def process_locale(handler, scope, receive, send):
# A correct locale has to be here
assert babel.current_locale.language == "ru"
return await handler(scope, receive, send)
@app.route("/")
async def index(request):
assert babel.current_locale.language == "ru"
return babel.gettext("Hello World!")
await app.lifespan.run("startup")
client = muffin.TestClient(app)
async with client.lifespan():
res = await client.get(
"/", headers={"accept-language": "ru-RU, ru;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5"}
)
assert await res.text() == "Привет, Мир!"
def test_locale_ctx(babel: "Babel"):
assert babel.gettext("Hello World!") == "Hello World!"
with babel.locale_ctx("ru"):
assert babel.gettext("Hello World!") == "Привет, Мир!"
with babel.locale_ctx("en-RU"):
assert babel.gettext("Hello World!") == "Hello World!"
def test_gettext(babel: "Babel"):
assert babel.gettext("Hello %(user)s", user="John") == "Hello John"
assert babel.gettext("Hello %(user)s") == "Hello %(user)s"