-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_python_interface.py
More file actions
278 lines (203 loc) · 8.36 KB
/
test_python_interface.py
File metadata and controls
278 lines (203 loc) · 8.36 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python
import pathlib
from datetime import datetime
import pytest
import rustfluent as fluent
data_dir = pathlib.Path(__file__).parent.resolve() / "data"
# Bidirectional markers.
# See https://unicode.org/reports/tr9/#Directional_Formatting_Characters
BIDI_OPEN, BIDI_CLOSE = "\u2068", "\u2069"
def test_en_basic():
bundle = fluent.Bundle("en", data_dir / "en.ftl")
assert bundle.get_translation("hello-world") == "Hello World"
def test_en_basic_str_path():
bundle = fluent.Bundle("en", str(data_dir / "en.ftl"))
assert bundle.get_translation("hello-world") == "Hello World"
def test_en_basic_with_named_arguments():
bundle = fluent.Bundle(
language="en",
ftl_filename=data_dir / "en.ftl",
)
assert bundle.get_translation("hello-world") == "Hello World"
def test_en_with_variables():
bundle = fluent.Bundle("en", data_dir / "en.ftl")
assert (
bundle.get_translation("hello-user", variables={"user": "Bob"})
== f"Hello, {BIDI_OPEN}Bob{BIDI_CLOSE}"
)
def test_en_with_variables_use_isolating_off():
bundle = fluent.Bundle("en", data_dir / "en.ftl")
assert (
bundle.get_translation(
"hello-user",
variables={"user": "Bob"},
use_isolating=False,
)
== "Hello, Bob"
)
@pytest.mark.parametrize(
"description, identifier, variables, expected",
(
("String", "hello-user", {"user": "Bob"}, f"Hello, {BIDI_OPEN}Bob{BIDI_CLOSE}"),
("Integer", "apples", {"numberOfApples": 10}, f"{BIDI_OPEN}10{BIDI_CLOSE} apples"),
(
"Naive datetime",
"date-message",
{"date": datetime(2020, 1, 5)},
f"The date is {BIDI_OPEN}2020-01-05{BIDI_CLOSE}.",
),
),
)
def test_variables_of_different_types(description, identifier, variables, expected):
bundle = fluent.Bundle("en", data_dir / "en.ftl")
result = bundle.get_translation(identifier, variables=variables)
assert result == expected
def test_invalid_language():
with pytest.raises(ValueError) as exc_info:
fluent.Bundle("$", "")
assert str(exc_info.value) == "Invalid language: '$'"
@pytest.mark.parametrize(
"key",
(
object(),
34.3,
10,
),
)
def test_invalid_variable_keys_raise_type_error(key):
bundle = fluent.Bundle("en", data_dir / "en.ftl")
with pytest.raises(TypeError, match="Variable key not a str, got"):
bundle.get_translation("hello-user", variables={key: "Bob"})
@pytest.mark.parametrize(
"value",
(
object(),
34.3,
1_000_000_000_000, # Larger than signed long integer.
),
)
def test_invalid_variable_values_use_key_instead(value):
bundle = fluent.Bundle("en", data_dir / "en.ftl")
result = bundle.get_translation("hello-user", variables={"user": value})
assert result == f"Hello, {BIDI_OPEN}user{BIDI_CLOSE}"
def test_fr_basic():
bundle = fluent.Bundle("fr", data_dir / "fr.ftl")
assert bundle.get_translation("hello-world") == "Bonjour le monde!"
def test_fr_with_args():
bundle = fluent.Bundle("fr", data_dir / "fr.ftl")
assert (
bundle.get_translation("hello-user", variables={"user": "Bob"})
== f"Bonjour, {BIDI_OPEN}Bob{BIDI_CLOSE}!"
)
@pytest.mark.parametrize(
"number, expected",
(
(1, "One"),
(2, "Something else"),
# Note that for selection to work, the variable must be an integer.
# So "1" is not equivalent to 1.
("1", "Something else"),
),
)
def test_selector(number, expected):
bundle = fluent.Bundle("en", data_dir / "en.ftl")
result = bundle.get_translation("with-selector", variables={"number": number})
assert result == expected
def test_id_not_found():
bundle = fluent.Bundle("fr", data_dir / "fr.ftl")
with pytest.raises(ValueError):
bundle.get_translation("missing", variables={"user": "Bob"})
def test_file_not_found():
with pytest.raises(FileNotFoundError):
fluent.Bundle("fr", data_dir / "none.ftl")
@pytest.mark.parametrize("pass_strict_argument_explicitly", (True, False))
def test_parses_other_parts_of_file_that_contains_errors_in_non_strict_mode(
pass_strict_argument_explicitly,
):
kwargs = dict(strict=False) if pass_strict_argument_explicitly else {}
bundle = fluent.Bundle("fr", data_dir / "errors.ftl", **kwargs)
translation = bundle.get_translation("valid-message")
assert translation == "I'm valid."
def test_raises_parser_error_on_file_that_contains_errors_in_strict_mode():
filename = data_dir / "errors.ftl"
with pytest.raises(fluent.ParserError) as exc_info:
fluent.Bundle("fr", filename, strict=True)
message = str(exc_info.value)
# Recombine first line if it was too long
lines = message.split("\n")
if lines[1].endswith(".ftl"):
lines = [(lines[0] + lines[1]).replace(" │ ", ""), *lines[2:]]
message = "\n".join(lines)
# End recombination
expected = f"""\
× Error when parsing {filename}
╭─[1:16]
1 │ invalid-message
· ┬
· ╰── Expected a token starting with "="
2 │
3 │ valid-message = I'm valid.
╰────
"""
assert message == expected
def test_parser_error_str():
assert str(fluent.ParserError) == "<class 'rustfluent.ParserError'>"
# Attribute access tests
def test_basic_attribute_access():
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
assert bundle.get_translation("welcome-message.title") == "Welcome to our site"
def test_regular_message_still_works_with_attributes():
"""Test that accessing the main message value still works when it has attributes."""
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
assert bundle.get_translation("welcome-message") == "Welcome!"
def test_multiple_attributes_on_same_message():
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
assert bundle.get_translation("login-input.placeholder") == "email@example.com"
assert bundle.get_translation("login-input.aria-label") == "Login input value"
assert bundle.get_translation("login-input.title") == "Type your login email"
def test_attribute_with_variables():
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
result = bundle.get_translation("greeting.formal", variables={"name": "Alice"})
assert result == f"Hello, {BIDI_OPEN}Alice{BIDI_CLOSE}"
def test_attribute_with_variables_use_isolating_off():
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
result = bundle.get_translation(
"greeting.informal",
variables={"name": "Bob"},
use_isolating=False,
)
assert result == "Hi Bob!"
def test_attribute_on_message_without_main_value():
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
assert bundle.get_translation("form-button.submit") == "Submit Form"
assert bundle.get_translation("form-button.cancel") == "Cancel"
assert bundle.get_translation("form-button.reset") == "Reset Form"
def test_message_without_value_raises_error():
"""Test that accessing a message without a value (only attributes) raises an error."""
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
with pytest.raises(ValueError, match="form-button - Message has no value"):
bundle.get_translation("form-button")
def test_missing_message_with_attribute_syntax_raises_error():
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
with pytest.raises(ValueError, match="nonexistent not found"):
bundle.get_translation("nonexistent.title")
def test_missing_attribute_raises_error():
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
with pytest.raises(
ValueError,
match="welcome-message.nonexistent - Attribute 'nonexistent' not found on message 'welcome-message'",
):
bundle.get_translation("welcome-message.nonexistent")
@pytest.mark.parametrize(
"identifier,expected",
(
("welcome-message", "Welcome!"),
("welcome-message.title", "Welcome to our site"),
("welcome-message.aria-label", "Welcome greeting"),
("login-input", "Email"),
("login-input.placeholder", "email@example.com"),
),
)
def test_attribute_and_message_access_parameterized(identifier, expected):
bundle = fluent.Bundle("en", data_dir / "attributes.ftl")
assert bundle.get_translation(identifier) == expected