@@ -143,6 +143,35 @@ def formatResult(
143143 send_run_data (result , test_run_pipe )
144144
145145
146+ def filter_tests (suite : unittest .TestSuite , test_ids : List [str ]) -> unittest .TestSuite :
147+ """Filter the tests in the suite to only run the ones with the given ids."""
148+ filtered_suite = unittest .TestSuite ()
149+ for test in suite :
150+ if isinstance (test , unittest .TestCase ):
151+ if test .id () in test_ids :
152+ filtered_suite .addTest (test )
153+ else :
154+ filtered_suite .addTest (filter_tests (test , test_ids ))
155+ return filtered_suite
156+
157+
158+ def get_all_test_ids (suite : unittest .TestSuite ) -> List [str ]:
159+ """Return a list of all test ids in the suite."""
160+ test_ids = []
161+ for test in suite :
162+ if isinstance (test , unittest .TestCase ):
163+ test_ids .append (test .id ())
164+ else :
165+ test_ids .extend (get_all_test_ids (test ))
166+ return test_ids
167+
168+
169+ def find_missing_tests (test_ids : List [str ], suite : unittest .TestSuite ) -> List [str ]:
170+ """Return a list of test ids that are not in the suite."""
171+ all_test_ids = get_all_test_ids (suite )
172+ return [test_id for test_id in test_ids if test_id not in all_test_ids ]
173+
174+
146175# Args: start_path path to a directory or a file, list of ids that may be empty.
147176# Edge cases:
148177# - if tests got deleted since the VS Code side last ran discovery and the current test run,
@@ -169,16 +198,6 @@ def run_tests(
169198 start_dir = os .path .dirname (cwd )
170199 pattern = os .path .basename (cwd )
171200
172- # Discover tests at path with the file name as a pattern (if any).
173- loader = unittest .TestLoader ()
174-
175- args = { # noqa: F841
176- "start_dir" : start_dir ,
177- "pattern" : pattern ,
178- "top_level_dir" : top_level_dir ,
179- }
180- suite = loader .discover (start_dir , pattern , top_level_dir ) # noqa: F841
181-
182201 if failfast is None :
183202 failfast = False
184203 if locals is None :
@@ -191,9 +210,20 @@ def run_tests(
191210 failfast = failfast ,
192211 verbosity = verbosity ,
193212 )
194- # lets try to tailer our own suite so we can figure out running only the ones we want
213+
214+ # Discover tests at path with the file name as a pattern (if any).
195215 loader = unittest .TestLoader ()
196- tailor : unittest .TestSuite = loader .loadTestsFromNames (test_ids )
216+ suite = loader .discover (start_dir , pattern , top_level_dir )
217+
218+ # lets try to tailer our own suite so we can figure out running only the ones we want
219+ tailor : unittest .TestSuite = filter_tests (suite , test_ids )
220+
221+ # If any tests are missing, add them to the payload.
222+ not_found = find_missing_tests (test_ids , tailor )
223+ if not_found :
224+ missing_suite = loader .loadTestsFromNames (not_found )
225+ tailor .addTests (missing_suite )
226+
197227 result : UnittestTestResult = runner .run (tailor ) # type: ignore
198228
199229 payload ["result" ] = result .formatted
0 commit comments