【问题标题】:How to run teardown function / fixture after parametrize参数化后如何运行拆卸功能/夹具
【发布时间】:2019-08-24 19:51:46
【问题描述】:

我正在尝试为一个测试用例的整个参数化运行拆卸功能/夹具。所以我想在我的 conftest.py 文件中有这样的东西

@pytest.fixture(autouse=True, scope="parametrization")
def parametrization_scope():
    print("First run of parametrization fixture")
    # Executing 100 parametrizations
    yield
    print("Yield run of parametrization fixture")

在我的 test.py 中类似于

@pytest.mark.parametrize(n-params)
# run initiate fixture here of parametrization
def test():
    # executing n number of times

# run yield fixture here of parametrization

【问题讨论】:

  • 将拆解代码放在夹具中yield之后。
  • 是的,如果有范围“参数化”,那将起作用。 “function”范围在每个测试用例运行之前/之后运行,“module”范围在整个模块/文件运行之前/之后运行,“session”范围用于在整个会话运行之前/之后运行。我需要的只是参数化之前/之后
  • parametrization 甚至是有效范围吗?
  • 不是。我只是举了一个例子来说明我想在这里取得成功。因此,与其他夹具范围类似的行为。我已经对其进行了一些解决方法,以便为我的最后一个配置(列表 [-1])提供一个名为“last_run”且其值设置为“True”的键,并在测试用例中检查此类键的存在,如果'last_run' 是 True....
  • 您可以做的是在钩子中实现您的自定义逻辑:pytest_sessionstart 在测试收集(以及参数化)运行之前调用,pytest_runtestloop 在测试收集完成后调用(并且所有测试都是参数化的),但在实际测试执行开始之前。

标签: python parameters automated-tests pytest fixtures


【解决方案1】:

您可以使用测试类来解决缺少的“参数化”范围,如下所示:

import pytest

@pytest.fixture(scope="class")
def foo():
    print("setup")
    yield None
    print("teardown")

class TestSum:
    @pytest.mark.parametrize(
        "a,b,c",
        [(3, 5, 8), (2, 4, 6)],
    )
    def test_eval(self, a, b, c, foo):
        assert a + b == c

如果只有TestSum 类使用fixture foo,你甚至可以将foo 的定义放在类中。

【讨论】:

  • 哇,@bnjmnp,好主意和解决方案。可悲的是,我已经用另一种不需要这样做的测试逻辑方式解决了这个问题。但是,很好的解决方案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 2020-03-23
  • 2023-03-03
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多