unittest-discover: Avoid adding test parent dir to sys.path.

When running tests from subfolders, import by "full dotted path" rather
than just module name, removing the need to add the test parent folder to
`sys.path`.

This matches CPython more closely, which places `abspath(top)` at the start
of `sys.path` but doesn't include the test file parent dir at all.

It fixes issues where projects may include a `test_xxx.py` file in their
distribution which would (prior to this change) be unintentionally found by
unittest-discover.

Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
pull/872/head
Andrew Leech 2024-06-06 15:12:45 +10:00 zatwierdzone przez Damien George
rodzic 98f8a7e771
commit 50ac49c42b
4 zmienionych plików z 28 dodań i 7 usunięć

Wyświetl plik

@ -1,4 +1,4 @@
metadata(version="0.1.2")
metadata(version="0.1.3")
require("argparse")
require("fnmatch")

Wyświetl plik

@ -0,0 +1 @@
imported = True

Wyświetl plik

@ -0,0 +1,13 @@
import sys
import unittest
class TestModuleImport(unittest.TestCase):
def test_ModuleImportPath(self):
try:
from sub.sub import imported
assert imported
except ImportError:
print("This test is intended to be run with unittest discover"
"from the unittest-discover/tests dir. sys.path:", sys.path)
raise

Wyświetl plik

@ -6,7 +6,12 @@ import sys
from fnmatch import fnmatch
from micropython import const
from unittest import TestRunner, TestResult, TestSuite
try:
from unittest import TestRunner, TestResult, TestSuite
except ImportError:
print("Error: This must be used from an installed copy of unittest-discover which will"
" also install base unittest module.")
raise
# Run a single test in a clean environment.
@ -14,11 +19,11 @@ def _run_test_module(runner: TestRunner, module_name: str, *extra_paths: list[st
module_snapshot = {k: v for k, v in sys.modules.items()}
path_snapshot = sys.path[:]
try:
for path in reversed(extra_paths):
for path in extra_paths:
if path:
sys.path.insert(0, path)
module = __import__(module_name)
module = __import__(module_name, None, None, module_name)
suite = TestSuite(module_name)
suite._load_module(module)
return runner.run(suite)
@ -36,16 +41,18 @@ def _run_all_in_dir(runner: TestRunner, path: str, pattern: str, top: str):
for fname, ftype, *_ in os.ilistdir(path):
if fname in ("..", "."):
continue
fpath = "/".join((path, fname))
if ftype == _DIR_TYPE:
result += _run_all_in_dir(
runner=runner,
path="/".join((path, fname)),
path=fpath,
pattern=pattern,
top=top,
)
if fnmatch(fname, pattern):
module_name = fname.rsplit(".", 1)[0]
result += _run_test_module(runner, module_name, path, top)
module_path = fpath.rsplit(".", 1)[0] # remove ext
module_path = module_path.replace("/", ".").strip(".")
result += _run_test_module(runner, module_path, top)
return result