【问题标题】:pytest fixture passing valuespytest 夹具传递值
【发布时间】:2018-06-08 01:17:37
【问题描述】:

我正在尝试将值传递给夹具,因为我基本上对许多测试都有相同的代码,但只有一些值发生变化,因为我理解 pytest 夹具不接受这一点,但不确定如何解决这个问题,因为例如我有这个:

import pytest


@pytest.fixture
def option_a():
    a = 1
    b = 2
    return print(a + b)


@pytest.fixture
def option_b():
    a = 5
    b = 3
    return print(a + b)


def test_foo(option_b):
    pass

不是在夹具选项 a 或选项 b 之间进行选择,而是都添加,唯一改变的是值,我可以有一个夹具来设置我想在 test_foo 上运行的值吗?

提前致谢。

【问题讨论】:

标签: python pytest


【解决方案1】:

您提供的示例非常简单,您不需要固定装置。你只需这样做:

import pytest

@pytest.mark.parametrize("a,b,expected", [
    (1,2,3),
    (5,3,8),
])
def test_foo(a, b, expected):
    assert a + b == expected

详情请见https://docs.pytest.org/en/3.6.1/parametrize.html

但是,我假设您只是将其简化为制作MCVE 的一部分。在这种情况下,您需要执行以下操作:

@pytest.fixture(params=[(1 , 2, "three"), (5,3,"eight")])
def option_a_and_b(request):
    a, b, word = request.param
    return a + b, word

def test_foo(option_a_and_b):
    total, word = option_a_and_b
    if total == 3:
        assert word == "three"
    elif total == 8:
        assert word == "eight"
    else:
        assert False

def test_bar(option_a_and_b):
    pass

如果您运行此代码,您会注意到 4 个通过测试,因为获得该夹具的每个测试都将为每个 param 运行。

详情请见https://docs.pytest.org/en/3.6.1/fixture.html#fixture-parametrize

【讨论】:

  • 感谢 Zev,您的代码很容易理解,我只是有一个问题,如果我只想在 test_foo 上使用第二个参数 (5,3,"eight"] 而不删除第一个参数夹具 option_a_and_b (1 , 2, "three"), 我该怎么做?我正在尝试这个,因为我的夹具包含可用于许多测试的代码,但唯一改变的是值,谢谢
  • 您的意思是像 [fixture of fixtures](stackoverflow.com/questions/35777854/pytest-fixture-of-fixtures) 还是 indirect parameterization??如果没有更好地理解(查看代码)你在找什么,我不知道。如果您遇到特定问题,您可以发布实际代码的相关部分(而不是像这样的简单示例),您可能会获得更具体和相关的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-21
  • 2020-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多