Debian Codegraph @

lib-python/3/test/test_tracemalloc.py

raw symbols SCIP
1 import contextlib
2 import os
3 import sys
4 import unittest
5 from unittest.mock import patch
6 from test.support.script_helper import (assert_python_ok, assert_python_failure,
7 interpreter_requires_environment)
8 from test import support
9 from test.support import os_helper
10
11 try:
12 import _testcapi
13 except ImportError:
14 _testcapi = None
15
16
17 try:
18 import tracemalloc
19 except ImportError:
20 raise unittest.SkipTest("tracemalloc is required")
21
22 EMPTY_STRING_SIZE = sys.getsizeof(b'')
23 INVALID_NFRAME = (-1, 2**30)
24
25
26 def get_frames(nframe, lineno_delta):
27 frames = []
28 frame = sys._getframe(1)
29 for index in range(nframe):
30 code = frame.f_code
31 lineno = frame.f_lineno + lineno_delta
32 frames.append((code.co_filename, lineno))
33 lineno_delta = 0
34 frame = frame.f_back
35 if frame is None:
36 break
37 return tuple(frames)
38
39 def allocate_bytes(size):
40 nframe = tracemalloc.get_traceback_limit()
41 bytes_len = (size - EMPTY_STRING_SIZE)
42 frames = get_frames(nframe, 1)
43 data = b'x' * bytes_len
44 return data, tracemalloc.Traceback(frames, min(len(frames), nframe))
45
46 def create_snapshots():
47 traceback_limit = 2
48
49 # _tracemalloc._get_traces() returns a list of (domain, size,
50 # traceback_frames) tuples. traceback_frames is a tuple of (filename,
51 # line_number) tuples.
52 raw_traces = [
53 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
54 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
55 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
56
57 (1, 2, (('a.py', 5), ('b.py', 4)), 3),
58
59 (2, 66, (('b.py', 1),), 1),
60
61 (3, 7, (('<unknown>', 0),), 1),
62 ]
63 snapshot = tracemalloc.Snapshot(raw_traces, traceback_limit)
64
65 raw_traces2 = [
66 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
67 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
68 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
69
70 (2, 2, (('a.py', 5), ('b.py', 4)), 3),
71 (2, 5000, (('a.py', 5), ('b.py', 4)), 3),
72
73 (4, 400, (('c.py', 578),), 1),
74 ]
75 snapshot2 = tracemalloc.Snapshot(raw_traces2, traceback_limit)
76
77 return (snapshot, snapshot2)
78
79 def frame(filename, lineno):
80 return tracemalloc._Frame((filename, lineno))
81
82 def traceback(*frames):
83 return tracemalloc.Traceback(frames)
84
85 def traceback_lineno(filename, lineno):
86 return traceback((filename, lineno))
87
88 def traceback_filename(filename):
89 return traceback_lineno(filename, 0)
90
91
92 class TestTraceback(unittest.TestCase):
93 def test_repr(self):
94 def get_repr(*args) -> str:
95 return repr(tracemalloc.Traceback(*args))
96
97 self.assertEqual(get_repr(()), "<Traceback ()>")
98 self.assertEqual(get_repr((), 0), "<Traceback () total_nframe=0>")
99
100 frames = (("f1", 1), ("f2", 2))
101 exp_repr_frames = (
102 "(<Frame filename='f2' lineno=2>,"
103 " <Frame filename='f1' lineno=1>)"
104 )
105 self.assertEqual(get_repr(frames),
106 f"<Traceback {exp_repr_frames}>")
107 self.assertEqual(get_repr(frames, 2),
108 f"<Traceback {exp_repr_frames} total_nframe=2>")
109
110
111 class TestTracemallocEnabled(unittest.TestCase):
112 def setUp(self):
113 if tracemalloc.is_tracing():
114 self.skipTest("tracemalloc must be stopped before the test")
115
116 tracemalloc.start(1)
117
118 def tearDown(self):
119 tracemalloc.stop()
120
121 def test_get_tracemalloc_memory(self):
122 data = [allocate_bytes(123) for count in range(1000)]
123 size = tracemalloc.get_tracemalloc_memory()
124 self.assertGreaterEqual(size, 0)
125
126 tracemalloc.clear_traces()
127 size2 = tracemalloc.get_tracemalloc_memory()
128 self.assertGreaterEqual(size2, 0)
129 self.assertLessEqual(size2, size)
130
131 def test_get_object_traceback(self):
132 tracemalloc.clear_traces()
133 obj_size = 12345
134 obj, obj_traceback = allocate_bytes(obj_size)
135 traceback = tracemalloc.get_object_traceback(obj)
136 self.assertEqual(traceback, obj_traceback)
137
138 def test_new_reference(self):
139 tracemalloc.clear_traces()
140 # gc.collect() indirectly calls PyList_ClearFreeList()
141 support.gc_collect()
142
143 # Create a list and "destroy it": put it in the PyListObject free list
144 obj = []
145 obj = None
146
147 # Create a list which should reuse the previously created empty list
148 obj = []
149
150 nframe = tracemalloc.get_traceback_limit()
151 frames = get_frames(nframe, -3)
152 obj_traceback = tracemalloc.Traceback(frames, min(len(frames), nframe))
153
154 traceback = tracemalloc.get_object_traceback(obj)
155 self.assertIsNotNone(traceback)
156 self.assertEqual(traceback, obj_traceback)
157
158 def test_set_traceback_limit(self):
159 obj_size = 10
160
161 tracemalloc.stop()
162 self.assertRaises(ValueError, tracemalloc.start, -1)
163
164 tracemalloc.stop()
165 tracemalloc.start(10)
166 obj2, obj2_traceback = allocate_bytes(obj_size)
167 traceback = tracemalloc.get_object_traceback(obj2)
168 self.assertEqual(len(traceback), 10)
169 self.assertEqual(traceback, obj2_traceback)
170
171 tracemalloc.stop()
172 tracemalloc.start(1)
173 obj, obj_traceback = allocate_bytes(obj_size)
174 traceback = tracemalloc.get_object_traceback(obj)
175 self.assertEqual(len(traceback), 1)
176 self.assertEqual(traceback, obj_traceback)
177
178 def find_trace(self, traces, traceback):
179 for trace in traces:
180 if trace[2] == traceback._frames:
181 return trace
182
183 self.fail("trace not found")
184
185 def test_get_traces(self):
186 tracemalloc.clear_traces()
187 obj_size = 12345
188 obj, obj_traceback = allocate_bytes(obj_size)
189
190 traces = tracemalloc._get_traces()
191 trace = self.find_trace(traces, obj_traceback)
192
193 self.assertIsInstance(trace, tuple)
194 domain, size, traceback, length = trace
195 self.assertEqual(size, obj_size)
196 self.assertEqual(traceback, obj_traceback._frames)
197
198 tracemalloc.stop()
199 self.assertEqual(tracemalloc._get_traces(), [])
200
201 def test_get_traces_intern_traceback(self):
202 # dummy wrappers to get more useful and identical frames in the traceback
203 def allocate_bytes2(size):
204 return allocate_bytes(size)
205 def allocate_bytes3(size):
206 return allocate_bytes2(size)
207 def allocate_bytes4(size):
208 return allocate_bytes3(size)
209
210 # Ensure that two identical tracebacks are not duplicated
211 tracemalloc.stop()
212 tracemalloc.start(4)
213 obj_size = 123
214 obj1, obj1_traceback = allocate_bytes4(obj_size)
215 obj2, obj2_traceback = allocate_bytes4(obj_size)
216
217 traces = tracemalloc._get_traces()
218
219 obj1_traceback._frames = tuple(reversed(obj1_traceback._frames))
220 obj2_traceback._frames = tuple(reversed(obj2_traceback._frames))
221
222 trace1 = self.find_trace(traces, obj1_traceback)
223 trace2 = self.find_trace(traces, obj2_traceback)
224 domain1, size1, traceback1, length1 = trace1
225 domain2, size2, traceback2, length2 = trace2
226 self.assertIs(traceback2, traceback1)
227
228 def test_get_traced_memory(self):
229 # Python allocates some internals objects, so the test must tolerate
230 # a small difference between the expected size and the real usage
231 max_error = 2048
232
233 # allocate one object
234 obj_size = 1024 * 1024
235 tracemalloc.clear_traces()
236 obj, obj_traceback = allocate_bytes(obj_size)
237 size, peak_size = tracemalloc.get_traced_memory()
238 self.assertGreaterEqual(size, obj_size)
239 self.assertGreaterEqual(peak_size, size)
240
241 self.assertLessEqual(size - obj_size, max_error)
242 self.assertLessEqual(peak_size - size, max_error)
243
244 # destroy the object
245 obj = None
246 size2, peak_size2 = tracemalloc.get_traced_memory()
247 self.assertLess(size2, size)
248 self.assertGreaterEqual(size - size2, obj_size - max_error)
249 self.assertGreaterEqual(peak_size2, peak_size)
250
251 # clear_traces() must reset traced memory counters
252 tracemalloc.clear_traces()
253 self.assertEqual(tracemalloc.get_traced_memory(), (0, 0))
254
255 # allocate another object
256 obj, obj_traceback = allocate_bytes(obj_size)
257 size, peak_size = tracemalloc.get_traced_memory()
258 self.assertGreaterEqual(size, obj_size)
259
260 # stop() also resets traced memory counters
261 tracemalloc.stop()
262 self.assertEqual(tracemalloc.get_traced_memory(), (0, 0))
263
264 def test_clear_traces(self):
265 obj, obj_traceback = allocate_bytes(123)
266 traceback = tracemalloc.get_object_traceback(obj)
267 self.assertIsNotNone(traceback)
268
269 tracemalloc.clear_traces()
270 traceback2 = tracemalloc.get_object_traceback(obj)
271 self.assertIsNone(traceback2)
272
273 def test_reset_peak(self):
274 # Python allocates some internals objects, so the test must tolerate
275 # a small difference between the expected size and the real usage
276 tracemalloc.clear_traces()
277
278 # Example: allocate a large piece of memory, temporarily
279 large_sum = sum(list(range(100000)))
280 size1, peak1 = tracemalloc.get_traced_memory()
281
282 # reset_peak() resets peak to traced memory: peak2 < peak1
283 tracemalloc.reset_peak()
284 size2, peak2 = tracemalloc.get_traced_memory()
285 self.assertGreaterEqual(peak2, size2)
286 self.assertLess(peak2, peak1)
287
288 # check that peak continue to be updated if new memory is allocated:
289 # peak3 > peak2
290 obj_size = 1024 * 1024
291 obj, obj_traceback = allocate_bytes(obj_size)
292 size3, peak3 = tracemalloc.get_traced_memory()
293 self.assertGreaterEqual(peak3, size3)
294 self.assertGreater(peak3, peak2)
295 self.assertGreaterEqual(peak3 - peak2, obj_size)
296
297 def test_is_tracing(self):
298 tracemalloc.stop()
299 self.assertFalse(tracemalloc.is_tracing())
300
301 tracemalloc.start()
302 self.assertTrue(tracemalloc.is_tracing())
303
304 def test_snapshot(self):
305 obj, source = allocate_bytes(123)
306
307 # take a snapshot
308 snapshot = tracemalloc.take_snapshot()
309
310 # This can vary
311 self.assertGreater(snapshot.traces[1].traceback.total_nframe, 10)
312
313 # write on disk
314 snapshot.dump(os_helper.TESTFN)
315 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
316
317 # load from disk
318 snapshot2 = tracemalloc.Snapshot.load(os_helper.TESTFN)
319 self.assertEqual(snapshot2.traces, snapshot.traces)
320
321 # tracemalloc must be tracing memory allocations to take a snapshot
322 tracemalloc.stop()
323 with self.assertRaises(RuntimeError) as cm:
324 tracemalloc.take_snapshot()
325 self.assertEqual(str(cm.exception),
326 "the tracemalloc module must be tracing memory "
327 "allocations to take a snapshot")
328
329 def test_snapshot_save_attr(self):
330 # take a snapshot with a new attribute
331 snapshot = tracemalloc.take_snapshot()
332 snapshot.test_attr = "new"
333 snapshot.dump(os_helper.TESTFN)
334 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
335
336 # load() should recreate the attribute
337 snapshot2 = tracemalloc.Snapshot.load(os_helper.TESTFN)
338 self.assertEqual(snapshot2.test_attr, "new")
339
340 def fork_child(self):
341 if not tracemalloc.is_tracing():
342 return 2
343
344 obj_size = 12345
345 obj, obj_traceback = allocate_bytes(obj_size)
346 traceback = tracemalloc.get_object_traceback(obj)
347 if traceback is None:
348 return 3
349
350 # everything is fine
351 return 0
352
353 @support.requires_fork()
354 def test_fork(self):
355 # check that tracemalloc is still working after fork
356 pid = os.fork()
357 if not pid:
358 # child
359 exitcode = 1
360 try:
361 exitcode = self.fork_child()
362 finally:
363 os._exit(exitcode)
364 else:
365 support.wait_process(pid, exitcode=0)
366
367 def test_no_incomplete_frames(self):
368 tracemalloc.stop()
369 tracemalloc.start(8)
370
371 def f(x):
372 def g():
373 return x
374 return g
375
376 obj = f(0).__closure__[0]
377 traceback = tracemalloc.get_object_traceback(obj)
378 self.assertIn("test_tracemalloc", traceback[-1].filename)
379 self.assertNotIn("test_tracemalloc", traceback[-2].filename)
380
381
382 class TestSnapshot(unittest.TestCase):
383 maxDiff = 4000
384
385 def test_create_snapshot(self):
386 raw_traces = [(0, 5, (('a.py', 2),), 10)]
387
388 with contextlib.ExitStack() as stack:
389 stack.enter_context(patch.object(tracemalloc, 'is_tracing',
390 return_value=True))
391 stack.enter_context(patch.object(tracemalloc, 'get_traceback_limit',
392 return_value=5))
393 stack.enter_context(patch.object(tracemalloc, '_get_traces',
394 return_value=raw_traces))
395
396 snapshot = tracemalloc.take_snapshot()
397 self.assertEqual(snapshot.traceback_limit, 5)
398 self.assertEqual(len(snapshot.traces), 1)
399 trace = snapshot.traces[0]
400 self.assertEqual(trace.size, 5)
401 self.assertEqual(trace.traceback.total_nframe, 10)
402 self.assertEqual(len(trace.traceback), 1)
403 self.assertEqual(trace.traceback[0].filename, 'a.py')
404 self.assertEqual(trace.traceback[0].lineno, 2)
405
406 def test_filter_traces(self):
407 snapshot, snapshot2 = create_snapshots()
408 filter1 = tracemalloc.Filter(False, "b.py")
409 filter2 = tracemalloc.Filter(True, "a.py", 2)
410 filter3 = tracemalloc.Filter(True, "a.py", 5)
411
412 original_traces = list(snapshot.traces._traces)
413
414 # exclude b.py
415 snapshot3 = snapshot.filter_traces((filter1,))
416 self.assertEqual(snapshot3.traces._traces, [
417 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
418 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
419 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
420 (1, 2, (('a.py', 5), ('b.py', 4)), 3),
421 (3, 7, (('<unknown>', 0),), 1),
422 ])
423
424 # filter_traces() must not touch the original snapshot
425 self.assertEqual(snapshot.traces._traces, original_traces)
426
427 # only include two lines of a.py
428 snapshot4 = snapshot3.filter_traces((filter2, filter3))
429 self.assertEqual(snapshot4.traces._traces, [
430 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
431 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
432 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
433 (1, 2, (('a.py', 5), ('b.py', 4)), 3),
434 ])
435
436 # No filter: just duplicate the snapshot
437 snapshot5 = snapshot.filter_traces(())
438 self.assertIsNot(snapshot5, snapshot)
439 self.assertIsNot(snapshot5.traces, snapshot.traces)
440 self.assertEqual(snapshot5.traces, snapshot.traces)
441
442 self.assertRaises(TypeError, snapshot.filter_traces, filter1)
443
444 def test_filter_traces_domain(self):
445 snapshot, snapshot2 = create_snapshots()
446 filter1 = tracemalloc.Filter(False, "a.py", domain=1)
447 filter2 = tracemalloc.Filter(True, "a.py", domain=1)
448
449 original_traces = list(snapshot.traces._traces)
450
451 # exclude a.py of domain 1
452 snapshot3 = snapshot.filter_traces((filter1,))
453 self.assertEqual(snapshot3.traces._traces, [
454 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
455 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
456 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
457 (2, 66, (('b.py', 1),), 1),
458 (3, 7, (('<unknown>', 0),), 1),
459 ])
460
461 # include domain 1
462 snapshot3 = snapshot.filter_traces((filter1,))
463 self.assertEqual(snapshot3.traces._traces, [
464 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
465 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
466 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
467 (2, 66, (('b.py', 1),), 1),
468 (3, 7, (('<unknown>', 0),), 1),
469 ])
470
471 def test_filter_traces_domain_filter(self):
472 snapshot, snapshot2 = create_snapshots()
473 filter1 = tracemalloc.DomainFilter(False, domain=3)
474 filter2 = tracemalloc.DomainFilter(True, domain=3)
475
476 # exclude domain 2
477 snapshot3 = snapshot.filter_traces((filter1,))
478 self.assertEqual(snapshot3.traces._traces, [
479 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
480 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
481 (0, 10, (('a.py', 2), ('b.py', 4)), 3),
482 (1, 2, (('a.py', 5), ('b.py', 4)), 3),
483 (2, 66, (('b.py', 1),), 1),
484 ])
485
486 # include domain 2
487 snapshot3 = snapshot.filter_traces((filter2,))
488 self.assertEqual(snapshot3.traces._traces, [
489 (3, 7, (('<unknown>', 0),), 1),
490 ])
491
492 def test_snapshot_group_by_line(self):
493 snapshot, snapshot2 = create_snapshots()
494 tb_0 = traceback_lineno('<unknown>', 0)
495 tb_a_2 = traceback_lineno('a.py', 2)
496 tb_a_5 = traceback_lineno('a.py', 5)
497 tb_b_1 = traceback_lineno('b.py', 1)
498 tb_c_578 = traceback_lineno('c.py', 578)
499
500 # stats per file and line
501 stats1 = snapshot.statistics('lineno')
502 self.assertEqual(stats1, [
503 tracemalloc.Statistic(tb_b_1, 66, 1),
504 tracemalloc.Statistic(tb_a_2, 30, 3),
505 tracemalloc.Statistic(tb_0, 7, 1),
506 tracemalloc.Statistic(tb_a_5, 2, 1),
507 ])
508
509 # stats per file and line (2)
510 stats2 = snapshot2.statistics('lineno')
511 self.assertEqual(stats2, [
512 tracemalloc.Statistic(tb_a_5, 5002, 2),
513 tracemalloc.Statistic(tb_c_578, 400, 1),
514 tracemalloc.Statistic(tb_a_2, 30, 3),
515 ])
516
517 # stats diff per file and line
518 statistics = snapshot2.compare_to(snapshot, 'lineno')
519 self.assertEqual(statistics, [
520 tracemalloc.StatisticDiff(tb_a_5, 5002, 5000, 2, 1),
521 tracemalloc.StatisticDiff(tb_c_578, 400, 400, 1, 1),
522 tracemalloc.StatisticDiff(tb_b_1, 0, -66, 0, -1),
523 tracemalloc.StatisticDiff(tb_0, 0, -7, 0, -1),
524 tracemalloc.StatisticDiff(tb_a_2, 30, 0, 3, 0),
525 ])
526
527 def test_snapshot_group_by_file(self):
528 snapshot, snapshot2 = create_snapshots()
529 tb_0 = traceback_filename('<unknown>')
530 tb_a = traceback_filename('a.py')
531 tb_b = traceback_filename('b.py')
532 tb_c = traceback_filename('c.py')
533
534 # stats per file
535 stats1 = snapshot.statistics('filename')
536 self.assertEqual(stats1, [
537 tracemalloc.Statistic(tb_b, 66, 1),
538 tracemalloc.Statistic(tb_a, 32, 4),
539 tracemalloc.Statistic(tb_0, 7, 1),
540 ])
541
542 # stats per file (2)
543 stats2 = snapshot2.statistics('filename')
544 self.assertEqual(stats2, [
545 tracemalloc.Statistic(tb_a, 5032, 5),
546 tracemalloc.Statistic(tb_c, 400, 1),
547 ])
548
549 # stats diff per file
550 diff = snapshot2.compare_to(snapshot, 'filename')
551 self.assertEqual(diff, [
552 tracemalloc.StatisticDiff(tb_a, 5032, 5000, 5, 1),
553 tracemalloc.StatisticDiff(tb_c, 400, 400, 1, 1),
554 tracemalloc.StatisticDiff(tb_b, 0, -66, 0, -1),
555 tracemalloc.StatisticDiff(tb_0, 0, -7, 0, -1),
556 ])
557
558 def test_snapshot_group_by_traceback(self):
559 snapshot, snapshot2 = create_snapshots()
560
561 # stats per file
562 tb1 = traceback(('a.py', 2), ('b.py', 4))
563 tb2 = traceback(('a.py', 5), ('b.py', 4))
564 tb3 = traceback(('b.py', 1))
565 tb4 = traceback(('<unknown>', 0))
566 stats1 = snapshot.statistics('traceback')
567 self.assertEqual(stats1, [
568 tracemalloc.Statistic(tb3, 66, 1),
569 tracemalloc.Statistic(tb1, 30, 3),
570 tracemalloc.Statistic(tb4, 7, 1),
571 tracemalloc.Statistic(tb2, 2, 1),
572 ])
573
574 # stats per file (2)
575 tb5 = traceback(('c.py', 578))
576 stats2 = snapshot2.statistics('traceback')
577 self.assertEqual(stats2, [
578 tracemalloc.Statistic(tb2, 5002, 2),
579 tracemalloc.Statistic(tb5, 400, 1),
580 tracemalloc.Statistic(tb1, 30, 3),
581 ])
582
583 # stats diff per file
584 diff = snapshot2.compare_to(snapshot, 'traceback')
585 self.assertEqual(diff, [
586 tracemalloc.StatisticDiff(tb2, 5002, 5000, 2, 1),
587 tracemalloc.StatisticDiff(tb5, 400, 400, 1, 1),
588 tracemalloc.StatisticDiff(tb3, 0, -66, 0, -1),
589 tracemalloc.StatisticDiff(tb4, 0, -7, 0, -1),
590 tracemalloc.StatisticDiff(tb1, 30, 0, 3, 0),
591 ])
592
593 self.assertRaises(ValueError,
594 snapshot.statistics, 'traceback', cumulative=True)
595
596 def test_snapshot_group_by_cumulative(self):
597 snapshot, snapshot2 = create_snapshots()
598 tb_0 = traceback_filename('<unknown>')
599 tb_a = traceback_filename('a.py')
600 tb_b = traceback_filename('b.py')
601 tb_a_2 = traceback_lineno('a.py', 2)
602 tb_a_5 = traceback_lineno('a.py', 5)
603 tb_b_1 = traceback_lineno('b.py', 1)
604 tb_b_4 = traceback_lineno('b.py', 4)
605
606 # per file
607 stats = snapshot.statistics('filename', True)
608 self.assertEqual(stats, [
609 tracemalloc.Statistic(tb_b, 98, 5),
610 tracemalloc.Statistic(tb_a, 32, 4),
611 tracemalloc.Statistic(tb_0, 7, 1),
612 ])
613
614 # per line
615 stats = snapshot.statistics('lineno', True)
616 self.assertEqual(stats, [
617 tracemalloc.Statistic(tb_b_1, 66, 1),
618 tracemalloc.Statistic(tb_b_4, 32, 4),
619 tracemalloc.Statistic(tb_a_2, 30, 3),
620 tracemalloc.Statistic(tb_0, 7, 1),
621 tracemalloc.Statistic(tb_a_5, 2, 1),
622 ])
623
624 def test_trace_format(self):
625 snapshot, snapshot2 = create_snapshots()
626 trace = snapshot.traces[0]
627 self.assertEqual(str(trace), 'b.py:4: 10 B')
628 traceback = trace.traceback
629 self.assertEqual(str(traceback), 'b.py:4')
630 frame = traceback[0]
631 self.assertEqual(str(frame), 'b.py:4')
632
633 def test_statistic_format(self):
634 snapshot, snapshot2 = create_snapshots()
635 stats = snapshot.statistics('lineno')
636 stat = stats[0]
637 self.assertEqual(str(stat),
638 'b.py:1: size=66 B, count=1, average=66 B')
639
640 def test_statistic_diff_format(self):
641 snapshot, snapshot2 = create_snapshots()
642 stats = snapshot2.compare_to(snapshot, 'lineno')
643 stat = stats[0]
644 self.assertEqual(str(stat),
645 'a.py:5: size=5002 B (+5000 B), count=2 (+1), average=2501 B')
646
647 def test_slices(self):
648 snapshot, snapshot2 = create_snapshots()
649 self.assertEqual(snapshot.traces[:2],
650 (snapshot.traces[0], snapshot.traces[1]))
651
652 traceback = snapshot.traces[0].traceback
653 self.assertEqual(traceback[:2],
654 (traceback[0], traceback[1]))
655
656 def test_format_traceback(self):
657 snapshot, snapshot2 = create_snapshots()
658 def getline(filename, lineno):
659 return ' <%s, %s>' % (filename, lineno)
660 with unittest.mock.patch('tracemalloc.linecache.getline',
661 side_effect=getline):
662 tb = snapshot.traces[0].traceback
663 self.assertEqual(tb.format(),
664 [' File "b.py", line 4',
665 ' <b.py, 4>',
666 ' File "a.py", line 2',
667 ' <a.py, 2>'])
668
669 self.assertEqual(tb.format(limit=1),
670 [' File "a.py", line 2',
671 ' <a.py, 2>'])
672
673 self.assertEqual(tb.format(limit=-1),
674 [' File "b.py", line 4',
675 ' <b.py, 4>'])
676
677 self.assertEqual(tb.format(most_recent_first=True),
678 [' File "a.py", line 2',
679 ' <a.py, 2>',
680 ' File "b.py", line 4',
681 ' <b.py, 4>'])
682
683 self.assertEqual(tb.format(limit=1, most_recent_first=True),
684 [' File "a.py", line 2',
685 ' <a.py, 2>'])
686
687 self.assertEqual(tb.format(limit=-1, most_recent_first=True),
688 [' File "b.py", line 4',
689 ' <b.py, 4>'])
690
691
692 class TestFilters(unittest.TestCase):
693 maxDiff = 2048
694
695 def test_filter_attributes(self):
696 # test default values
697 f = tracemalloc.Filter(True, "abc")
698 self.assertEqual(f.inclusive, True)
699 self.assertEqual(f.filename_pattern, "abc")
700 self.assertIsNone(f.lineno)
701 self.assertEqual(f.all_frames, False)
702
703 # test custom values
704 f = tracemalloc.Filter(False, "test.py", 123, True)
705 self.assertEqual(f.inclusive, False)
706 self.assertEqual(f.filename_pattern, "test.py")
707 self.assertEqual(f.lineno, 123)
708 self.assertEqual(f.all_frames, True)
709
710 # parameters passed by keyword
711 f = tracemalloc.Filter(inclusive=False, filename_pattern="test.py", lineno=123, all_frames=True)
712 self.assertEqual(f.inclusive, False)
713 self.assertEqual(f.filename_pattern, "test.py")
714 self.assertEqual(f.lineno, 123)
715 self.assertEqual(f.all_frames, True)
716
717 # read-only attribute
718 self.assertRaises(AttributeError, setattr, f, "filename_pattern", "abc")
719
720 def test_filter_match(self):
721 # filter without line number
722 f = tracemalloc.Filter(True, "abc")
723 self.assertTrue(f._match_frame("abc", 0))
724 self.assertTrue(f._match_frame("abc", 5))
725 self.assertTrue(f._match_frame("abc", 10))
726 self.assertFalse(f._match_frame("12356", 0))
727 self.assertFalse(f._match_frame("12356", 5))
728 self.assertFalse(f._match_frame("12356", 10))
729
730 f = tracemalloc.Filter(False, "abc")
731 self.assertFalse(f._match_frame("abc", 0))
732 self.assertFalse(f._match_frame("abc", 5))
733 self.assertFalse(f._match_frame("abc", 10))
734 self.assertTrue(f._match_frame("12356", 0))
735 self.assertTrue(f._match_frame("12356", 5))
736 self.assertTrue(f._match_frame("12356", 10))
737
738 # filter with line number > 0
739 f = tracemalloc.Filter(True, "abc", 5)
740 self.assertFalse(f._match_frame("abc", 0))
741 self.assertTrue(f._match_frame("abc", 5))
742 self.assertFalse(f._match_frame("abc", 10))
743 self.assertFalse(f._match_frame("12356", 0))
744 self.assertFalse(f._match_frame("12356", 5))
745 self.assertFalse(f._match_frame("12356", 10))
746
747 f = tracemalloc.Filter(False, "abc", 5)
748 self.assertTrue(f._match_frame("abc", 0))
749 self.assertFalse(f._match_frame("abc", 5))
750 self.assertTrue(f._match_frame("abc", 10))
751 self.assertTrue(f._match_frame("12356", 0))
752 self.assertTrue(f._match_frame("12356", 5))
753 self.assertTrue(f._match_frame("12356", 10))
754
755 # filter with line number 0
756 f = tracemalloc.Filter(True, "abc", 0)
757 self.assertTrue(f._match_frame("abc", 0))
758 self.assertFalse(f._match_frame("abc", 5))
759 self.assertFalse(f._match_frame("abc", 10))
760 self.assertFalse(f._match_frame("12356", 0))
761 self.assertFalse(f._match_frame("12356", 5))
762 self.assertFalse(f._match_frame("12356", 10))
763
764 f = tracemalloc.Filter(False, "abc", 0)
765 self.assertFalse(f._match_frame("abc", 0))
766 self.assertTrue(f._match_frame("abc", 5))
767 self.assertTrue(f._match_frame("abc", 10))
768 self.assertTrue(f._match_frame("12356", 0))
769 self.assertTrue(f._match_frame("12356", 5))
770 self.assertTrue(f._match_frame("12356", 10))
771
772 def test_filter_match_filename(self):
773 def fnmatch(inclusive, filename, pattern):
774 f = tracemalloc.Filter(inclusive, pattern)
775 return f._match_frame(filename, 0)
776
777 self.assertTrue(fnmatch(True, "abc", "abc"))
778 self.assertFalse(fnmatch(True, "12356", "abc"))
779 self.assertFalse(fnmatch(True, "<unknown>", "abc"))
780
781 self.assertFalse(fnmatch(False, "abc", "abc"))
782 self.assertTrue(fnmatch(False, "12356", "abc"))
783 self.assertTrue(fnmatch(False, "<unknown>", "abc"))
784
785 def test_filter_match_filename_joker(self):
786 def fnmatch(filename, pattern):
787 filter = tracemalloc.Filter(True, pattern)
788 return filter._match_frame(filename, 0)
789
790 # empty string
791 self.assertFalse(fnmatch('abc', ''))
792 self.assertFalse(fnmatch('', 'abc'))
793 self.assertTrue(fnmatch('', ''))
794 self.assertTrue(fnmatch('', '*'))
795
796 # no *
797 self.assertTrue(fnmatch('abc', 'abc'))
798 self.assertFalse(fnmatch('abc', 'abcd'))
799 self.assertFalse(fnmatch('abc', 'def'))
800
801 # a*
802 self.assertTrue(fnmatch('abc', 'a*'))
803 self.assertTrue(fnmatch('abc', 'abc*'))
804 self.assertFalse(fnmatch('abc', 'b*'))
805 self.assertFalse(fnmatch('abc', 'abcd*'))
806
807 # a*b
808 self.assertTrue(fnmatch('abc', 'a*c'))
809 self.assertTrue(fnmatch('abcdcx', 'a*cx'))
810 self.assertFalse(fnmatch('abb', 'a*c'))
811 self.assertFalse(fnmatch('abcdce', 'a*cx'))
812
813 # a*b*c
814 self.assertTrue(fnmatch('abcde', 'a*c*e'))
815 self.assertTrue(fnmatch('abcbdefeg', 'a*bd*eg'))
816 self.assertFalse(fnmatch('abcdd', 'a*c*e'))
817 self.assertFalse(fnmatch('abcbdefef', 'a*bd*eg'))
818
819 # replace .pyc suffix with .py
820 self.assertTrue(fnmatch('a.pyc', 'a.py'))
821 self.assertTrue(fnmatch('a.py', 'a.pyc'))
822
823 if os.name == 'nt':
824 # case insensitive
825 self.assertTrue(fnmatch('aBC', 'ABc'))
826 self.assertTrue(fnmatch('aBcDe', 'Ab*dE'))
827
828 self.assertTrue(fnmatch('a.pyc', 'a.PY'))
829 self.assertTrue(fnmatch('a.py', 'a.PYC'))
830 else:
831 # case sensitive
832 self.assertFalse(fnmatch('aBC', 'ABc'))
833 self.assertFalse(fnmatch('aBcDe', 'Ab*dE'))
834
835 self.assertFalse(fnmatch('a.pyc', 'a.PY'))
836 self.assertFalse(fnmatch('a.py', 'a.PYC'))
837
838 if os.name == 'nt':
839 # normalize alternate separator "/" to the standard separator "\"
840 self.assertTrue(fnmatch(r'a/b', r'a\b'))
841 self.assertTrue(fnmatch(r'a\b', r'a/b'))
842 self.assertTrue(fnmatch(r'a/b\c', r'a\b/c'))
843 self.assertTrue(fnmatch(r'a/b/c', r'a\b\c'))
844 else:
845 # there is no alternate separator
846 self.assertFalse(fnmatch(r'a/b', r'a\b'))
847 self.assertFalse(fnmatch(r'a\b', r'a/b'))
848 self.assertFalse(fnmatch(r'a/b\c', r'a\b/c'))
849 self.assertFalse(fnmatch(r'a/b/c', r'a\b\c'))
850
851 # as of 3.5, .pyo is no longer munged to .py
852 self.assertFalse(fnmatch('a.pyo', 'a.py'))
853
854 def test_filter_match_trace(self):
855 t1 = (("a.py", 2), ("b.py", 3))
856 t2 = (("b.py", 4), ("b.py", 5))
857 t3 = (("c.py", 5), ('<unknown>', 0))
858 unknown = (('<unknown>', 0),)
859
860 f = tracemalloc.Filter(True, "b.py", all_frames=True)
861 self.assertTrue(f._match_traceback(t1))
862 self.assertTrue(f._match_traceback(t2))
863 self.assertFalse(f._match_traceback(t3))
864 self.assertFalse(f._match_traceback(unknown))
865
866 f = tracemalloc.Filter(True, "b.py", all_frames=False)
867 self.assertFalse(f._match_traceback(t1))
868 self.assertTrue(f._match_traceback(t2))
869 self.assertFalse(f._match_traceback(t3))
870 self.assertFalse(f._match_traceback(unknown))
871
872 f = tracemalloc.Filter(False, "b.py", all_frames=True)
873 self.assertFalse(f._match_traceback(t1))
874 self.assertFalse(f._match_traceback(t2))
875 self.assertTrue(f._match_traceback(t3))
876 self.assertTrue(f._match_traceback(unknown))
877
878 f = tracemalloc.Filter(False, "b.py", all_frames=False)
879 self.assertTrue(f._match_traceback(t1))
880 self.assertFalse(f._match_traceback(t2))
881 self.assertTrue(f._match_traceback(t3))
882 self.assertTrue(f._match_traceback(unknown))
883
884 f = tracemalloc.Filter(False, "<unknown>", all_frames=False)
885 self.assertTrue(f._match_traceback(t1))
886 self.assertTrue(f._match_traceback(t2))
887 self.assertTrue(f._match_traceback(t3))
888 self.assertFalse(f._match_traceback(unknown))
889
890 f = tracemalloc.Filter(True, "<unknown>", all_frames=True)
891 self.assertFalse(f._match_traceback(t1))
892 self.assertFalse(f._match_traceback(t2))
893 self.assertTrue(f._match_traceback(t3))
894 self.assertTrue(f._match_traceback(unknown))
895
896 f = tracemalloc.Filter(False, "<unknown>", all_frames=True)
897 self.assertTrue(f._match_traceback(t1))
898 self.assertTrue(f._match_traceback(t2))
899 self.assertFalse(f._match_traceback(t3))
900 self.assertFalse(f._match_traceback(unknown))
901
902
903 class TestCommandLine(unittest.TestCase):
904 def test_env_var_disabled_by_default(self):
905 # not tracing by default
906 code = 'import tracemalloc; print(tracemalloc.is_tracing())'
907 ok, stdout, stderr = assert_python_ok('-c', code)
908 stdout = stdout.rstrip()
909 self.assertEqual(stdout, b'False')
910
911 @unittest.skipIf(interpreter_requires_environment(),
912 'Cannot run -E tests when PYTHON env vars are required.')
913 def test_env_var_ignored_with_E(self):
914 """PYTHON* environment variables must be ignored when -E is present."""
915 code = 'import tracemalloc; print(tracemalloc.is_tracing())'
916 ok, stdout, stderr = assert_python_ok('-E', '-c', code, PYTHONTRACEMALLOC='1')
917 stdout = stdout.rstrip()
918 self.assertEqual(stdout, b'False')
919
920 def test_env_var_disabled(self):
921 # tracing at startup
922 code = 'import tracemalloc; print(tracemalloc.is_tracing())'
923 ok, stdout, stderr = assert_python_ok('-c', code, PYTHONTRACEMALLOC='0')
924 stdout = stdout.rstrip()
925 self.assertEqual(stdout, b'False')
926
927 def test_env_var_enabled_at_startup(self):
928 # tracing at startup
929 code = 'import tracemalloc; print(tracemalloc.is_tracing())'
930 ok, stdout, stderr = assert_python_ok('-c', code, PYTHONTRACEMALLOC='1')
931 stdout = stdout.rstrip()
932 self.assertEqual(stdout, b'True')
933
934 def test_env_limit(self):
935 # start and set the number of frames
936 code = 'import tracemalloc; print(tracemalloc.get_traceback_limit())'
937 ok, stdout, stderr = assert_python_ok('-c', code, PYTHONTRACEMALLOC='10')
938 stdout = stdout.rstrip()
939 self.assertEqual(stdout, b'10')
940
941 def check_env_var_invalid(self, nframe):
942 with support.SuppressCrashReport():
943 ok, stdout, stderr = assert_python_failure(
944 '-c', 'pass',
945 PYTHONTRACEMALLOC=str(nframe))
946
947 if b'ValueError: the number of frames must be in range' in stderr:
948 return
949 if b'PYTHONTRACEMALLOC: invalid number of frames' in stderr:
950 return
951 self.fail(f"unexpected output: {stderr!a}")
952
953
954 def test_env_var_invalid(self):
955 for nframe in INVALID_NFRAME:
956 with self.subTest(nframe=nframe):
957 self.check_env_var_invalid(nframe)
958
959 def test_sys_xoptions(self):
960 for xoptions, nframe in (
961 ('tracemalloc', 1),
962 ('tracemalloc=1', 1),
963 ('tracemalloc=15', 15),
964 ):
965 with self.subTest(xoptions=xoptions, nframe=nframe):
966 code = 'import tracemalloc; print(tracemalloc.get_traceback_limit())'
967 ok, stdout, stderr = assert_python_ok('-X', xoptions, '-c', code)
968 stdout = stdout.rstrip()
969 self.assertEqual(stdout, str(nframe).encode('ascii'))
970
971 def check_sys_xoptions_invalid(self, nframe):
972 args = ('-X', 'tracemalloc=%s' % nframe, '-c', 'pass')
973 with support.SuppressCrashReport():
974 ok, stdout, stderr = assert_python_failure(*args)
975
976 if b'ValueError: the number of frames must be in range' in stderr:
977 return
978 if b'-X tracemalloc=NFRAME: invalid number of frames' in stderr:
979 return
980 self.fail(f"unexpected output: {stderr!a}")
981
982 def test_sys_xoptions_invalid(self):
983 for nframe in INVALID_NFRAME:
984 with self.subTest(nframe=nframe):
985 self.check_sys_xoptions_invalid(nframe)
986
987 @unittest.skipIf(_testcapi is None, 'need _testcapi')
988 def test_pymem_alloc0(self):
989 # Issue #21639: Check that PyMem_Malloc(0) with tracemalloc enabled
990 # does not crash.
991 code = 'import _testcapi; _testcapi.test_pymem_alloc0(); 1'
992 assert_python_ok('-X', 'tracemalloc', '-c', code)
993
994
995 @unittest.skipIf(_testcapi is None, 'need _testcapi')
996 class TestCAPI(unittest.TestCase):
997 maxDiff = 80 * 20
998
999 def setUp(self):
1000 if tracemalloc.is_tracing():
1001 self.skipTest("tracemalloc must be stopped before the test")
1002
1003 self.domain = 5
1004 self.size = 123
1005 self.obj = allocate_bytes(self.size)[0]
1006
1007 # for the type "object", id(obj) is the address of its memory block.
1008 # This type is not tracked by the garbage collector
1009 self.ptr = id(self.obj)
1010
1011 def tearDown(self):
1012 tracemalloc.stop()
1013
1014 def get_traceback(self):
1015 frames = _testcapi.tracemalloc_get_traceback(self.domain, self.ptr)
1016 if frames is not None:
1017 return tracemalloc.Traceback(frames)
1018 else:
1019 return None
1020
1021 def track(self, release_gil=False, nframe=1):
1022 frames = get_frames(nframe, 1)
1023 _testcapi.tracemalloc_track(self.domain, self.ptr, self.size,
1024 release_gil)
1025 return frames
1026
1027 def untrack(self):
1028 _testcapi.tracemalloc_untrack(self.domain, self.ptr)
1029
1030 def get_traced_memory(self):
1031 # Get the traced size in the domain
1032 snapshot = tracemalloc.take_snapshot()
1033 domain_filter = tracemalloc.DomainFilter(True, self.domain)
1034 snapshot = snapshot.filter_traces([domain_filter])
1035 return sum(trace.size for trace in snapshot.traces)
1036
1037 def check_track(self, release_gil):
1038 nframe = 5
1039 tracemalloc.start(nframe)
1040
1041 size = tracemalloc.get_traced_memory()[0]
1042
1043 frames = self.track(release_gil, nframe)
1044 self.assertEqual(self.get_traceback(),
1045 tracemalloc.Traceback(frames))
1046
1047 self.assertEqual(self.get_traced_memory(), self.size)
1048
1049 def test_track(self):
1050 self.check_track(False)
1051
1052 def test_track_without_gil(self):
1053 # check that calling _PyTraceMalloc_Track() without holding the GIL
1054 # works too
1055 self.check_track(True)
1056
1057 def test_track_already_tracked(self):
1058 nframe = 5
1059 tracemalloc.start(nframe)
1060
1061 # track a first time
1062 self.track()
1063
1064 # calling _PyTraceMalloc_Track() must remove the old trace and add
1065 # a new trace with the new traceback
1066 frames = self.track(nframe=nframe)
1067 self.assertEqual(self.get_traceback(),
1068 tracemalloc.Traceback(frames))
1069
1070 def test_untrack(self):
1071 tracemalloc.start()
1072
1073 self.track()
1074 self.assertIsNotNone(self.get_traceback())
1075 self.assertEqual(self.get_traced_memory(), self.size)
1076
1077 # untrack must remove the trace
1078 self.untrack()
1079 self.assertIsNone(self.get_traceback())
1080 self.assertEqual(self.get_traced_memory(), 0)
1081
1082 # calling _PyTraceMalloc_Untrack() multiple times must not crash
1083 self.untrack()
1084 self.untrack()
1085
1086 def test_stop_track(self):
1087 tracemalloc.start()
1088 tracemalloc.stop()
1089
1090 with self.assertRaises(RuntimeError):
1091 self.track()
1092 self.assertIsNone(self.get_traceback())
1093
1094 def test_stop_untrack(self):
1095 tracemalloc.start()
1096 self.track()
1097
1098 tracemalloc.stop()
1099 with self.assertRaises(RuntimeError):
1100 self.untrack()
1101
1102
1103 if __name__ == "__main__":
1104 unittest.main()