如何让Pytest识别单元测试文件以通过GitHub CI/CD测试
pytest无法找到单元测试文件,收集到0个测试用例(exit code 5)
我在管理一门大学课程的GitHub仓库,正在配置CI/CD流程,目前大部分检查都通过了,但卡在pytest测试环节。执行pytest --verbose .时输出如下:
Run pytest --verbose . ============================= test session starts ============================== platform linux -- Python 3.10.13, pytest-8.0.0, pluggy-1.4.0 -- /opt/hostedtoolcache/Python/3.10.13/x64/bin/python cachedir: .pytest_cache hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase(PosixPath('/home/runner/work/OOP-ajsaylor/OOP-ajsaylor/.hypothesis/examples')) rootdir: /home/runner/work/OOP-ajsaylor/OOP-ajsaylor plugins: hypothesis-6.98.4 collecting ... collected 0 items ============================ no tests ran in 1.01s ============================= Error: Process completed with exit code 5.
我已经编写了对应程序的单元测试文件,但pytest似乎无法识别它们,希望能找到让pytest识别测试文件的方法。
解决方案
以下是排查和解决pytest无法找到测试文件的实用步骤:
检查测试文件命名规则:pytest默认只会识别以
test_开头或以_test.py结尾的文件,比如test_calculator.py或calculator_test.py。如果你的测试文件名不符合这个规则(比如my_tests.py),pytest会直接忽略它,修改文件名即可。确认测试文件位置与路径:
- 如果测试文件放在单独的
tests/目录下,执行命令时可以直接指定该目录:pytest tests/ --verbose,确保pytest扫描到正确的路径。 - 检查仓库中的
.gitignore或.pytestignore文件,确认测试文件或其所在目录没有被加入忽略列表。
- 如果测试文件放在单独的
检查测试用例的命名:即使文件名正确,文件内的测试函数/类也需要符合规则:
- 测试函数必须以
test_开头,比如def test_add_function():。 - 测试类必须以
Test开头(且不能包含__init__方法),类中的测试方法同样要以test_开头,示例:class TestCalculator: def test_subtract(self): # 测试逻辑 pass
- 测试函数必须以
手动指定测试文件路径排查:如果以上步骤都没问题,尝试直接指定测试文件的完整路径执行,比如
pytest ./tests/test_my_module.py --verbose。如果这样能收集到测试用例,说明是路径扫描的问题,可能需要调整pytest的执行路径或配置。检查pytest配置文件:查看仓库中是否存在
pytest.ini、setup.cfg或tox.ini文件,这些文件可能修改了pytest的测试文件匹配规则。比如如果配置中有python_files = *spec.py,那么只有以.spec.py结尾的文件会被识别,需要修改配置或调整测试文件名适配规则。
内容的提问来源于stack exchange,提问作者Austin
相关产品推荐
相关产品推荐

