Skip to content

Commit be75241

Browse files
committed
gh-158232: Fix _compare_grouped_stats mutating old_group and a typo
1 parent 8122ff4 commit be75241

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎Lib/test/test_tracemalloc.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,23 @@ def test_snapshot_group_by_traceback(self):
598598
self.assertRaises(ValueError,
599599
snapshot.statistics, 'traceback', cumulative=True)
600600

601+
def test_compare_to_does_not_mutate_group(self):
602+
# gh-158232: _compare_grouped_stats() used to pop from old_group,
603+
# silently draining the caller's dict.
604+
tb_a = traceback(('f.py', 1))
605+
tb_b = traceback(('f.py', 2))
606+
tb_c = traceback(('f.py', 3))
607+
608+
old = {tb_a: tracemalloc.Statistic(tb_a, 100, 2),
609+
tb_b: tracemalloc.Statistic(tb_b, 50, 1)}
610+
new = {tb_a: tracemalloc.Statistic(tb_a, 200, 3),
611+
tb_c: tracemalloc.Statistic(tb_c, 10, 1)}
612+
old_copy = dict(old)
613+
614+
tracemalloc._compare_grouped_stats(old, new)
615+
616+
self.assertEqual(old, old_copy)
617+
601618
def test_snapshot_group_by_cumulative(self):
602619
snapshot, snapshot2 = create_snapshots()
603620
tb_0 = traceback_filename('<unknown>')

‎Lib/tracemalloc.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ def _sort_key(self):
119119

120120
def _compare_grouped_stats(old_group, new_group):
121121
statistics = []
122+
old_group = dict(old_group)
122123
for traceback, stat in new_group.items():
123124
previous = old_group.pop(traceback, None)
124125
if previous is not None:
@@ -478,7 +479,7 @@ def _group_by(self, key_type, cumulative):
478479
if key_type not in ('traceback', 'filename', 'lineno'):
479480
raise ValueError("unknown key_type: %r" % (key_type,))
480481
if cumulative and key_type not in ('lineno', 'filename'):
481-
raise ValueError("cumulative mode cannot by used "
482+
raise ValueError("cumulative mode cannot be used "
482483
"with key type %r" % key_type)
483484

484485
stats = {}

0 commit comments

Comments
 (0)