diff --git a/python/tests/BUILD.bazel b/python/tests/BUILD.bazel index b04da8956..56f493132 100644 --- a/python/tests/BUILD.bazel +++ b/python/tests/BUILD.bazel @@ -4,11 +4,16 @@ load("@rules_python//python:py_test.bzl", "py_test") py_test( name = "test_opencc", size = "small", - srcs = ["test_opencc.py"], + srcs = [ + "pytest_runner.py", + "test_opencc.py", + ], + args = ["test_opencc.py"], data = [ "//test/testcases", ], imports = [".."], + main = "pytest_runner.py", deps = [ "//python/opencc", requirement("pytest"), @@ -20,8 +25,13 @@ py_test( py_test( name = "test_cli", size = "small", - srcs = ["test_cli.py"], + srcs = [ + "pytest_runner.py", + "test_cli.py", + ], + args = ["test_cli.py"], imports = [".."], + main = "pytest_runner.py", deps = [ "//python/opencc", requirement("pytest"), diff --git a/python/tests/pytest_runner.py b/python/tests/pytest_runner.py new file mode 100644 index 000000000..3b4aef1f1 --- /dev/null +++ b/python/tests/pytest_runner.py @@ -0,0 +1,26 @@ +import os +import sys + +import pytest + + +def _test_path(test_dir: str, arg: str) -> str: + if os.path.isabs(arg): + return arg + return os.path.join(test_dir, arg) + + +def main() -> int: + test_dir = os.path.dirname(os.path.abspath(__file__)) + test_paths = [_test_path(test_dir, arg) for arg in sys.argv[1:]] + if not test_paths: + test_paths = [test_dir] + + return pytest.main([ + *test_paths, + f'--rootdir={test_dir}', + ]) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/python/tests/test_cli.py b/python/tests/test_cli.py index 9944d21d9..a6135fd15 100644 --- a/python/tests/test_cli.py +++ b/python/tests/test_cli.py @@ -218,7 +218,3 @@ def test_cli_custom_config_path_without_json_extension(tmp_path, monkeypatch): ) assert output_path.read_text(encoding='utf-8') == '滑鼠' - - -if __name__ == "__main__": - sys.exit(pytest.main([os.path.abspath(__file__)])) diff --git a/python/tests/test_opencc.py b/python/tests/test_opencc.py index 6507fdab2..5f5c54b06 100644 --- a/python/tests/test_opencc.py +++ b/python/tests/test_opencc.py @@ -1,7 +1,5 @@ import json import os -import pytest -import sys import zipfile _this_dir = os.path.dirname(os.path.abspath(__file__)) @@ -131,7 +129,3 @@ def test_custom_config_path_without_json_extension_is_preserved(): assert opencc._normalize_config_name('./s2t') == './s2t' assert opencc._normalize_config_name('configs/s2t') == 'configs/s2t' assert opencc._normalize_config_name(r'configs\s2t') == r'configs\s2t' - - -if __name__ == "__main__": - sys.exit(pytest.main([os.path.abspath(__file__)]))