gpt4 book ai didi

python - pytest 不会运行子目录中的测试文件

转载 作者:行者123 更新时间:2023-12-05 04:59:17 30 4
gpt4 key购买 nike

我是 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 文件,但结果还是一样。另外,我已经在两台不同的计算机上尝试过,但没有任何改变。如果问题无法解决,我可以忽略它并继续我的解决方案吗?

最佳答案

使用 pytest 配置项目的“最佳实践”方法是使用 a config file .最简单的解决方案是 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

您的示例是关于从命令行运行特定测试。 finding the rootdir from args 的完整规则集有点做作。

你应该注意到 pytest 目前支持 two possible layouts为您的测试和模块。目前是strongly suggested by pytest documentation to use a src layout .回答使用 __init__.py 的重要性在一定程度上取决于前者,但是选择配置文件和布局仍然优先于您选择如何使用 __init__.py定义您的包。

关于python - pytest 不会运行子目录中的测试文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63572310/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com