Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d11f76f

Browse files
committed
Issue #11761: make tests for gc.get_count() less fragile
2 parents c800af4 + e9b2a4c commit d11f76f

1 file changed

Lines changed: 27 additions & 16 deletions

File tree

Lib/test/test_gc.py

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -241,32 +241,43 @@ def __del__(self):
241241
# The following two tests are fragile:
242242
# They precisely count the number of allocations,
243243
# which is highly implementation-dependent.
244-
# For example:
245-
# - disposed tuples are not freed, but reused
246-
# - the call to assertEqual somehow avoids building its args tuple
244+
# For example, disposed tuples are not freed, but reused.
245+
# To minimize variations, though, we first store the get_count() results
246+
# and check them at the end.
247247
@refcount_test
248248
def test_get_count(self):
249-
# Avoid future allocation of method object
250-
assertEqual = self._baseAssertEqual
251249
gc.collect()
252-
assertEqual(gc.get_count(), (0, 0, 0))
253-
a = dict()
254-
# since gc.collect(), we created two objects:
255-
# the dict, and the tuple returned by get_count()
256-
assertEqual(gc.get_count(), (2, 0, 0))
250+
a, b, c = gc.get_count()
251+
x = []
252+
d, e, f = gc.get_count()
253+
self.assertEqual((b, c), (0, 0))
254+
self.assertEqual((e, f), (0, 0))
255+
# This is less fragile than asserting that a equals 0.
256+
self.assertLess(a, 5)
257+
# Between the two calls to get_count(), at least one object was
258+
# created (the list).
259+
self.assertGreater(d, a)
257260

258261
@refcount_test
259262
def test_collect_generations(self):
260-
# Avoid future allocation of method object
261-
assertEqual = self.assertEqual
262263
gc.collect()
263-
a = dict()
264+
# This object will "trickle" into generation N + 1 after
265+
# each call to collect(N)
266+
x = []
264267
gc.collect(0)
265-
assertEqual(gc.get_count(), (0, 1, 0))
268+
# x is now in gen 1
269+
a, b, c = gc.get_count()
266270
gc.collect(1)
267-
assertEqual(gc.get_count(), (0, 0, 1))
271+
# x is now in gen 2
272+
d, e, f = gc.get_count()
268273
gc.collect(2)
269-
assertEqual(gc.get_count(), (0, 0, 0))
274+
# x is now in gen 3
275+
g, h, i = gc.get_count()
276+
# We don't check a, d, g since their exact values depends on
277+
# internal implementation details of the interpreter.
278+
self.assertEqual((b, c), (1, 0))
279+
self.assertEqual((e, f), (0, 1))
280+
self.assertEqual((h, i), (0, 0))
270281

271282
def test_trashcan(self):
272283
class Ouch:

0 commit comments

Comments
 (0)