-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_utils.py
More file actions
426 lines (349 loc) · 10.9 KB
/
Copy pathtest_utils.py
File metadata and controls
426 lines (349 loc) · 10.9 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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
"""
test_utils
~~~~~~~~~~~~~~~
Test functions in utils.py
"""
# stdlib
import decimal
import pathlib
import platform
import re
import sys
from collections import namedtuple
# 3rd party
import pytest
# this package
from domdf_python_tools.testing import testing_boolean_values
from domdf_python_tools.typing import HasHead
from domdf_python_tools.utils import (
cmp,
convert_indents,
double_repr_string,
enquote_value,
head,
list2str,
posargs2kwargs,
printr,
printt,
pyversion,
stderr_writer,
str2tuple,
strtobool,
trim_precision
)
def test_pyversion():
assert isinstance(pyversion, int)
class TestList2Str:
@pytest.mark.parametrize(
"value, expects",
[
([1, 2, 3], "1,2,3"),
(['a', 'b', 'c'], "a,b,c"),
(['a', 'b', 1, 2], "a,b,1,2"),
(['a', 2, pathlib.Path("foo.txt")], "a,2,foo.txt"),
],
)
def test_list2str(self, value, expects):
str_representation = list2str(value)
assert isinstance(str_representation, str)
assert str_representation == expects
@pytest.mark.parametrize(
"value, expects",
[
([1, 2, 3], "1;2;3"),
(['a', 'b', 'c'], "a;b;c"),
(['a', 'b', 1, 2], "a;b;1;2"),
(['a', 2, pathlib.Path("foo.txt")], "a;2;foo.txt"),
],
)
def test_list2str_semicolon(self, value, expects):
str_representation = list2str(value, sep=';')
assert isinstance(str_representation, str)
assert str_representation == expects
class CustomRepr:
def __init__(self):
pass
def __repr__(self):
return "This is my custom __repr__!"
class NoRepr:
def __init__(self):
pass
no_repr_instance = NoRepr()
def get_mem_addr(obj):
if sys.platform == "win32" and platform.python_implementation() != "PyPy":
return f"0x0*{hex(id(obj))[2:].upper()}"
else:
return f"0x0*{hex(id(obj))[2:]}"
@pytest.mark.parametrize(
"obj, expects",
[
("This is a test", "'This is a test'"),
(pathlib.PurePosixPath("foo.txt"), r"PurePosixPath\('foo.txt'\)"),
(1234, "1234"),
(12.34, "12.34"),
(CustomRepr(), "This is my custom __repr__!"),
(no_repr_instance, f"<tests.test_utils.NoRepr object at {get_mem_addr(no_repr_instance)}>"),
],
)
def test_printr(obj, expects, capsys):
printr(obj)
captured = capsys.readouterr()
stdout = captured.out.split('\n')
assert re.match(expects, stdout[0])
@pytest.mark.parametrize(
"obj, expects",
[
("This is a test", "<class 'str'>"),
(pathlib.PurePosixPath("foo.txt"), "<class 'pathlib.PurePosixPath'>"),
(1234, "<class 'int'>"),
(12.34, "<class 'float'>"),
(CustomRepr(), "<class 'tests.test_utils.CustomRepr'>"),
(no_repr_instance, "<class 'tests.test_utils.NoRepr'>"),
],
)
def test_printt(obj, expects, capsys):
printt(obj)
captured = capsys.readouterr()
stdout = captured.out.split('\n')
assert stdout[0] == expects
@pytest.mark.parametrize(
"obj, expects",
[
("This is a test", "This is a test"),
(pathlib.PurePosixPath("foo.txt"), "foo.txt"),
(1234, "1234"),
(12.34, "12.34"),
(CustomRepr(), "This is my custom __repr__!"),
(no_repr_instance, f"<tests.test_utils.NoRepr object at {get_mem_addr(no_repr_instance)}>"),
],
)
def test_stderr_writer(obj, expects, capsys):
stderr_writer(obj)
captured = capsys.readouterr()
stderr = captured.err.split('\n')
assert re.match(expects, stderr[0])
class TestStr2Tuple:
@pytest.mark.parametrize(
"value, expects",
[
("1,2,3", (1, 2, 3)), # tests without spaces
("1, 2, 3", (1, 2, 3)), # tests with spaces
],
)
def test_str2tuple(self, value, expects):
assert isinstance(str2tuple(value), tuple)
assert str2tuple(value) == expects
@pytest.mark.parametrize(
"value, expects",
[
("1;2;3", (1, 2, 3)), # tests without semicolon
("1; 2; 3", (1, 2, 3)), # tests with semicolon
],
)
def test_str2tuple_semicolon(self, value, expects):
assert isinstance(str2tuple(value, sep=';'), tuple)
assert str2tuple(value, sep=';') == expects
class TestStrToBool:
@testing_boolean_values(extra_truthy=[50, -1])
def test_strtobool(self, boolean_string, expected_boolean):
assert strtobool(boolean_string) == expected_boolean
@pytest.mark.parametrize(
"obj, expects",
[
("truthy", ValueError),
("foo", ValueError),
("bar", ValueError),
(None, AttributeError),
(1.0, AttributeError),
(0.0, AttributeError),
],
)
def test_strtobool_errors(self, obj, expects):
with pytest.raises(expects):
strtobool(obj)
@pytest.mark.parametrize(
"obj, expects",
[
(True, True),
("True", "True"),
("true", "'true'"),
('y', "'y'"),
('Y', "'Y'"),
(1, 1),
(0, 0),
(50, 50),
(1.0, 1.0),
(0.0, 0.0),
(50.0, 50.0),
(decimal.Decimal("50.0"), "'50.0'"),
(False, False),
("False", "False"),
("false", "'false'"),
("Hello World", "'Hello World'"),
],
)
def test_enquote_value(obj, expects):
assert enquote_value(obj) == expects
#
#
# @pytest.mark.parametrize("obj, expects", [
# ("truthy", ValueError),
# ("foo", ValueError),
# ("bar", ValueError),
# (None, AttributeError),
# (1.0, AttributeError),
# (0.0, AttributeError),
# ])
# def test_enquote_value_errors(obj, expects):
# with pytest.raises(expects):
# enquote_value(obj)
def test_cmp():
assert isinstance(cmp(5, 20), int)
assert cmp(5, 20) < 0
assert cmp(5, 20) == -1
assert isinstance(cmp(20, 5), int)
assert cmp(20, 5) > 0
assert cmp(20, 5) == 1
assert isinstance(cmp(20, 20), int)
assert cmp(20, 20) == 0
def demo_function(arg1, arg2, arg3):
pass
@pytest.mark.parametrize(
"args, posarg_names, kwargs, expects",
[
((1, 2, 3), ("arg1", "arg2", "arg3"), {}, {"arg1": 1, "arg2": 2, "arg3": 3}),
((1, 2, 3), ("arg1", "arg2", "arg3"), None, {"arg1": 1, "arg2": 2, "arg3": 3}),
((1, 2, 3), ("arg1", "arg2", "arg3"), {"arg4": 4}, {"arg1": 1, "arg2": 2, "arg3": 3, "arg4": 4}),
((1, 2, 3), demo_function, None, {
"arg1": 1,
"arg2": 2,
"arg3": 3,
}),
]
)
def test_posargs2kwargs(args, posarg_names, kwargs, expects):
assert posargs2kwargs(args, posarg_names, kwargs) == expects
def test_convert_indents():
# TODO: test 'to'
assert convert_indents("hello world") == "hello world"
assert convert_indents("\thello world") == " hello world"
assert convert_indents("\t\thello world") == " hello world"
assert convert_indents("\t hello world") == " hello world"
assert convert_indents("hello world", tab_width=2) == "hello world"
assert convert_indents("\thello world", tab_width=2) == " hello world"
assert convert_indents("\t\thello world", tab_width=2) == " hello world"
assert convert_indents("\t hello world", tab_width=2) == " hello world"
assert convert_indents("hello world", from_=" ") == "hello world"
assert convert_indents(" hello world", from_=" ") == " hello world"
assert convert_indents(" hello world", from_=" ") == " hello world"
assert convert_indents(" hello world", from_=" ") == " hello world"
assert convert_indents("hello world", tab_width=2, from_=" ") == "hello world"
assert convert_indents(" hello world", tab_width=2, from_=" ") == " hello world"
assert convert_indents(" hello world", tab_width=2, from_=" ") == " hello world"
class TestHead:
def test_protocol(self):
assert not isinstance(str, HasHead)
assert not isinstance(int, HasHead)
assert not isinstance(float, HasHead)
assert not isinstance(tuple, HasHead)
assert not isinstance(list, HasHead)
def test_protocol_pandas(self):
pandas = pytest.importorskip("pandas")
assert isinstance(pandas.DataFrame, HasHead)
assert isinstance(pandas.Series, HasHead)
foo = namedtuple("foo", "a, b, c, d, e, f, g, h, i, j, k, l, m")
@pytest.mark.parametrize(
"args, expects",
[
((foo(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), ),
"foo(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10, ...)"),
((foo(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), 13),
"foo(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10, k=11, l=12, m=13)"),
]
)
def test_namedtuple(self, args, expects):
assert head(*args) == expects
@pytest.mark.parametrize(
"args, expects",
[
(((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), ), "(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...)"),
((
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13),
13,
),
"(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)"),
]
)
def test_tuple(self, args, expects):
assert head(*args) == expects
@pytest.mark.parametrize(
"args, expects",
[
(([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], ), "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...]"),
((
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
13,
),
"[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]"),
]
)
def test_list(self, args, expects):
assert head(*args) == expects
def test_data_frame(self):
pandas = pytest.importorskip("pandas")
df = pandas.DataFrame(
data=[["Bob", 20, "Apprentice"], ["Alice", 23, "Secretary"], ["Mario", 39, "Plumber"]],
columns=["Name", "Age", "Occupation"],
)
assert head(
df
) == """ Name Age Occupation
0 Bob 20 Apprentice
1 Alice 23 Secretary
2 Mario 39 Plumber\
"""
assert head(df, 1) == " Name Age Occupation\n0 Bob 20 Apprentice"
def test_series(self):
pandas = pytest.importorskip("pandas")
df = pandas.DataFrame(
data=[["Bob", 20, "Apprentice"], ["Alice", 23, "Secretary"], ["Mario", 39, "Plumber"]],
columns=["Name", "Age", "Occupation"],
)
ser = df.iloc[0]
assert head(ser) == """\
Name Bob
Age 20
Occupation Apprentice\
"""
assert head(ser, 1) == "Name Bob"
def test_str(self):
assert head("Hello World") == "Hello Worl..."
assert head("Hello World", 11) == "Hello World"
assert head("Hello World", 5) == "Hello..."
def test_trim_precision():
assert 170.10000000000002 != 170.1
assert trim_precision(170.10000000000002, 1) == 170.1
assert trim_precision(170.10000000000002, 2) == 170.1
assert trim_precision(170.10000000000002, 3) == 170.1
assert trim_precision(170.10000000000002, 4) == 170.1
assert trim_precision(170.10000000000002, 5) == 170.1
assert trim_precision(170.10000000000002) == 170.1
assert 170.15800000000002 != 170.158
assert trim_precision(170.15800000000002, 1) == 170.2
assert trim_precision(170.15800000000002, 2) == 170.16
assert trim_precision(170.15800000000002, 3) == 170.158
assert trim_precision(170.15800000000002, 4) == 170.158
assert trim_precision(170.15800000000002, 5) == 170.158
assert trim_precision(170.15800000000002) == 170.158
@pytest.mark.parametrize(
"value, expects",
[
("foo", '"foo"'),
("'foo'", "\"'foo'\""),
("don't", "\"don't\""),
("Here's a single quote \"", "\"Here's a single quote \\\"\""),
(enquote_value('☃'), "\"'☃'\""),
]
)
def test_double_repr_string(value: str, expects: str):
assert double_repr_string(value) == expects