假设我在 conftest.py 文件中建立了一个 pytest fixture,如下所示:
def live_fixture():
# network access here...
pass
我在许多测试函数中使用相同的 fixture ,假设 test_spam.py 有一些测试函数:
@pytest.mark.live
def test_one(live_fixture):
assert 1
def test_one():
assert 2
@pytest.mark.live
def test_three(live_fixture):
assert 3
我在第一个和第三个测试函数上使用了 @pytest.mark.live
装饰,因为这两个测试都依赖于 fixture live_fixture
,它在网络和做事。理由:我喜欢离线通过测试的可靠子集,例如
py.test -m "not live" test_spam.py --blockage
将可靠地通过(使用漂亮的 pytest-blockage 模块来强制执行无网络访问限制)。
但是在每个使用 live_fixture
的测试函数上写出 @pytest.mark.live
装饰是乏味且容易出错的。有没有什么方法可以让该 fixture 声明任何使用它的测试函数都应该自动应用 @pytest.mark.live
装饰,或者某种方法来检测内部文件 test_spam.py test_one
和 test_three
使用那个 live_fixture
因此应该有效地修饰 @pytest.mark.live
?
最佳答案
我通过尝试挖掘 pytest.mark 的工作原理,找到了另一个看似合理的解决方案。
我发现类 Node 有一个方法“add_marker”,它应该是实现功能 pytest.mark 的确切方法。类 Item 是从 Node 扩展而来的。
所以我的解决方案是:
- 尝试查找测试是否使用了 fixture 。
- 让测试的Item对象调用add_marker
例子:在conftest.py中添加如下方法
def pytest_itemcollected(item):
""" we just collected a test item. """
if 'live_fixture' in item.fixturenames:
item.add_marker('live')
我希望至少我的回答能激发人们想出更体面的方法。
关于python - 基于fixture的自动pytest.mark修饰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37949078/