pytest 与 tox

它很容易集成 pytest 带着tox测试。如果您遇到问题,请检查是否 listed as a known issue 和/或使用 support channels .

基本实例

假设布局如下:

tox.ini      # see below for content
setup.py     # a classic distutils/setuptools setup.py file

以及以下内容 tox.ini 内容:

[tox]
envlist = py35,py36

[testenv]
deps = pytest               # PYPI package providing pytest
commands = pytest {posargs} # substitute with tox' positional arguments

您现在可以调用 tox 在您的 tox.ini 就住在这里。 tox 将sdist打包您的项目,使用 python3.5python3.6 解释器,然后将在每个解释器中运行指定的测试命令。

扩展示例:在测试前更改目录并使用每个Virtualenv临时目录

假设布局如下:

tox.ini      # see below for content
setup.py     # a classic distutils/setuptools setup.py file
tests        # the directory containing tests

以及以下内容 tox.ini 内容:

[tox]
envlist = py35,py36

[testenv]
changedir = tests
deps = pytest
# change pytest tempdir and add posargs from command line
commands = pytest --basetemp="{envtmpdir}" {posargs}

您可以调用 tox 在您的 tox.ini 就住在这里。与前面的示例不同, pytest 命令将在当前工作目录设置为的情况下执行 tests 并且测试运行将使用per-viralenv临时目录。

使用多个CPU进行测试运行

pytest 支持通过将测试分发到多个进程和主机 pytest-xdist 插件。以下是要进行的示例配置 tox 使用此功能:

[testenv]
deps = pytest-xdist
changedir = tests
# use three sub processes
commands = pytest --basetemp="{envtmpdir}"  \
                  --confcutdir=..         \
                  -n 3                    \
                  {posargs}

已知问题和限制

文件名太长 。在pytest运行中,您可能会遇到临时创建的文件的“文件名过长”。尽量不要使用“--basetemp”参数。

installed-versus-checkout version . pytest 收集文件系统上的测试模块,然后尝试将它们导入到 fully qualified name 。这意味着如果您的测试文件可以从某个地方导入,那么您的 pytest 调用可能最终从签出目录(而不是已安装的软件包)导入软件包。

在python 3.x环境中,此问题的特征可能是pytest测试收集错误消息,如下所示:

import file mismatch:
imported module 'myproj.foo.tests.test_foo' has this __file__ attribute:
  /home/myuser/repos/myproj/build/lib/myproj/foo/tests/test_foo.py
which is not the same as the test file we want to collect:
  /home/myuser/repos/myproj/myproj/foo/tests/test_foo.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules

有几种方法可以防止这种情况发生。

使用已安装的测试(已知测试包 setup.py ),一个安全而显式的选项是给出显式路径 {{envsitepackagesdir}}/mypkg 为了火爆。或者,也可以使用 changedir 以便签出的文件位于导入路径之外,然后传递 --pyargs mypkg 为了火爆。

对于不会安装的测试,针对已安装的软件包运行它们的最简单方法是避免 __init__.py 测试目录中的文件;pytest仍然会通过将它们的父目录添加到 sys.path 但是它们不会被复制到其他地方,也不会被Python的导入系统在pytest之外找到。