Skip to content

Commit 4ae8ece

Browse files
gpsheadmiss-islington
authored andcommitted
bpo-34200: Fix non-determinism of test_pkg (GH-9248)
This causes the tearDown code to only unimport the test modules specifically created as part of each test via the self.mkhier method rather than abusing test.support.modules_setup() and the scary test.support.modules_cleanup() code. https://bugs.python.org/issue34200
1 parent ed709d5 commit 4ae8ece

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

Lib/test/test_pkg.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import tempfile
66
import textwrap
77
import unittest
8-
from test import support
98

109

1110
# Helpers to create and destroy hierarchies.
@@ -50,11 +49,13 @@ def setUp(self):
5049
self.root = None
5150
self.pkgname = None
5251
self.syspath = list(sys.path)
53-
self.modules_before = support.modules_setup()
52+
self.modules_to_cleanup = set() # Populated by mkhier().
5453

5554
def tearDown(self):
5655
sys.path[:] = self.syspath
57-
support.modules_cleanup(*self.modules_before)
56+
for modulename in self.modules_to_cleanup:
57+
if modulename in sys.modules:
58+
del sys.modules[modulename]
5859
if self.root: # Only clean if the test was actually run
5960
cleanout(self.root)
6061

@@ -75,17 +76,17 @@ def mkhier(self, descr):
7576
os.mkdir(root)
7677
for name, contents in descr:
7778
comps = name.split()
79+
self.modules_to_cleanup.add('.'.join(comps))
7880
fullname = root
7981
for c in comps:
8082
fullname = os.path.join(fullname, c)
8183
if contents is None:
8284
os.mkdir(fullname)
8385
else:
84-
f = open(fullname, "w")
85-
f.write(contents)
86-
if contents and contents[-1] != '\n':
87-
f.write('\n')
88-
f.close()
86+
with open(fullname, "w") as f:
87+
f.write(contents)
88+
if not contents.endswith('\n'):
89+
f.write('\n')
8990
self.root = root
9091
# package name is the name of the first item
9192
self.pkgname = descr[0][0]
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixed non-deterministic flakiness of test_pkg by not using the scary
2+
test.support.module_cleanup() logic to save and restore sys.modules contents
3+
between test cases.

0 commit comments

Comments
 (0)