我试图在类skipif装饰器中使用pytest fixture(scope = module),但是我收到一个错误,说明夹具没有定义。这可能吗?
conftest.py有一个模块范围的夹具,名为' target'返回一个CurrentTarget对象。 CurrentTarget对象具有一个函数isCommandSupported。 test_mytest.py有一个Test_MyTestClass类,它包含十几个测试函数。 我想跳过Test_MyTestClass中的所有测试,基于夹具target.isCommandSupported,所以我用skipif装饰Test_MyTestClass:
@pytest.mark.skipif(not target.isCommandSupprted('commandA), reason=command not supported')
class Test_MyTestClass:
...
我收到此错误:NameError:name' target'未定义
如果我尝试:
@pytest.mark.skipif(not pytest.config.getvalue('tgt').isCommandSupprted('commandA), reason=command not supported')
class Test_MyTestClass:
...
我收到此错误:AttributeError:' function'对象没有属性' isCommandSupprted'
答案 0 :(得分:3)
在第一种情况下出现错误的原因是pytest注入了fixture,因此它们可以通过函数参数在测试函数中使用。它们永远不会进入更高的范围。
你得到属性错误的原因是灯具是功能,并在第一次(或每次)使用时进行评估。所以,当你通过pytest.config
时,它仍然是一个功能。这与other answer失败的原因相同 - 如果您导入它,则导入夹具功能,而不是结果。
没有直接的方法可以做你想做的事情,但你可以通过一个额外的工具来解决它:
@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
答案 1 :(得分: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