python - 基于fixture的自动pytest.mark修饰

标签 python pytest python-decorators

假设我在 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_onetest_three 使用那个 live_fixture 因此应该有效地修饰 @pytest.mark.live?

最佳答案

我通过尝试挖掘 pytest.mark 的工作原理,找到了另一个看似合理的解决方案。

我发现类 Node 有一个方法“add_marker”,它应该是实现功能 pytest.mark 的确切方法。类 Item 是从 Node 扩展而来的。

所以我的解决方案是:

  1. 尝试查找测试是否使用了 fixture 。
  2. 让测试的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/

相关文章:

python - 在 python 中使用 Selenium、PhantomJS 和 Tor

python - 在 python 中使用外部文件进行测试

python - 有没有办法退出 pytest 测试并继续下一个测试?

Python3 不可能将 @property 作为装饰器参数传递

python - 如何制作函数装饰器并将它们链接在一起?

python - 计算装饰器内部可能调用或不调用的方法的调用次数

python - 如何防止我的 Colab notebook 在标准化我的图像时崩溃?

Python logging.DEBUG 级别不记录

python - 按列分组后如何获取频率最高的元素?

python - 合并两组非常相似的pytests