Skip to main content
 首页 » 编程设计

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

2024年10月17日8bonelee

我想要以下项目结构:

|--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