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
commit478d601975c5f9f66fc2a8a18df447a619d45d50 (patch)
tree5fa7e91e1ec5c6fa4b11822cfc01ff34af305e0c /tests/helpers.py
parent9d726f22bdc1f8be96724017721a673ca7d03247 (diff)
downloadpython-coveragepy-478d601975c5f9f66fc2a8a18df447a619d45d50.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 cbb6e01..f10169a 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()