From c09c4136bbaa5e83a911a32f0de8f847691ea17c Mon Sep 17 00:00:00 2001 From: Steven Arcangeli <506791+stevearc@users.noreply.github.com> Date: Wed, 8 Jun 2022 12:58:05 -0700 Subject: [PATCH] fix(unittest): correct args for tests/classes/files (#2) * fix: unittest adapter can run specific tests/groups/files * fix: running tests at the directory level * refactor: tidy id_to_unittest_args and remove print --- neotest_python/unittest.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/neotest_python/unittest.py b/neotest_python/unittest.py index 434fb55..f884e82 100644 --- a/neotest_python/unittest.py +++ b/neotest_python/unittest.py @@ -1,4 +1,6 @@ import inspect +import os +import sys import traceback import unittest from pathlib import Path @@ -24,6 +26,22 @@ class UnittestNeotestAdapter(NeotestAdapter): def case_id(self, case: "TestCase | TestSuite") -> str: return "::".join(self.case_id_elems(case)) + def id_to_unittest_args(self, case_id: str) -> List[str]: + """Converts a neotest ID into test specifier for unittest""" + path, *child_ids = case_id.split("::") + if not child_ids: + if os.path.isfile(path): + # Test files can be passed directly to unittest + return [path] + # Directories need to be run via the 'discover' argument + return ["discover", "-s", path] + + # Otherwise, convert the ID into a dotted path, relative to current dir + relative_file = os.path.relpath(path, os.getcwd()) + relative_stem = os.path.splitext(relative_file)[0] + relative_dotted = relative_stem.replace(os.sep, ".") + return [".".join([relative_dotted, *child_ids])] + def run(self, args: List[str]) -> Dict: results = {} @@ -71,9 +89,13 @@ class UnittestNeotestAdapter(NeotestAdapter): } return result + # Make sure we can import relative to current path + sys.path.insert(0, os.getcwd()) + # We only get a single case ID as the argument + argv = sys.argv[0:1] + self.id_to_unittest_args(args[0]) unittest.main( module=None, - argv=args, + argv=argv, testRunner=NeotestUnittestRunner(resultclass=NeotestTextTestResult), exit=False, )