[英]pytest will not run the test files in subdirectories
我是 pytest 的新手,并试图运行一个简单的测试来检查 pytest 是否有效。 我使用的是 Windows 10、python 3.8.5 和 pytest 6.0.1。
这是我的项目目录:
projects/
tests/
__init__.py
test_sample.py
这是我放在 test_sample.py 中的内容:
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
如果我执行以下操作:
> pytest
the test run fine (1 failed in 0.004s)
> pytest tests/test_sample.py
the test run fine (1 failed in 0.006s)
但是,如果我这样做:
> pytest test_sample.py
它会返回这样的消息:
no test ran in 0.000s
ERROR: file not found: test_sample.py
我尝试删除__init__.py
文件,但结果还是一样。 另外,我在 2 台不同的计算机上尝试过这个,但没有任何改变。 如果问题无法解决,我可以忽略它并继续我的解决方案吗?
使用 pytest 配置项目的“最佳实践”方法是使用配置文件。 最简单的解决方案是一个pytest.ini
,它看起来像这样:
# pytest.ini
[pytest]
testpaths = tests
这将配置testpaths
相对于你的rootdir
(pytest会告诉你这两个路径是什么,只要你运行它)。 这回答了您在问题中提出的具体问题。
C:\YourProject <<-- Run pytest on this path and it will be considered your rootdir.
│
│ pytest.ini
│ your_module.py
│
├───tests <<-- This is the directory you configured as testpaths in pytest.ini
│ __init__.py
│ test_sample.py
您的示例是关于从命令行运行特定测试。 从args
查找rootdir
的完整规则集有些人为。
您应该注意到 pytest 目前支持您的测试和模块的两种可能的布局。 pytest 文档目前强烈建议使用src
layout 。 回答使用__init__.py
的重要性在一定程度上取决于前者,但是选择配置文件和布局仍然优先于您选择如何使用__init__.py
来定义您的包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.