Skip to content

Commit 2644da4

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 2644da4

File tree

3 files changed

+28
-6
lines changed

3 files changed

+28
-6
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# This is intended to be imported as
2+
imported = True
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import sys
2+
import unittest
3+
4+
5+
class TestModuleImport(unittest.TestCase):
6+
def test_ModuleImportPath(self):
7+
try:
8+
from sub.sub import imported
9+
assert imported
10+
except ImportError:
11+
print("This test is intended to be run with unittest discover"
12+
"from the unittest-discover/tests dir. sys.path:", sys.path)
13+
raise

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

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,24 @@
66
from fnmatch import fnmatch
77
from micropython import const
88

9-
from unittest import TestRunner, TestResult, TestSuite
9+
try:
10+
from unittest import TestRunner, TestResult, TestSuite
11+
except ImportError:
12+
print("Error: This must be used from an installed copy of unittest-discover which will"
13+
" also install base unittest module.")
14+
raise
1015

1116

1217
# Run a single test in a clean environment.
1318
def _run_test_module(runner: TestRunner, module_name: str, *extra_paths: list[str]):
1419
module_snapshot = {k: v for k, v in sys.modules.items()}
1520
path_snapshot = sys.path[:]
1621
try:
17-
for path in reversed(extra_paths):
22+
for path in extra_paths:
1823
if path:
1924
sys.path.insert(0, path)
2025

21-
module = __import__(module_name)
26+
module = __import__(module_name, None, None, module_name)
2227
suite = TestSuite(module_name)
2328
suite._load_module(module)
2429
return runner.run(suite)
@@ -36,16 +41,18 @@ def _run_all_in_dir(runner: TestRunner, path: str, pattern: str, top: str):
3641
for fname, ftype, *_ in os.ilistdir(path):
3742
if fname in ("..", "."):
3843
continue
44+
fpath = "/".join((path, fname))
3945
if ftype == _DIR_TYPE:
4046
result += _run_all_in_dir(
4147
runner=runner,
42-
path="/".join((path, fname)),
48+
path=fpath,
4349
pattern=pattern,
4450
top=top,
4551
)
4652
if fnmatch(fname, pattern):
47-
module_name = fname.rsplit(".", 1)[0]
48-
result += _run_test_module(runner, module_name, path, top)
53+
module_path = fpath.rsplit(".", 1)[0] # remove ext
54+
module_path = module_path.replace("/", ".").strip(".")
55+
result += _run_test_module(runner, module_path, top)
4956
return result
5057

5158

0 commit comments

Comments
 (0)