为了账号安全,请及时绑定邮箱和手机立即绑定

pytest:通过固定装置参数化测试用例

pytest:通过固定装置参数化测试用例

holdtom 2022-12-27 16:34:54
您如何编写产生/返回参数化测试参数的夹具(一种方法)?例如,我有一个测试如下:@pytest.mark.parametrize(    "input,expected",     [("hello", "hello"),    ("world", "world")])def test_get_message(self, input, expected):    assert expected == MyClass.get_message(input)我对以下方法感兴趣,而不是通过input和expected传递:@pytest.mark.parametrize@pytest.fixture(scope="session")def test_messages(self):    # what should I write here to return multiple     # test case with expected value for each?    passdef test_get_message(self, test_messages):    expected = test_messages["expected"] # somehow extracted from test_messages?    input = test_messages["input"]       # somehow extracted from test message?    assert expected == MyClass.get_message(input)
查看完整描述

2 回答

?
不负相思意

TA贡献1777条经验 获得超10个赞

要将参数移动到夹具中,您可以使用夹具参数:


@pytest.fixture(params=[("hello", "hello"),

    ("world", "world")], scope="session")

def test_messages(self, request):

    return request.param


def test_get_message(self, test_messages):

    input = test_messages[0]   

    expected = test_messages[1]

    assert expected == MyClass.get_message(input)

您还可以将参数放入单独的函数中(与 wih 相同parametrize),例如


def get_test_messages():

    return [("hello", "hello"), ("world", "world")]


@pytest.fixture(params=get_test_messages(), scope="session")

def test_messages(self, request):

    return request.param


查看完整回答
反对 回复 2022-12-27
?
烙印99

TA贡献1829条经验 获得超13个赞

对我来说,你似乎想返回一个字典数组:


@pytest.fixture(scope="session")

def test_messages():

    return [

        {

            "input": "hello",

            "expected": "world"

        },

        {

            "input": "hello",

            "expected": "hello"

        }

    ]

要在测试用例中使用它,您需要遍历数组:


def test_get_message(self, test_messages):

    for test_data in test_messages:

        input = test_data["input"]

        expected = test_data["expected"]

        assert input == expected

但我不确定这是否是最好的方法,因为它仍然被视为只有一个测试用例,因此它只会在输出/报告中显示为一个测试用例。


查看完整回答
反对 回复 2022-12-27
  • 2 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号