在测试完成时运行的基本 pytest 拆卸

cha*_*l_t 4 fixtures pytest teardown

我至少使用 pytest 作为通用测试运行程序,对工作中的各种 API 产品进行大型自动化集成测试,并且我一直在尝试找到一个同样通用的拆卸函数示例,该函数在任何测试完成时运行,无论测试成功或失败失败。

我的典型使用模式是超线性的,通常是这样的:

def test_1():
    <logic>
    assert something

def test_2():
    <logic>
    assert something

def test_3():
    <logic>
    assert something
Run Code Online (Sandbox Code Playgroud)

有时,当这样做有意义时,我会在脚本的顶部放入一个设置装置,并将自动使用参数设置为“True”,该参数在每个脚本启动时运行:

@pytest.fixture(scope="session", autouse=True)
def setup_something():
    testhelper = TestHelper
    testhelper.create_something(host="somehost", channel="somechannel")

def test_1():
    <logic>
    assert something

def test_2():
    <logic>
    assert something

def test_3():
    <logic>
    assert something
Run Code Online (Sandbox Code Playgroud)

直到最近,一次性 Docker 环境让我能够跳过整个拆卸过程,但我有点紧张,其中一个目前不可用。理想情况下,在不偏离我已经使用的相同线性模式的情况下,我将如何实现另一个 pytest 夹具,其功能如下:

@pytest.fixture
def teardown():
    testhelper = TestHelper
    testhelper.delete_something(thing=something)
Run Code Online (Sandbox Code Playgroud)

运行何时完成?

Bru*_*ira 6

每个灯具都可能有一个可拆卸的部分:

@pytest.fixture
def something(request):
   # setup code
   def finalize():
       # teardown code
   request.addfinalizer(finalize)
   return fixture_result
Run Code Online (Sandbox Code Playgroud)

或者像我通常使用的那样:

@pytest.fixture
def something():
    # setup code
    yield fixture_result
    # teardown code
Run Code Online (Sandbox Code Playgroud)

请注意,在 pytest 3.0 之前的版本中,后一种习惯用法所需的装饰器是@pytest.yield_fixture. 然而,从 3.0 开始,人们只能使用常规@pytest.fixture装饰器,并且@pytest.yield_fixture被弃用

在这里查看更多内容