【问题标题】:PyTest: skip entire module/file (python 2 and 3)PyTest:跳过整个模块/文件(python 2和3)
【发布时间】:2017-02-28 14:51:25
【问题描述】:

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

try:
  import networkx
except:
  import pytest
  pytest.skip()

这适用于 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

【问题讨论】:

    标签: python pytest


    【解决方案1】:

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

    if pytest.__version__ < "3.0.0":
      pytest.skip()
    else:
      pytestmark = pytest.mark.skip
    

    【讨论】:

    • 出于好奇:为什么您的测试套件也需要与 pytest 2.8.1 一起使用?
    • 我希望我的代码尽可能向后兼容,这只是我在另一台机器上安装的版本。
    【解决方案2】:

    您可以使用pytest.skipallow_module_level=True 来跳过模块的剩余测试:

    pytest.skip(allow_module_level=True)
    

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 这也是一个优雅的解决方案。我不知道如何指定,例如from networkx.algorithms import bipartiteimportorskip,不过。
      • bipartite = pytest.importorskip("networkx.algorithms").bipartite(或者在importorskip之后单独导入)
      • 该链接在其下方提到了skipif 指令。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2012-09-11
      • 2012-12-31
      • 2018-01-07
      • 2020-12-03
      • 1970-01-01
      • 2015-10-04
      相关资源
      最近更新 更多