【问题标题】:Can I use a pytest fixture in the condition of my skipif logic?我可以在我的 skipif 逻辑条件下使用 pytest 夹具吗?
【发布时间】:2013-10-10 17:36:39
【问题描述】:

我正在尝试在类 skipif 装饰器中使用 pytest 夹具(范围 = 模块),但我收到一个错误,提示未定义夹具。这可能吗?

conftest.py 有一个名为“target”的模块范围的夹具,它返回一个 CurrentTarget 对象。 CurrentTarget 对象有一个函数 isCommandSupported。 test_mytest.py 有一个包含十几个测试函数的类 Test_MyTestClass。 我想根据fixture target.isCommandSupported 跳过Test_MyTestClass 中的所有测试,所以我用skipif 装饰Test_MyTestClass,如下所示:

@pytest.mark.skipif(not target.isCommandSupprted('commandA), reason=command not supported')
class Test_MyTestClass:
...

我收到此错误:NameError: name 'target' is not defined

如果我尝试:

@pytest.mark.skipif(not pytest.config.getvalue('tgt').isCommandSupprted('commandA), reason=command not supported')
class Test_MyTestClass:
...

我收到此错误:AttributeError: 'function' object has no attribute 'isCommandSupprted'

【问题讨论】:

  • 有没有更好的地方问这个问题?
  • 我看到 Holger Krekel 在这里回答,但他通常会指向 freenode 聊天以寻求支持问题。 pytest.org/latest/contact.html
  • 我偶然发现了同样的issue。您找到问题的解决方案了吗?

标签: pytest fixture


【解决方案1】:

您可以像这样从 conftest 导入target

from conftest import target

然后,您可以在 pytest.mark.skipif 中使用它,就像您在示例中所打算的那样。

@pytest.mark.skipif(not target.isCommandSupported('commandA'), reason='command not supported')
def Test_MyTestClass:

如果您需要在多个测试中重复相同的 pytest.mark.skipif 逻辑并希望避免复制粘贴,一个简单的装饰器会有所帮助:

check_unsupported = pytest.mark.skipif(not target.isCommandSupported('commandA'),
                                       reason='command not supported')

@check_unsupported
def test_one():
    pass

@check_unsupported
def test_two():
    pass

【讨论】:

    【解决方案2】:

    在第一种情况下出现错误的原因是 pytest 注入了固定装置,因此它们通过函数参数在您的测试函数中可用。它们永远不会被导入更高的范围。

    您得到 AttributeError 的原因是,fixture 是函数,并且在第一次(或每次)使用时都会被评估。所以,当你通过pytest.config 得到它时,它仍然是一个函数。这与other answer 失败的原因相同——如果你导入它,你导入的是fixture 函数,而不是结果。

    没有直接的方法来做你想做的事,但你可以用一个额外的夹具来解决它:

    @pytest.fixture(scope='module')
    def check_unsupported(target):
      if not target.isCommandSupported('commandA'):
        pytest.skip('command not supported')
    
    @pytest.mark.usefixtures('check_unsupported')
    def test_one():
      pass
    
    def test_two(check_unsupported):
      pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-21
      • 1970-01-01
      • 2020-04-15
      • 2022-01-03
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 2013-05-28
      相关资源
      最近更新 更多