-
-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathtest_main.py
More file actions
409 lines (339 loc) · 9.94 KB
/
test_main.py
File metadata and controls
409 lines (339 loc) · 9.94 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
import re
import sys
from collections.abc import Generator
from pathlib import Path
from subprocess import run
import pytest
from devtools import Debug, debug
from devtools.ansi import strip_ansi
from .utils import normalise_output
def test_print(capsys):
a = 1
b = 2
result = debug(a, b)
stdout, stderr = capsys.readouterr()
print(stdout)
assert normalise_output(stdout) == (
'tests/test_main.py:<line no> test_print\n' ' a: 1 (int)\n' ' b: 2 (int)\n'
)
assert stderr == ''
assert result == (1, 2)
def test_print_kwargs(capsys):
a = 1
b = 2
result = debug(a, b, foo=[1, 2, 3])
stdout, stderr = capsys.readouterr()
print(stdout)
assert normalise_output(stdout) == (
'tests/test_main.py:<line no> test_print_kwargs\n'
' a: 1 (int)\n'
' b: 2 (int)\n'
' foo: [1, 2, 3] (list) len=3\n'
)
assert stderr == ''
assert result == (1, 2, {'foo': [1, 2, 3]})
def test_print_generator(capsys):
gen = (i for i in [1, 2])
result = debug(gen)
stdout, stderr = capsys.readouterr()
print(stdout)
assert normalise_output(stdout) == (
'tests/test_main.py:<line no> test_print_generator\n'
' gen: (\n'
' 1,\n'
' 2,\n'
' ) (generator)\n'
)
assert stderr == ''
assert isinstance(result, Generator)
# the generator got evaluated and is now empty, that's correct currently
assert list(result) == []
@pytest.mark.parametrize(
['py_script', 'stdout'],
[
(
"""\
from devtools import debug
def test_func(v):
debug('in test func', v)
foobar = 'hello world'
print('running debug...')
debug(foobar)
test_func(42)
print('debug run.')
""",
"""\
running debug...
/path/to/test.py:8 <module>
foobar: 'hello world' (str) len=11
/path/to/test.py:4 test_func
'in test func' (str) len=12
v: 42 (int)
debug run.
""",
),
(
"""\
from devtools import debug
def f(x):
debug(x, trace_=True)
g(x)
def g(x):
debug(x, trace_=True)
x = 42
debug(x, trace_=True)
f(x)
""",
"""\
/path/to/test.py:11 <module>
x: 42 (int)
/path/to/test.py:12 <module>
/path/to/test.py:4 f
x: 42 (int)
/path/to/test.py:12 <module>
/path/to/test.py:5 f
/path/to/test.py:8 g
x: 42 (int)
""",
),
(
"""\
from devtools import debug
def f(x):
print(debug.format(x, trace_=True))
g(x)
def g(x):
print(debug.format(x, trace_=True))
x = 42
print(debug.format(x, trace_=True))
f(x)
""",
"""\
/path/to/test.py:11 <module>
x: 42 (int)
/path/to/test.py:12 <module>
/path/to/test.py:4 f
x: 42 (int)
/path/to/test.py:12 <module>
/path/to/test.py:5 f
/path/to/test.py:8 g
x: 42 (int)
""",
),
(
"""\
from devtools import debug
def f(x):
debug.trace(x)
g(x)
def g(x):
debug.trace(x)
x = 42
debug.trace(x)
f(x)
""",
"""\
/path/to/test.py:11 <module>
x: 42 (int)
/path/to/test.py:12 <module>
/path/to/test.py:4 f
x: 42 (int)
/path/to/test.py:12 <module>
/path/to/test.py:5 f
/path/to/test.py:8 g
x: 42 (int)
""",
),
],
)
@pytest.mark.xfail(
sys.platform == 'win32',
reason='Fatal Python error: _Py_HashRandomization_Init: failed to get random numbers to initialize Python',
)
def test_print_subprocess(py_script, stdout, tmp_path):
f = tmp_path / 'test.py'
f.write_text(py_script)
p = run(
[sys.executable, str(f)],
capture_output=True,
text=True,
env={
'PYTHONPATH': str(Path(__file__).parents[1].resolve()),
},
)
assert p.stderr == ''
assert p.returncode == 0, (p.stderr, p.stdout)
assert p.stdout.replace(str(f), '/path/to/test.py') == stdout
def test_format():
a = b'i might bite'
b = 'hello this is a test'
v = debug.format(a, b)
s = normalise_output(str(v))
print(s)
assert s == (
"tests/test_main.py:<line no> test_format\n"
" a: b'i might bite' (bytes) len=12\n"
" b: 'hello this is a test' (str) len=20"
)
def test_odd_path(mocker):
# all valid calls
mocked_relative_to = mocker.patch('pathlib.Path.relative_to')
mocked_relative_to.side_effect = ValueError()
v = debug.format('test')
if sys.platform == 'win32':
pattern = r'\w:\\.*?\\'
else:
pattern = r'/.*?/'
pattern += r"test_main.py:\d{2,} test_odd_path\n 'test' \(str\) len=4"
assert re.search(pattern, str(v)), v
def test_small_call_frame():
debug_ = Debug(warnings=False)
v = debug_.format(
1,
2,
3,
)
assert normalise_output(str(v)) == (
'tests/test_main.py:<line no> test_small_call_frame\n' ' 1 (int)\n' ' 2 (int)\n' ' 3 (int)'
)
def test_small_call_frame_warning():
debug_ = Debug()
v = debug_.format(
1,
2,
3,
)
print(f'\n---\n{v}\n---')
assert normalise_output(str(v)) == (
'tests/test_main.py:<line no> test_small_call_frame_warning\n' ' 1 (int)\n' ' 2 (int)\n' ' 3 (int)'
)
@pytest.mark.skipif(sys.version_info < (3, 6), reason='kwarg order is not guaranteed for 3.5')
def test_kwargs():
a = 'variable'
v = debug.format(first=a, second='literal')
s = normalise_output(str(v))
print(s)
assert s == (
"tests/test_main.py:<line no> test_kwargs\n"
" first: 'variable' (str) len=8 variable=a\n"
" second: 'literal' (str) len=7"
)
def test_kwargs_orderless():
# for python3.5
a = 'variable'
v = debug.format(first=a, second='literal')
s = normalise_output(str(v))
assert set(s.split('\n')) == {
'tests/test_main.py:<line no> test_kwargs_orderless',
" first: 'variable' (str) len=8 variable=a",
" second: 'literal' (str) len=7",
}
def test_simple_vars():
v = debug.format('test', 1, 2)
s = normalise_output(str(v))
assert s == (
"tests/test_main.py:<line no> test_simple_vars\n" " 'test' (str) len=4\n" " 1 (int)\n" " 2 (int)"
)
r = normalise_output(repr(v))
assert r == (
"<DebugOutput tests/test_main.py:<line no> test_simple_vars arguments: 'test' (str) len=4 1 (int) 2 (int)>"
)
def test_attributes():
class Foo:
x = 1
class Bar:
y = Foo()
b = Bar()
v = debug.format(b.y.x)
assert 'test_attributes\n b.y.x: 1 (int)' in str(v)
def test_eval():
v = eval('debug.format(1)')
assert str(v) == '<string>:1 <module> (no code context for debug call, code inspection impossible)\n 1 (int)'
def test_warnings_disabled():
debug_ = Debug(warnings=False)
v1 = eval('debug_.format(1)')
assert str(v1) == '<string>:1 <module>\n 1 (int)'
v2 = debug_.format(1)
assert 'test_warnings_disabled\n 1 (int)' in str(v2)
def test_eval_kwargs():
v = eval('debug.format(1, apple="pear")')
assert set(str(v).split('\n')) == {
'<string>:1 <module> (no code context for debug call, code inspection impossible)',
' 1 (int)',
" apple: 'pear' (str) len=4",
}
def test_exec(capsys):
exec('a = 1\n' 'b = 2\n' 'debug(b, a + b)')
stdout, stderr = capsys.readouterr()
assert stdout == (
'<string>:3 <module> (no code context for debug call, code inspection impossible)\n'
' 2 (int)\n'
' 3 (int)\n'
)
assert stderr == ''
def test_colours():
v = debug.format(range(6))
s = v.str(True)
assert s.startswith('\x1b[35mtests'), repr(s)
s2 = normalise_output(strip_ansi(s))
assert s2 == normalise_output(v.str()), repr(s2)
def test_colours_warnings(mocker):
mocked_getframe = mocker.patch('sys._getframe')
mocked_getframe.side_effect = ValueError()
v = debug.format('x')
s = normalise_output(v.str(True))
assert s.startswith('\x1b[35m<unknown>'), repr(s)
s2 = strip_ansi(s)
assert s2 == v.str(), repr(s2)
def test_inspect_error(mocker):
mocked_getframe = mocker.patch('sys._getframe')
mocked_getframe.side_effect = ValueError()
v = debug.format('x')
print(repr(str(v)))
assert str(v) == "<unknown>:0 (error parsing code, call stack too shallow)\n 'x' (str) len=1"
def test_breakpoint(mocker):
# not much else we can do here
mocked_set_trace = mocker.patch('pdb.Pdb.set_trace')
debug.breakpoint()
assert mocked_set_trace.called
@pytest.mark.xfail(
sys.platform == 'win32' and sys.version_info >= (3, 9),
reason='see https://github.com/alexmojaki/executing/issues/27',
)
def test_starred_kwargs():
v = {'foo': 1, 'bar': 2}
v = debug.format(**v)
s = normalise_output(v.str())
assert set(s.split('\n')) == {
'tests/test_main.py:<line no> test_starred_kwargs',
' foo: 1 (int)',
' bar: 2 (int)',
}
@pytest.mark.skipif(sys.version_info < (3, 7), reason='error repr different before 3.7')
def test_pretty_error():
class BadPretty:
def __getattr__(self, item):
raise RuntimeError('this is an error')
b = BadPretty()
v = debug.format(b)
s = normalise_output(str(v))
assert s == (
"tests/test_main.py:<line no> test_pretty_error\n"
" b: <tests.test_main.test_pretty_error.<locals>.BadPretty object at 0x<hash>> (BadPretty)\n"
" !!! error pretty printing value: RuntimeError('this is an error')"
)
def test_multiple_debugs():
debug.format([i * 2 for i in range(2)])
debug.format([i * 2 for i in range(2)])
v = debug.format([i * 2 for i in range(2)])
s = normalise_output(str(v))
assert s == (
'tests/test_main.py:<line no> test_multiple_debugs\n' ' [i * 2 for i in range(2)]: [0, 2] (list) len=2'
)
def test_return_args(capsys):
assert debug('foo') == 'foo'
assert debug('foo', 'bar') == ('foo', 'bar')
assert debug('foo', 'bar', spam=123) == ('foo', 'bar', {'spam': 123})
assert debug(spam=123) == ({'spam': 123},)
stdout, stderr = capsys.readouterr()
print(stdout)