PyTest:跳过整个模块/文件(python 2和3)

mat*_*ten 5 python pytest

如果导入不起作用,我想跳过整个测试:

try:
  import networkx
except:
  import pytest
  pytest.skip()
Run Code Online (Sandbox Code Playgroud)

这对python-2.7和python-3.5都很好,两者都使用pytest-2.8.1.当我尝试使用pytest-3.0.5在python-3.6中运行代码时,我收到以下错误:

不允许在测试之外使用pytest.skip.如果您正在尝试修饰测试函数,请改用@ pytest.mark.skip或@ pytest.mark.skipif装饰器.

如何编写适用于所有上述环境的代码/测试?我已经尝试重写像这样的except块,但它只适用于最新的配置:

try:
  pytest.skip()
except:
  pytestmark = pytest.mark.skip
Run Code Online (Sandbox Code Playgroud)

Con*_*tor 21

您可以使用pytest.skipwithallow_module_level=True跳过模块的其余测试:

pytest.skip(allow_module_level=True)
Run Code Online (Sandbox Code Playgroud)

请参阅示例: https: //docs.pytest.org/en/latest/how-to/skipping.html#skipping-test-functions


mat*_*ten 7

我自己想通了。skip 块需要检查 pytest 的版本:

if pytest.__version__ < "3.0.0":
  pytest.skip()
else:
  pytestmark = pytest.mark.skip
Run Code Online (Sandbox Code Playgroud)

  • 我希望我的代码尽可能向后兼容,这只是我在另一台机器上安装的版本。 (3认同)

The*_*ler 7

更直接的解决方案是使用pytest.importorskip.