summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNed Batchelder <ned@nedbatchelder.com>2021-10-05 19:43:00 -0400
committerNed Batchelder <ned@nedbatchelder.com>2021-10-05 19:43:00 -0400
commitccf7b3083a068ecea40d8ad104dabbef903856bb (patch)
treeef7653f1eff20c4d304c15ac594c529e5a83b353
parent62116801c3ae2f7bfc6302836e46bdfac681c1a5 (diff)
downloadpython-coveragepy-git-nedbat/fix-tomli-tests-1228.tar.gz
fix: pretend we didn't import third-party packages we usenedbat/fix-tomli-tests-1228
-rw-r--r--coverage/misc.py19
-rw-r--r--coverage/tomlconfig.py7
2 files changed, 21 insertions, 5 deletions
diff --git a/coverage/misc.py b/coverage/misc.py
index 11dad23e..d11b5ace 100644
--- a/coverage/misc.py
+++ b/coverage/misc.py
@@ -5,6 +5,7 @@
import errno
import hashlib
+import importlib
import importlib.util
import inspect
import locale
@@ -43,6 +44,24 @@ def isolate_module(mod):
os = isolate_module(os)
+def import_extra(modname):
+ """Import a third-party module we need, but might not be installed.
+
+ This also cleans out the module after the import, so that coverage won't
+ appear to have imported it. This lets the extra package use coverage for
+ their own tests.
+ """
+ try:
+ mod = importlib.import_module(modname)
+ except ImportError:
+ mod = None
+ else:
+ for name in list(sys.modules.keys()):
+ if name.startswith(modname):
+ del sys.modules[name]
+ return mod
+
+
def dummy_decorator_with_args(*args_unused, **kwargs_unused):
"""Dummy no-op implementation of a decorator with arguments."""
def _decorator(func):
diff --git a/coverage/tomlconfig.py b/coverage/tomlconfig.py
index 203192c9..91bd61bd 100644
--- a/coverage/tomlconfig.py
+++ b/coverage/tomlconfig.py
@@ -8,13 +8,10 @@ import os
import re
from coverage.exceptions import CoverageException
-from coverage.misc import substitute_variables
+from coverage.misc import import_extra, substitute_variables
# TOML support is an install-time extra option.
-try:
- import tomli
-except ImportError: # pragma: not covered
- tomli = None
+tomli = import_extra("tomli")
class TomlDecodeError(Exception):