-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
test_api.py
394 lines (295 loc) · 9.27 KB
/
test_api.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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import io
import json
import os
from datetime import date
from datetime import datetime
from datetime import time
from types import MappingProxyType
import pytest
import tomlkit
from tomlkit import dump
from tomlkit import dumps
from tomlkit import load
from tomlkit import loads
from tomlkit import parse
from tomlkit.exceptions import InvalidCharInStringError
from tomlkit.exceptions import InvalidControlChar
from tomlkit.exceptions import InvalidDateError
from tomlkit.exceptions import InvalidDateTimeError
from tomlkit.exceptions import InvalidNumberError
from tomlkit.exceptions import InvalidTimeError
from tomlkit.exceptions import UnexpectedCharError
from tomlkit.items import AoT
from tomlkit.items import Array
from tomlkit.items import Bool
from tomlkit.items import Date
from tomlkit.items import DateTime
from tomlkit.items import Float
from tomlkit.items import InlineTable
from tomlkit.items import Integer
from tomlkit.items import Key
from tomlkit.items import Table
from tomlkit.items import Time
from tomlkit.toml_document import TOMLDocument
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date, time)):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
@pytest.mark.parametrize(
"example_name",
[
"example",
"fruit",
"hard",
"sections_with_same_start",
"pyproject",
"0.5.0",
"test",
"newline_in_strings",
"preserve_quotes_in_string",
"string_slash_whitespace_newline",
"table_names",
],
)
def test_parse_can_parse_valid_toml_files(example, example_name):
assert isinstance(parse(example(example_name)), TOMLDocument)
assert isinstance(loads(example(example_name)), TOMLDocument)
@pytest.mark.parametrize(
"example_name",
[
"example",
"fruit",
"hard",
"sections_with_same_start",
"pyproject",
"0.5.0",
"test",
"newline_in_strings",
"preserve_quotes_in_string",
"string_slash_whitespace_newline",
"table_names",
],
)
def test_load_from_file_object(example_name):
with open(
os.path.join(os.path.dirname(__file__), "examples", example_name + ".toml"),
encoding="utf-8",
) as fp:
assert isinstance(load(fp), TOMLDocument)
@pytest.mark.parametrize("example_name", ["0.5.0", "pyproject", "table_names"])
def test_parsed_document_are_properly_json_representable(
example, json_example, example_name
):
doc = json.loads(json.dumps(parse(example(example_name)), default=json_serial))
json_doc = json.loads(json_example(example_name))
assert doc == json_doc
@pytest.mark.parametrize(
"example_name,error",
[
("section_with_trailing_characters", UnexpectedCharError),
("key_value_with_trailing_chars", UnexpectedCharError),
("array_with_invalid_chars", UnexpectedCharError),
("invalid_number", InvalidNumberError),
("invalid_date", InvalidDateError),
("invalid_time", InvalidTimeError),
("invalid_datetime", InvalidDateTimeError),
("trailing_comma", UnexpectedCharError),
("newline_in_singleline_string", InvalidControlChar),
("string_slash_whitespace_char", InvalidCharInStringError),
("array_no_comma", UnexpectedCharError),
("array_duplicate_comma", UnexpectedCharError),
("array_leading_comma", UnexpectedCharError),
("inline_table_no_comma", UnexpectedCharError),
("inline_table_duplicate_comma", UnexpectedCharError),
("inline_table_leading_comma", UnexpectedCharError),
("inline_table_trailing_comma", UnexpectedCharError),
],
)
def test_parse_raises_errors_for_invalid_toml_files(
invalid_example, error, example_name
):
with pytest.raises(error):
parse(invalid_example(example_name))
@pytest.mark.parametrize(
"example_name",
[
"example",
"fruit",
"hard",
"sections_with_same_start",
"pyproject",
"0.5.0",
"test",
"table_names",
],
)
def test_original_string_and_dumped_string_are_equal(example, example_name):
content = example(example_name)
parsed = parse(content)
assert content == dumps(parsed)
def test_a_raw_dict_can_be_dumped():
s = dumps({"foo": "bar"})
assert s == 'foo = "bar"\n'
def test_mapping_types_can_be_dumped():
x = MappingProxyType({"foo": "bar"})
assert dumps(x) == 'foo = "bar"\n'
def test_dumps_weird_object():
with pytest.raises(TypeError):
dumps(object())
def test_dump_tuple_value_as_array():
x = {"foo": (1, 2)}
assert dumps(x) == "foo = [1, 2]\n"
x = {"foo": ({"a": 1}, {"a": 2})}
assert dumps(x) == "[[foo]]\na = 1\n\n[[foo]]\na = 2\n"
def test_dump_to_file_object():
doc = {"foo": "bar"}
fp = io.StringIO()
dump(doc, fp)
assert fp.getvalue() == 'foo = "bar"\n'
def test_integer():
i = tomlkit.integer("34")
assert isinstance(i, Integer)
def test_float():
i = tomlkit.float_("34.56")
assert isinstance(i, Float)
def test_boolean():
i = tomlkit.boolean("true")
assert isinstance(i, Bool)
def test_date():
dt = tomlkit.date("1979-05-13")
assert isinstance(dt, Date)
with pytest.raises(ValueError):
tomlkit.date("12:34:56")
def test_time():
dt = tomlkit.time("12:34:56")
assert isinstance(dt, Time)
with pytest.raises(ValueError):
tomlkit.time("1979-05-13")
def test_datetime():
dt = tomlkit.datetime("1979-05-13T12:34:56")
assert isinstance(dt, DateTime)
with pytest.raises(ValueError):
tomlkit.time("1979-05-13")
def test_array():
a = tomlkit.array()
assert isinstance(a, Array)
a = tomlkit.array("[1,2, 3]")
assert isinstance(a, Array)
def test_table():
t = tomlkit.table()
assert isinstance(t, Table)
def test_inline_table():
t = tomlkit.inline_table()
assert isinstance(t, InlineTable)
def test_aot():
t = tomlkit.aot()
assert isinstance(t, AoT)
def test_key():
k = tomlkit.key("foo")
assert isinstance(k, Key)
def test_key_value():
k, i = tomlkit.key_value("foo = 12")
assert isinstance(k, Key)
assert isinstance(i, Integer)
def test_string():
s = tomlkit.string('foo "')
assert s.value == 'foo "'
assert s.as_string() == '"foo \\""'
def test_item_dict_to_table():
t = tomlkit.item({"foo": {"bar": "baz"}})
assert t.value == {"foo": {"bar": "baz"}}
assert (
t.as_string()
== """[foo]
bar = "baz"
"""
)
def test_item_mixed_aray():
example = [{"a": 3}, "b", 42]
expected = '[{a = 3}, "b", 42]'
t = tomlkit.item(example)
assert t.as_string().strip() == expected
assert dumps({"x": {"y": example}}).strip() == "[x]\ny = " + expected
def test_build_super_table():
doc = tomlkit.document()
table = tomlkit.table(True)
table.add("bar", {"x": 1})
doc.add("foo", table)
assert doc.as_string() == "[foo.bar]\nx = 1\n"
def test_add_dotted_key():
doc = tomlkit.document()
doc.add(tomlkit.key(["foo", "bar"]), 1)
assert doc.as_string() == "foo.bar = 1\n"
table = tomlkit.table()
table.add(tomlkit.key(["foo", "bar"]), 1)
assert table.as_string() == "foo.bar = 1\n"
@pytest.mark.parametrize(
("raw", "expected"),
[
("true", True),
("false", False),
],
)
def test_value_parses_boolean(raw, expected):
parsed = tomlkit.value(raw)
assert parsed == expected
@pytest.mark.parametrize(
"raw", ["t", "f", "tru", "fals", "test", "friend", "truthy", "falsify"]
)
def test_value_rejects_values_looking_like_bool_at_start(raw):
"""Reproduces https://github.com/sdispater/tomlkit/issues/165"""
with pytest.raises(tomlkit.exceptions.ParseError):
tomlkit.value(raw)
@pytest.mark.parametrize(
"raw",
[
"truee",
"truely",
"true-thoughts",
"true_hip_hop",
],
)
def test_value_rejects_values_having_true_prefix(raw):
"""Values that have ``true`` or ``false`` as prefix but then have additional chars are rejected."""
with pytest.raises(tomlkit.exceptions.ParseError):
tomlkit.value(raw)
@pytest.mark.parametrize(
"raw",
[
"falsee",
"falsely",
"false-ideas",
"false_prophet",
],
)
def test_value_rejects_values_having_false_prefix(raw):
"""Values that have ``true`` or ``false`` as prefix but then have additional chars are rejected."""
with pytest.raises(tomlkit.exceptions.ParseError):
tomlkit.value(raw)
@pytest.mark.parametrize(
"raw",
[
'"foo"1.2',
"truefalse",
"1.0false",
"100true",
"truetrue",
"falsefalse",
"1.2.3.4",
"[][]",
"{a=[][]}[]",
"true[]",
"false{a=1}",
],
)
def test_value_rejects_values_with_appendage(raw):
"""Values that appear valid at the beginning but leave chars unparsed are rejected."""
with pytest.raises(tomlkit.exceptions.ParseError):
tomlkit.value(raw)
def test_create_super_table_with_table():
data = {"foo": {"bar": {"a": 1}}}
assert dumps(data) == "[foo.bar]\na = 1\n"
def test_create_super_table_with_aot():
data = {"foo": {"bar": [{"a": 1}]}}
assert dumps(data) == "[[foo.bar]]\na = 1\n"