Skip to content

Commit 7d3dbb4

Browse files
committed
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. Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
1 parent 98f8a7e commit 7d3dbb4

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

python-stdlib/unittest-discover/unittest/__main__.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@ def _run_test_module(runner: TestRunner, module_name: str, *extra_paths: list[st
1414
module_snapshot = {k: v for k, v in sys.modules.items()}
1515
path_snapshot = sys.path[:]
1616
try:
17-
for path in reversed(extra_paths):
17+
for path in extra_paths:
1818
if path:
1919
sys.path.insert(0, path)
2020

21-
module = __import__(module_name)
21+
module = __import__(module_name, None, None, module_name)
2222
suite = TestSuite(module_name)
2323
suite._load_module(module)
2424
return runner.run(suite)
@@ -36,16 +36,18 @@ def _run_all_in_dir(runner: TestRunner, path: str, pattern: str, top: str):
3636
for fname, ftype, *_ in os.ilistdir(path):
3737
if fname in ("..", "."):
3838
continue
39+
fpath = "/".join((path, fname))
3940
if ftype == _DIR_TYPE:
4041
result += _run_all_in_dir(
4142
runner=runner,
42-
path="/".join((path, fname)),
43+
path=fpath,
4344
pattern=pattern,
4445
top=top,
4546
)
4647
if fnmatch(fname, pattern):
47-
module_name = fname.rsplit(".", 1)[0]
48-
result += _run_test_module(runner, module_name, path, top)
48+
module_path = fpath.rsplit(".", 1)[0] # remove ext
49+
module_path = module_path.replace("/", ".").strip(".")
50+
result += _run_test_module(runner, module_path, top)
4951
return result
5052

5153

0 commit comments

Comments
 (0)