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

ste*_*ius 4 python testing project-structure pytest

我想要以下项目结构:

|--folder/
|  |--tests/
|  |--project/
Run Code Online (Sandbox Code Playgroud)

我们写一个简单的例子:

|--test_pytest/
|  |--tests/
|  |  |--test_sum.py
|  |--t_pytest/
|  |  |--sum.py
|  |  |--__init__.py
Run Code Online (Sandbox Code Playgroud)

总和.py:

def my_sum(a, b):
    return a + b
Run Code Online (Sandbox Code Playgroud)

test_sum.py:

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

让我们运行它:

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 =========
Run Code Online (Sandbox Code Playgroud)

它看不到 t_pytest 模块。它的制作方式类似于 httpie:

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

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

为什么?我该如何纠正?

Li *_*eng 5

另一种方法是通过在文件夹测试中添加 __init__.py 文件来使测试成为一个模块。最受欢迎的 python lib 请求之一https://github.com/kennethreitz/requests在他们的单元测试文件夹测试中以这种方式进行。您不必将 PYTHONPATH 导出到您的项目来执行测试。

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

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

from t_pytest.sum import my_sum
Run Code Online (Sandbox Code Playgroud)