summaryrefslogtreecommitdiff
path: root/tests/helpers.py
diff options
context:
space:
mode:
authorNed Batchelder <ned@nedbatchelder.com>2017-02-11 11:13:30 -0500
committerNed Batchelder <ned@nedbatchelder.com>2017-02-11 11:13:30 -0500
commit8db9a3d0ec940128877d6ddf326b6d9ec721c23f (patch)
treec84da799cbeabea4cef429b51db89823a0c72ba8 /tests/helpers.py
parentfac9f94f1665c7dc9ca2eab676c1d3fc52a854fb (diff)
downloadpython-coveragepy-git-8db9a3d0ec940128877d6ddf326b6d9ec721c23f.tar.gz
Refactor module cleaning so we can use it outside of tests
Diffstat (limited to 'tests/helpers.py')
-rw-r--r--tests/helpers.py31
1 files changed, 30 insertions, 1 deletions
diff --git a/tests/helpers.py b/tests/helpers.py
index cbb6e01c..f10169a9 100644
--- a/tests/helpers.py
+++ b/tests/helpers.py
@@ -3,13 +3,18 @@
"""Helpers for coverage.py tests."""
+import glob
+import itertools
import os
import re
+import shutil
import subprocess
import sys
+from unittest_mixins import ModuleCleaner
+
from coverage import env
-from coverage.backward import unicode_class
+from coverage.backward import invalidate_import_caches, unicode_class
from coverage.misc import output_encoding
@@ -99,3 +104,27 @@ def re_line(text, pat):
lines = re_lines(text, pat).splitlines()
assert len(lines) == 1
return lines[0]
+
+
+class SuperModuleCleaner(ModuleCleaner):
+ """Remember the state of sys.modules and restore it later."""
+
+ def clean_local_file_imports(self):
+ """Clean up the results of calls to `import_local_file`.
+
+ Use this if you need to `import_local_file` the same file twice in
+ one test.
+
+ """
+ # So that we can re-import files, clean them out first.
+ self.cleanup_modules()
+
+ # Also have to clean out the .pyc file, since the timestamp
+ # resolution is only one second, a changed file might not be
+ # picked up.
+ for pyc in itertools.chain(glob.glob('*.pyc'), glob.glob('*$py.class')):
+ os.remove(pyc)
+ if os.path.exists("__pycache__"):
+ shutil.rmtree("__pycache__")
+
+ invalidate_import_caches()