Debian Codegraph @

Lib/test/test_trace.py

raw
1 import os
2 from pickle import dump
3 import sys
4 from test.support import captured_stdout, requires_resource, requires_gil_enabled
5 from test.support.os_helper import (TESTFN, rmtree, unlink)
6 from test.support.script_helper import assert_python_ok, assert_python_failure
7 import textwrap
8 import unittest
9 from types import FunctionType
10
11 import trace
12 from trace import Trace
13
14 from test.tracedmodules import testmod
15
16 ##
17 ## See also test_sys_settrace.py, which contains tests that cover
18 ## tracing of many more code blocks.
19 ##
20
21 #------------------------------- Utilities -----------------------------------#
22
23 def fix_ext_py(filename):
24 """Given a .pyc filename converts it to the appropriate .py"""
25 if filename.endswith('.pyc'):
26 filename = filename[:-1]
27 return filename
28
29 def my_file_and_modname():
30 """The .py file and module name of this file (__file__)"""
31 modname = os.path.splitext(os.path.basename(__file__))[0]
32 return fix_ext_py(__file__), modname
33
34 def get_firstlineno(func):
35 return func.__code__.co_firstlineno
36
37 #-------------------- Target functions for tracing ---------------------------#
38 #
39 # The relative line numbers of lines in these functions matter for verifying
40 # tracing. Please modify the appropriate tests if you change one of the
41 # functions. Absolute line numbers don't matter.
42 #
43
44 def traced_func_linear(x, y):
45 a = x
46 b = y
47 c = a + b
48 return c
49
50 def traced_func_loop(x, y):
51 c = x
52 for i in range(5):
53 c += y
54 return c
55
56 def traced_func_importing(x, y):
57 return x + y + testmod.func(1)
58
59 def traced_func_simple_caller(x):
60 c = traced_func_linear(x, x)
61 return c + x
62
63 def traced_func_importing_caller(x):
64 k = traced_func_simple_caller(x)
65 k += traced_func_importing(k, x)
66 return k
67
68 def traced_func_generator(num):
69 c = 5 # executed once
70 for i in range(num):
71 yield i + c
72
73 def traced_func_calling_generator():
74 k = 0
75 for i in traced_func_generator(10):
76 k += i
77
78 def traced_doubler(num):
79 return num * 2
80
81 def traced_capturer(*args, **kwargs):
82 return args, kwargs
83
84 def traced_caller_list_comprehension():
85 k = 10
86 mylist = [traced_doubler(i) for i in range(k)]
87 return mylist
88
89 def traced_decorated_function():
90 def decorator1(f):
91 return f
92 def decorator_fabric():
93 def decorator2(f):
94 return f
95 return decorator2
96 @decorator1
97 @decorator_fabric()
98 def func():
99 pass
100 func()
101
102
103 class TracedClass(object):
104 def __init__(self, x):
105 self.a = x
106
107 def inst_method_linear(self, y):
108 return self.a + y
109
110 def inst_method_calling(self, x):
111 c = self.inst_method_linear(x)
112 return c + traced_func_linear(x, c)
113
114 @classmethod
115 def class_method_linear(cls, y):
116 return y * 2
117
118 @staticmethod
119 def static_method_linear(y):
120 return y * 2
121
122
123 #------------------------------ Test cases -----------------------------------#
124
125
126 class TestLineCounts(unittest.TestCase):
127 """White-box testing of line-counting, via runfunc"""
128 def setUp(self):
129 self.addCleanup(sys.settrace, sys.gettrace())
130 self.tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0)
131 self.my_py_filename = fix_ext_py(__file__)
132
133 def test_traced_func_linear(self):
134 result = self.tracer.runfunc(traced_func_linear, 2, 5)
135 self.assertEqual(result, 7)
136
137 # all lines are executed once
138 expected = {}
139 firstlineno = get_firstlineno(traced_func_linear)
140 for i in range(1, 5):
141 expected[(self.my_py_filename, firstlineno + i)] = 1
142
143 self.assertEqual(self.tracer.results().counts, expected)
144
145 def test_traced_func_loop(self):
146 self.tracer.runfunc(traced_func_loop, 2, 3)
147
148 firstlineno = get_firstlineno(traced_func_loop)
149 expected = {
150 (self.my_py_filename, firstlineno + 1): 1,
151 (self.my_py_filename, firstlineno + 2): 6,
152 (self.my_py_filename, firstlineno + 3): 5,
153 (self.my_py_filename, firstlineno + 4): 1,
154 }
155 self.assertEqual(self.tracer.results().counts, expected)
156
157 def test_traced_func_importing(self):
158 self.tracer.runfunc(traced_func_importing, 2, 5)
159
160 firstlineno = get_firstlineno(traced_func_importing)
161 expected = {
162 (self.my_py_filename, firstlineno + 1): 1,
163 (fix_ext_py(testmod.__file__), 2): 1,
164 (fix_ext_py(testmod.__file__), 3): 1,
165 }
166
167 self.assertEqual(self.tracer.results().counts, expected)
168
169 def test_trace_func_generator(self):
170 self.tracer.runfunc(traced_func_calling_generator)
171
172 firstlineno_calling = get_firstlineno(traced_func_calling_generator)
173 firstlineno_gen = get_firstlineno(traced_func_generator)
174 expected = {
175 (self.my_py_filename, firstlineno_calling + 1): 1,
176 (self.my_py_filename, firstlineno_calling + 2): 11,
177 (self.my_py_filename, firstlineno_calling + 3): 10,
178 (self.my_py_filename, firstlineno_gen + 1): 1,
179 (self.my_py_filename, firstlineno_gen + 2): 11,
180 (self.my_py_filename, firstlineno_gen + 3): 10,
181 }
182 self.assertEqual(self.tracer.results().counts, expected)
183
184 def test_trace_list_comprehension(self):
185 self.tracer.runfunc(traced_caller_list_comprehension)
186
187 firstlineno_calling = get_firstlineno(traced_caller_list_comprehension)
188 firstlineno_called = get_firstlineno(traced_doubler)
189 expected = {
190 (self.my_py_filename, firstlineno_calling + 1): 1,
191 (self.my_py_filename, firstlineno_calling + 2): 11,
192 (self.my_py_filename, firstlineno_calling + 3): 1,
193 (self.my_py_filename, firstlineno_called + 1): 10,
194 }
195 self.assertEqual(self.tracer.results().counts, expected)
196
197 def test_traced_decorated_function(self):
198 self.tracer.runfunc(traced_decorated_function)
199
200 firstlineno = get_firstlineno(traced_decorated_function)
201 expected = {
202 (self.my_py_filename, firstlineno + 1): 1,
203 (self.my_py_filename, firstlineno + 2): 1,
204 (self.my_py_filename, firstlineno + 3): 1,
205 (self.my_py_filename, firstlineno + 4): 1,
206 (self.my_py_filename, firstlineno + 5): 1,
207 (self.my_py_filename, firstlineno + 6): 1,
208 (self.my_py_filename, firstlineno + 7): 2,
209 (self.my_py_filename, firstlineno + 8): 2,
210 (self.my_py_filename, firstlineno + 9): 2,
211 (self.my_py_filename, firstlineno + 10): 1,
212 (self.my_py_filename, firstlineno + 11): 1,
213 }
214 self.assertEqual(self.tracer.results().counts, expected)
215
216 def test_linear_methods(self):
217 # XXX todo: later add 'static_method_linear' and 'class_method_linear'
218 # here, once issue1764286 is resolved
219 #
220 for methname in ['inst_method_linear',]:
221 tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0)
222 traced_obj = TracedClass(25)
223 method = getattr(traced_obj, methname)
224 tracer.runfunc(method, 20)
225
226 firstlineno = get_firstlineno(method)
227 expected = {
228 (self.my_py_filename, firstlineno + 1): 1,
229 }
230 self.assertEqual(tracer.results().counts, expected)
231
232
233 class TestRunExecCounts(unittest.TestCase):
234 """A simple sanity test of line-counting, via runctx (exec)"""
235 def setUp(self):
236 self.my_py_filename = fix_ext_py(__file__)
237 self.addCleanup(sys.settrace, sys.gettrace())
238
239 def test_exec_counts(self):
240 self.tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0)
241 code = r'''traced_func_loop(2, 5)'''
242 code = compile(code, __file__, 'exec')
243 self.tracer.runctx(code, globals(), vars())
244
245 firstlineno = get_firstlineno(traced_func_loop)
246 expected = {
247 (self.my_py_filename, firstlineno + 1): 1,
248 (self.my_py_filename, firstlineno + 2): 6,
249 (self.my_py_filename, firstlineno + 3): 5,
250 (self.my_py_filename, firstlineno + 4): 1,
251 }
252
253 # When used through 'run', some other spurious counts are produced, like
254 # the settrace of threading, which we ignore, just making sure that the
255 # counts fo traced_func_loop were right.
256 #
257 for k in expected.keys():
258 self.assertEqual(self.tracer.results().counts[k], expected[k])
259
260
261 class TestFuncs(unittest.TestCase):
262 """White-box testing of funcs tracing"""
263 def setUp(self):
264 self.addCleanup(sys.settrace, sys.gettrace())
265 self.tracer = Trace(count=0, trace=0, countfuncs=1)
266 self.filemod = my_file_and_modname()
267 self._saved_tracefunc = sys.gettrace()
268
269 def tearDown(self):
270 if self._saved_tracefunc is not None:
271 sys.settrace(self._saved_tracefunc)
272
273 def test_simple_caller(self):
274 self.tracer.runfunc(traced_func_simple_caller, 1)
275
276 expected = {
277 self.filemod + ('traced_func_simple_caller',): 1,
278 self.filemod + ('traced_func_linear',): 1,
279 }
280 self.assertEqual(self.tracer.results().calledfuncs, expected)
281
282 def test_arg_errors(self):
283 res = self.tracer.runfunc(traced_capturer, 1, 2, self=3, func=4)
284 self.assertEqual(res, ((1, 2), {'self': 3, 'func': 4}))
285 with self.assertRaises(TypeError):
286 self.tracer.runfunc(func=traced_capturer, arg=1)
287 with self.assertRaises(TypeError):
288 self.tracer.runfunc()
289
290 def test_loop_caller_importing(self):
291 self.tracer.runfunc(traced_func_importing_caller, 1)
292
293 expected = {
294 self.filemod + ('traced_func_simple_caller',): 1,
295 self.filemod + ('traced_func_linear',): 1,
296 self.filemod + ('traced_func_importing_caller',): 1,
297 self.filemod + ('traced_func_importing',): 1,
298 (fix_ext_py(testmod.__file__), 'testmod', 'func'): 1,
299 }
300 self.assertEqual(self.tracer.results().calledfuncs, expected)
301
302 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
303 'pre-existing trace function throws off measurements')
304 @requires_gil_enabled("gh-117783: immortalization of types affects traced method names")
305 def test_inst_method_calling(self):
306 obj = TracedClass(20)
307 self.tracer.runfunc(obj.inst_method_calling, 1)
308
309 expected = {
310 self.filemod + ('TracedClass.inst_method_calling',): 1,
311 self.filemod + ('TracedClass.inst_method_linear',): 1,
312 self.filemod + ('traced_func_linear',): 1,
313 }
314 self.assertEqual(self.tracer.results().calledfuncs, expected)
315
316 def test_traced_decorated_function(self):
317 self.tracer.runfunc(traced_decorated_function)
318
319 expected = {
320 self.filemod + ('traced_decorated_function',): 1,
321 self.filemod + ('decorator_fabric',): 1,
322 self.filemod + ('decorator2',): 1,
323 self.filemod + ('decorator1',): 1,
324 self.filemod + ('func',): 1,
325 }
326 self.assertEqual(self.tracer.results().calledfuncs, expected)
327
328
329 class TestCallers(unittest.TestCase):
330 """White-box testing of callers tracing"""
331 def setUp(self):
332 self.addCleanup(sys.settrace, sys.gettrace())
333 self.tracer = Trace(count=0, trace=0, countcallers=1)
334 self.filemod = my_file_and_modname()
335
336 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
337 'pre-existing trace function throws off measurements')
338 @requires_gil_enabled("gh-117783: immortalization of types affects traced method names")
339 def test_loop_caller_importing(self):
340 self.tracer.runfunc(traced_func_importing_caller, 1)
341
342 expected = {
343 ((os.path.splitext(trace.__file__)[0] + '.py', 'trace', 'Trace.runfunc'),
344 (self.filemod + ('traced_func_importing_caller',))): 1,
345 ((self.filemod + ('traced_func_simple_caller',)),
346 (self.filemod + ('traced_func_linear',))): 1,
347 ((self.filemod + ('traced_func_importing_caller',)),
348 (self.filemod + ('traced_func_simple_caller',))): 1,
349 ((self.filemod + ('traced_func_importing_caller',)),
350 (self.filemod + ('traced_func_importing',))): 1,
351 ((self.filemod + ('traced_func_importing',)),
352 (fix_ext_py(testmod.__file__), 'testmod', 'func')): 1,
353 }
354 self.assertEqual(self.tracer.results().callers, expected)
355
356
357 # Created separately for issue #3821
358 class TestCoverage(unittest.TestCase):
359 def setUp(self):
360 self.addCleanup(sys.settrace, sys.gettrace())
361
362 def tearDown(self):
363 rmtree(TESTFN)
364 unlink(TESTFN)
365
366 DEFAULT_SCRIPT = '''if True:
367 import unittest
368 from test.test_pprint import QueryTestCase
369 loader = unittest.TestLoader()
370 tests = loader.loadTestsFromTestCase(QueryTestCase)
371 tests(unittest.TestResult())
372 '''
373 def _coverage(self, tracer, cmd=DEFAULT_SCRIPT):
374 tracer.run(cmd)
375 r = tracer.results()
376 r.write_results(show_missing=True, summary=True, coverdir=TESTFN)
377
378 @requires_resource('cpu')
379 def test_coverage(self):
380 tracer = trace.Trace(trace=0, count=1)
381 with captured_stdout() as stdout:
382 self._coverage(tracer)
383 stdout = stdout.getvalue()
384 self.assertIn("pprint.py", stdout)
385 self.assertIn("case.py", stdout) # from unittest
386 files = os.listdir(TESTFN)
387 self.assertIn("pprint.cover", files)
388 self.assertIn("unittest.case.cover", files)
389
390 def test_coverage_ignore(self):
391 # Ignore all files, nothing should be traced nor printed
392 libpath = os.path.normpath(os.path.dirname(os.path.dirname(__file__)))
393 # sys.prefix does not work when running from a checkout
394 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,
395 libpath] + sys.path, trace=0, count=1)
396 with captured_stdout() as stdout:
397 self._coverage(tracer)
398 if os.path.exists(TESTFN):
399 files = os.listdir(TESTFN)
400 self.assertEqual(files, ['_importlib.cover']) # Ignore __import__
401
402 def test_issue9936(self):
403 tracer = trace.Trace(trace=0, count=1)
404 modname = 'test.tracedmodules.testmod'
405 # Ensure that the module is executed in import
406 if modname in sys.modules:
407 del sys.modules[modname]
408 cmd = ("import test.tracedmodules.testmod as t;"
409 "t.func(0); t.func2();")
410 with captured_stdout() as stdout:
411 self._coverage(tracer, cmd)
412 stdout.seek(0)
413 stdout.readline()
414 coverage = {}
415 for line in stdout:
416 lines, cov, module = line.split()[:3]
417 coverage[module] = (int(lines), int(cov[:-1]))
418 # XXX This is needed to run regrtest.py as a script
419 modname = trace._fullmodname(sys.modules[modname].__file__)
420 self.assertIn(modname, coverage)
421 self.assertEqual(coverage[modname], (5, 100))
422
423 def test_coverageresults_update(self):
424 # Update empty CoverageResults with a non-empty infile.
425 infile = TESTFN + '-infile'
426 with open(infile, 'wb') as f:
427 dump(({}, {}, {'caller': 1}), f, protocol=1)
428 self.addCleanup(unlink, infile)
429 results = trace.CoverageResults({}, {}, infile, {})
430 self.assertEqual(results.callers, {'caller': 1})
431
432 ### Tests that don't mess with sys.settrace and can be traced
433 ### themselves TODO: Skip tests that do mess with sys.settrace when
434 ### regrtest is invoked with -T option.
435 class Test_Ignore(unittest.TestCase):
436 def test_ignored(self):
437 jn = os.path.join
438 ignore = trace._Ignore(['x', 'y.z'], [jn('foo', 'bar')])
439 self.assertTrue(ignore.names('x.py', 'x'))
440 self.assertFalse(ignore.names('xy.py', 'xy'))
441 self.assertFalse(ignore.names('y.py', 'y'))
442 self.assertTrue(ignore.names(jn('foo', 'bar', 'baz.py'), 'baz'))
443 self.assertFalse(ignore.names(jn('bar', 'z.py'), 'z'))
444 # Matched before.
445 self.assertTrue(ignore.names(jn('bar', 'baz.py'), 'baz'))
446
447 # Created for Issue 31908 -- CLI utility not writing cover files
448 class TestCoverageCommandLineOutput(unittest.TestCase):
449
450 codefile = 'tmp.py'
451 coverfile = 'tmp.cover'
452
453 def setUp(self):
454 with open(self.codefile, 'w', encoding='iso-8859-15') as f:
455 f.write(textwrap.dedent('''\
456 # coding: iso-8859-15
457 x = 'spœm'
458 if []:
459 print('unreachable')
460 '''))
461
462 def tearDown(self):
463 unlink(self.codefile)
464 unlink(self.coverfile)
465
466 def test_cover_files_written_no_highlight(self):
467 # Test also that the cover file for the trace module is not created
468 # (issue #34171).
469 tracedir = os.path.dirname(os.path.abspath(trace.__file__))
470 tracecoverpath = os.path.join(tracedir, 'trace.cover')
471 unlink(tracecoverpath)
472
473 argv = '-m trace --count'.split() + [self.codefile]
474 status, stdout, stderr = assert_python_ok(*argv)
475 self.assertEqual(stderr, b'')
476 self.assertFalse(os.path.exists(tracecoverpath))
477 self.assertTrue(os.path.exists(self.coverfile))
478 with open(self.coverfile, encoding='iso-8859-15') as f:
479 self.assertEqual(f.read(),
480 " # coding: iso-8859-15\n"
481 " 1: x = 'spœm'\n"
482 " 1: if []:\n"
483 " print('unreachable')\n"
484 )
485
486 def test_cover_files_written_with_highlight(self):
487 argv = '-m trace --count --missing'.split() + [self.codefile]
488 status, stdout, stderr = assert_python_ok(*argv)
489 self.assertTrue(os.path.exists(self.coverfile))
490 with open(self.coverfile, encoding='iso-8859-15') as f:
491 self.assertEqual(f.read(), textwrap.dedent('''\
492 # coding: iso-8859-15
493 1: x = 'spœm'
494 1: if []:
495 >>>>>> print('unreachable')
496 '''))
497
498 class TestCommandLine(unittest.TestCase):
499
500 def test_failures(self):
501 _errors = (
502 (b'progname is missing: required with the main options', '-l', '-T'),
503 (b'cannot specify both --listfuncs and (--trace or --count)', '-lc'),
504 (b'argument -R/--no-report: not allowed with argument -r/--report', '-rR'),
505 (b'must specify one of --trace, --count, --report, --listfuncs, or --trackcalls', '-g'),
506 (b'-r/--report requires -f/--file', '-r'),
507 (b'--summary can only be used with --count or --report', '-sT'),
508 (b'unrecognized arguments: -y', '-y'))
509 for message, *args in _errors:
510 *_, stderr = assert_python_failure('-m', 'trace', *args)
511 self.assertIn(message, stderr)
512
513 def test_listfuncs_flag_success(self):
514 filename = TESTFN + '.py'
515 modulename = os.path.basename(TESTFN)
516 with open(filename, 'w', encoding='utf-8') as fd:
517 self.addCleanup(unlink, filename)
518 fd.write("a = 1\n")
519 status, stdout, stderr = assert_python_ok('-m', 'trace', '-l', filename,
520 PYTHONIOENCODING='utf-8')
521 self.assertIn(b'functions called:', stdout)
522 expected = f'filename: {filename}, modulename: {modulename}, funcname: <module>'
523 self.assertIn(expected.encode(), stdout)
524
525 def test_sys_argv_list(self):
526 with open(TESTFN, 'w', encoding='utf-8') as fd:
527 self.addCleanup(unlink, TESTFN)
528 fd.write("import sys\n")
529 fd.write("print(type(sys.argv))\n")
530
531 status, direct_stdout, stderr = assert_python_ok(TESTFN)
532 status, trace_stdout, stderr = assert_python_ok('-m', 'trace', '-l', TESTFN,
533 PYTHONIOENCODING='utf-8')
534 self.assertIn(direct_stdout.strip(), trace_stdout)
535
536 def test_count_and_summary(self):
537 filename = f'{TESTFN}.py'
538 coverfilename = f'{TESTFN}.cover'
539 modulename = os.path.basename(TESTFN)
540 with open(filename, 'w', encoding='utf-8') as fd:
541 self.addCleanup(unlink, filename)
542 self.addCleanup(unlink, coverfilename)
543 fd.write(textwrap.dedent("""\
544 x = 1
545 y = 2
546
547 def f():
548 return x + y
549
550 for i in range(10):
551 f()
552 """))
553 status, stdout, _ = assert_python_ok('-m', 'trace', '-cs', filename,
554 PYTHONIOENCODING='utf-8')
555 stdout = stdout.decode()
556 self.assertEqual(status, 0)
557 self.assertIn('lines cov% module (path)', stdout)
558 self.assertIn(f'6 100% {modulename} ({filename})', stdout)
559
560 def test_run_as_module(self):
561 assert_python_ok('-m', 'trace', '-l', '--module', 'timeit', '-n', '1')
562 assert_python_failure('-m', 'trace', '-l', '--module', 'not_a_module_zzz')
563
564
565 class TestTrace(unittest.TestCase):
566 def setUp(self):
567 self.addCleanup(sys.settrace, sys.gettrace())
568 self.tracer = Trace(count=0, trace=1)
569 self.filemod = my_file_and_modname()
570
571 def test_no_source_file(self):
572 filename = "<unknown>"
573 co = traced_func_linear.__code__
574 co = co.replace(co_filename=filename)
575 f = FunctionType(co, globals())
576
577 with captured_stdout() as out:
578 self.tracer.runfunc(f, 2, 3)
579
580 out = out.getvalue().splitlines()
581 firstlineno = get_firstlineno(f)
582 self.assertIn(f" --- modulename: {self.filemod[1]}, funcname: {f.__code__.co_name}", out[0])
583 self.assertIn(f"{filename}({firstlineno + 1})", out[1])
584 self.assertIn(f"{filename}({firstlineno + 2})", out[2])
585 self.assertIn(f"{filename}({firstlineno + 3})", out[3])
586 self.assertIn(f"{filename}({firstlineno + 4})", out[4])
587
588
589 if __name__ == '__main__':
590 unittest.main()