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

时间:2016-06-14 15:54:36

标签: python testing pytest project-structure

我想要以下项目结构:

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

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

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

sum.py:

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

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

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

4 个答案:

答案 0 :(得分:2)

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

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

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

from t_pytest.sum import my_sum

答案 1 :(得分:0)

谢谢你,jonrsharpe。 Py.test没有魔法,我需要让我的包可以自己导入。有一种可能的解决方案:

   $ export PYTHONPATH="${PYTHONPATH}: [Path to folder with my module]"   

(PYTHONPATH是sys.path的路径源之一)
如果我需要永久更改,我需要将此字符串添加到~/.bashrc

答案 2 :(得分:0)

尝试一下:

{
    "protocol": "ftp",
    "host": "myhost.com",
    "port": 21,
    "user": "username**",
    "pass": "password**",
    "promptForPass": false,
    "remote": "/",
    "local": "",
    "secure": true,
    "secureOptions": {"rejectUnauthorized": false, "requestCert": true, "agent": false},
    "connTimeout": 10000,
    "pasvTimeout": 10000,
    "keepalive": 10000,
    "watch": [],
    "watchTimeout": 500
}

它与@stepuncius points at以及this answera gist中引用的内容相同。我只是想将其作为一个完整的答案。对于小型项目而言,这是一种简单的解决方案,无需干预数据包模块结构或# in bash/zsh shell test_pytest$ PYTHONPATH=. pytest # in fish shell test_pytest$ env PYTHONPATH=. pytest 等。

答案 3 :(得分:-1)

使用pytest:

{{for}}

这可能有助于解决您的问题 with unittest:

假设我们有名为if __name__ == '__main__': import pytest pytest.main(['-x', 'tests', '--capture', 'sys']) # Note: tests is the directory name

的入门脚本

run_tests.py中的代码:

run_tests.py

你只需将import unittest if __name__ == '__main__': # use the default shared TestLoader instance test_loader = unittest.defaultTestLoader # use the basic test runner that outputs to sys.stderr test_runner = unittest.TextTestRunner() # automatically discover all tests in the current dir of the form test*.py # NOTE: only works for python 2.7 and later test_suite = test_loader.discover('./tests') # run the test suite test_runner.run(test_suite) 替换为你的顶层目标dir(绝对路径)包含所有测试脚本

您只需像

一样运行此文件

./tests

您将能够看到运行所有测试脚本。