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

标签 pytest fixtures teardown

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

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

def test_1():
    <logic>
    assert something

def test_2():
    <logic>
    assert something

def test_3():
    <logic>
    assert something

偶尔,当这样做有意义时,我会在我的脚本顶部放入一个设置 fixture ,其中 autouse 参数设置为“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

直到最近,一次性 docker 环境让我能够跳过整个拆解过程,但我有点手忙脚乱,其中一个现在不可用。理想情况下,在不偏离我已经使用的相同线性模式的情况下,我将如何实现另一个执行类似操作的 pytest fixture:

@pytest.fixture
def teardown():
    testhelper = TestHelper
    testhelper.delete_something(thing=something)

什么时候运行完成?

最佳答案

每个固定装置都可能有拆卸部分:

@pytest.fixture
def something(request):
   # setup code
   def finalize():
       # teardown code
   request.addfinalizer(finalize)
   return fixture_result

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

@pytest.fixture
def something():
    # setup code
    yield fixture_result
    # teardown code

请注意,在 pytest pre-3.0 中,后一个习语所需的装饰器是 @pytest.yield_fixture。然而,从 3.0 开始,人们可以只使用常规的 @pytest.fixture 装饰器,而 @pytest.yield_fixturedeprecated .

查看更多here

关于pytest - 在测试完成时运行的基本 pytest 拆解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33558450/

相关文章:

python - [py.test] : test dependencies

python - Allure 与 Pytest : no decorators for Title and Description

python - 如何在发生测试失败/错误时为 py.test 打印堆栈跟踪?

ruby-on-rails - 如何设置 RSpec 进行性能测试 'on the side'

pytest - 将变量传递给 pytest_sessionfinish

Python单元测试tearDownClass()实例,如何拥有它?

java - Junit @Before/@After 调用的顺序是什么?

python - 测试 CLI : how can i ignore test case by name?

ruby-on-rails - ActiveRecord::Fixture::FixtureError: 表 "users"没有名为 "monkey"的列

python - 我如何在相同的场景中使用相同的步骤,但在 pytest-bdd 中使用不同的参数?