简体   繁体   English

在一个pytest函数中进行多次测试

[英]Multiple tests in one pytest function

I have a "conceptual" question regarding pytest and how I should handle multiple tests. 我有一个关于pytest的“概念”问题以及我应该如何处理多个测试。

Let's say I need to test something for a bunch of strings: names = [" ", "a ", " a", " a "] . 假设我需要为一堆字符串测试一些东西: names = [" ", "a ", " a", " a "]

I could create multiple test_ functions to test them individually, but they would be exactly the same, but with different input. 我可以创建多个test_函数来单独测试它们,但它们完全相同,但输入不同。

I was thinking on doing something like: 我在想做类似的事情:

def test_names():
    names = [" ", "a ", " a", " a "]
    for name in names:
        with pytest.raises(errors.MyFooError) as ex:
            random_method(name)

The problem is: doing this, in case one element doesn't raise errors.MyFooError , I would receive this: 问题是:这样做,以防一个元素没有引发errors.MyFooError ,我会收到这个:

Failed: DID NOT RAISE <class 'errors.MyFooError'

The message is generic, I have no idea in which element this occurred. 该消息是通用的,我不知道发生了哪个元素。

I would probably just split into 4 tests, one for each element of the list, I guess this is the correct way to do it? 我可能会分成4个测试,一个用于列表中的每个元素,我想这是正确的方法吗? What happens if the list is huge? 如果列表很大,会发生什么?

You should use the parametrize capabilities of pytest as shown here . 您应该使用parametrize的能力pytest如图所示这里

Your code would look as 你的代码看起来像

import pytest

@pytest.mark.parametrize('input', [" ", "a ", " a", " a "])
def test_names(input):
    with pytest.raises(errors.MyFooError) as ex:
        random_method(input)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM