Skip to content

Commit f7f0f0b

Browse files
committed
gh-145865: Fix CoverageResults.__init__ to copy the counts dict
Fix typo where self.counter was assigned instead of self.counts, causing the counts dict to not be copied. This made CoverageResults.update() mutate the caller's original dict. The fix changes self.counter = self.counts.copy() to self.counts = self.counts.copy(), matching the pattern used for calledfuncs and callers on the following lines. Also removes the dead self.counter attribute which was never read anywhere in the codebase.
1 parent 678eefd commit f7f0f0b

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

Lib/test/test_trace.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -590,5 +590,33 @@ def test_no_source_file(self):
590590
self.assertIn(f"{filename}({firstlineno + 4})", out[4])
591591

592592

593+
class TestCoverageResultsInit(unittest.TestCase):
594+
def test_counts_dict_is_copied(self):
595+
# gh-145865: CoverageResults.__init__ should copy the counts dict
596+
# to avoid mutating the caller's dict on update()
597+
from trace import CoverageResults
598+
599+
counts = {}
600+
cr = CoverageResults(counts=counts)
601+
cr.update(CoverageResults(counts={("file.py", 1): 5}))
602+
self.assertEqual(counts, {}) # original must not be mutated
603+
604+
def test_calledfuncs_dict_is_copied(self):
605+
from trace import CoverageResults
606+
607+
calledfuncs = {}
608+
cr = CoverageResults(calledfuncs=calledfuncs)
609+
cr.update(CoverageResults(calledfuncs={("file.py", "mod", "func"): 1}))
610+
self.assertEqual(calledfuncs, {})
611+
612+
def test_callers_dict_is_copied(self):
613+
from trace import CoverageResults
614+
615+
callers = {}
616+
cr = CoverageResults(callers=callers)
617+
cr.update(CoverageResults(callers={(("a.py", "m", "f"), ("b.py", "m", "g")): 1}))
618+
self.assertEqual(callers, {})
619+
620+
593621
if __name__ == '__main__':
594622
unittest.main()

Lib/trace.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ def __init__(self, counts=None, calledfuncs=None, infile=None,
155155
self.counts = counts
156156
if self.counts is None:
157157
self.counts = {}
158-
self.counter = self.counts.copy() # map (filename, lineno) to count
158+
self.counts = self.counts.copy() # map (filename, lineno) to count
159159
self.calledfuncs = calledfuncs
160160
if self.calledfuncs is None:
161161
self.calledfuncs = {}

0 commit comments

Comments
 (0)