diff --git a/Lib/test/libregrtest/findtests.py b/Lib/test/libregrtest/findtests.py index 142a4d068bc47e5..f8662293c1aaf59 100644 --- a/Lib/test/libregrtest/findtests.py +++ b/Lib/test/libregrtest/findtests.py @@ -95,12 +95,17 @@ def list_cases(tests: TestTuple, *, match_labels: TestFilter | None = None, test_dir: StrPath | None = None) -> None: support.verbose = False - cases_by_module, skipped = collect_cases(tests, match_tests=match_tests, - match_labels=match_labels, - test_dir=test_dir) - for cases in cases_by_module.values(): - for case_id in cases: - print(case_id) + set_match_tests(match_tests, match_labels) + + skipped = [] + for test_name in tests: + module_name = abs_module_name(test_name, test_dir) + try: + suite = unittest.defaultTestLoader.loadTestsFromName(module_name) + _list_cases(suite) + except unittest.SkipTest: + skipped.append(test_name) + if skipped: sys.stdout.flush() stderr = sys.stderr diff --git a/Lib/test/test_regrtest.py b/Lib/test/test_regrtest.py index cd2cd8a21e8ea7f..517ae769c44aece 100644 --- a/Lib/test/test_regrtest.py +++ b/Lib/test/test_regrtest.py @@ -1526,6 +1526,21 @@ def test_method2(self): testname) self.assertEqual(output.splitlines(), all_methods) + def test_list_cases_import_error(self): + # A test module which fails to import has no test case to list + code = textwrap.dedent(""" + import unittest + + class Tests(unittest.TestCase): + def test_method1(self): + pass + """) + testname = self.create_test(code=code) + broken = self.create_test(code='import nonexistent_module') + output = self.run_tests('--list-cases', broken, testname) + self.assertEqual(output.splitlines(), + ['%s.Tests.test_method1' % testname]) + @support.cpython_only def test_crashed(self): # Any code which causes a crash diff --git a/Misc/NEWS.d/next/Tests/2026-12-02-19-17-24.gh-issue-163032.HtW1VF.rst b/Misc/NEWS.d/next/Tests/2026-12-02-19-17-24.gh-issue-163032.HtW1VF.rst new file mode 100644 index 000000000000000..fafae345ad402c5 --- /dev/null +++ b/Misc/NEWS.d/next/Tests/2026-12-02-19-17-24.gh-issue-163032.HtW1VF.rst @@ -0,0 +1,2 @@ +Fix ``python -m test --list-cases`` listing the name of a test module that +fails to import.