diff options
-rw-r--r-- | coverage/misc.py | 19 | ||||
-rw-r--r-- | coverage/tomlconfig.py | 7 |
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): |