基于fixture的自动pytest.mark装饰

Jos*_*idt 4 python pytest python-decorators

假设我在 conftest.py 文件中建立了一个 pytest 固定装置,如下所示:

def live_fixture():
    # network access here...
    pass
Run Code Online (Sandbox Code Playgroud)

我在许多测试函数中使用了这个相同的装置,比如 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
Run Code Online (Sandbox Code Playgroud)

@pytest.mark.live在第一个和第三个测试函数上使用装饰,因为这两个测试都依赖于 fixture live_fixture,它通过网络发出并执行一些操作。理由:我喜欢让我的测试的可靠子集离线通过,例如

py.test -m "not live" test_spam.py --blockage
Run Code Online (Sandbox Code Playgroud)

将可靠地通过(使用漂亮的pytest-blockage模块来强制执行无网络访问限制)。

但是@pytest.mark.live在使用live_fixturehere 的每个测试函数上写出装饰是乏味且容易出错的。有没有办法让该夹具声明任何使用它的测试函数都应该自动对其@pytest.mark.live应用装饰,或者某种方法来检测文件 test_spam.py 中的那个test_onetest_three使用它live_fixture,因此应该被有效地装饰@pytest.mark.live

Li *_*eng 5

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

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

所以我的解决方案是:

  1. 试图找出测试是否使用了夹具。
  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')
Run Code Online (Sandbox Code Playgroud)

我希望至少我的回答会激发人们想出更体面的方法。