所以我有一个巨大的对象,它包含在固定装置内启动的信息。我需要使用这些信息来运行我的测试,棘手的部分从这里开始。 如果我在测试用例中使用的对象中没有属性,我必须跳过它。
带有对象生成的 fixture 在测试运行之前被启动一次(通常)。 在测试之前,我需要一个易于使用的装饰器/fixture/任何东西,以检查对象是否具有对象内部所需的内容。
例子:
@pytest.fixture(scope="package")
def info(request):
print("Setting up...")
obj = Creator()
obj.setup()
obj.prepare() if hasattr(obj, "prepare") else ""
def teardown():
obj.teardown() if hasattr(obj, "teardown") else ""
request.addfinalizer(teardown)
return obj.call()
...
@has_attr("some_attr")
def test_sometest(info):
assert info.some_attr == 42
最佳答案
我可以想到多种可能性来实现这一目标,但没有一种看起来像您的示例那样干净。
最简单的方法就是在测试中跳过:
def test_something(info):
if not hasattr(info, "some_attr"):
pytest.skip("Missing attribute 'some_attr'")
assert info.some_attr == 42
可能不是你想要的,但如果你没有太多测试,它可能有意义。 如果您只想检查几个不同的属性,则可以为这些属性制作特定的 fixture :
@pytest.fixture
def info_with_some_attr(info):
if not hasattr(info, "some_attr"):
pytest.skip("Missing attribute 'some_attr'")
yield info
def test_something(info_with_some_attr):
assert info_with_some_attr.some_attr == 42
如果你有更多的属性,你可以用属性名来参数化 fixture:
@pytest.fixture
def info_with_attr(request, info):
if hasattr(request, "param"):
for attr in request.param:
if not hasattr(info, attr):
pytest.skip(f"Missing attribute '{attr}'")
yield info
@pytest.mark.parametrize("info_with_attr", [("some_attr", "another_attr")], indirect=True)
def test_something(info_with_attr):
assert info_with_attr.some_attr == 42
这完全符合您的要求,尽管它看起来有点笨拙。
编辑:更新最后一个示例以使用元组而不是单个字符串,如评论中所述。
关于python-3.x - 使用固定装置跳过 pytest 中的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64175143/