gpt4 book ai didi

python - pytest:如何制作专用测试目录

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:43 25 4
gpt4 key购买 nike

我想要以下项目结构:

|--folder/
| |--tests/
| |--project/

让我们写一个简单的例子:

|--test_pytest/
| |--tests/
| | |--test_sum.py
| |--t_pytest/
| | |--sum.py
| | |--__init__.py

求和.py:

def my_sum(a, b):
return a + b

测试总和.py:

from t_pytest.sum import my_sum
def test_my_sum():
assert my_sum(2, 2) == 5, "math still works"

让我们运行它:

test_pytest$ py.test ./
========== test session starts ===========
platform linux -- Python 3.4.3, pytest-2.9.2, py-1.4.31, pluggy-0.3.1
rootdir: /home/step/test_pytest, inifile:
collected 0 items / 1 errors

================= ERRORS =================
___ ERROR collecting tests/test_sum.py ___
tests/test_sum.py:1: in <module>
from t_pytest import my_sum
E ImportError: No module named 't_pytest'
======== 1 error in 0.01 seconds =========

它看不到 t_pytest 模块。它被制作成 httpie:

https://github.com/jkbrzt/httpie/

https://github.com/jkbrzt/httpie/blob/master/tests/test_errors.py

为什么?我该如何纠正它?

最佳答案

另一种方法是通过在文件夹测试中添加 __init__.py 文件,使测试也成为一个模块。最流行的 python 库请求之一 https://github.com/kennethreitz/requests在他们的单元测试文件夹测试中就是这样做的。您不必将 PYTHONPATH 导出到您的项目即可执行测试。

限制是您必须在示例项目的“test_pytest”目录中运行 py.test 命令。

还有一件事,您的示例代码中的导入行是错误的。应该是

from t_pytest.sum import my_sum

关于python - pytest:如何制作专用测试目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37816820/

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