一个测试可以对@ mark.parametrize进行两次测试吗?

时间:2020-05-01 09:57:51

标签: python testing pytest fixtures parametrized-testing

我有raise ValueError个要测试的功能。到目前为止,我的解决方案是:

import pytest
import record

@pytest.fixture(name='raised')
def is_value_error_raised(func, args):
    try:
        func(*args)
        return True
    except ValueError:
        return False


@pytest.mark.parametrize(('func', 'args', 'expected'),
                         ((record.check_length, ('Test', 1, 100), True),
                          (record.check_length, ('', 1, 100), False),
                          ))
def test_length_check(raised, expected):
    assert raised == expected


@pytest.mark.parametrize(('func', 'args', 'expected'),
                         ((record.check_lang_code, ['EN'], True),
                          (record.check_lang_code, ['Test'], False),
                          ))
def test_lang_check(raised, expected):
    assert raised == expected

但是在这种方法中,我在每个测试用例中都重复了函数名称。我试图摆脱它。我想知道是否可以制作类似于以下内容的东西:

@pytest.mark.parametrize(('func', record.check_lang_code))
@pytest.mark.parametrize(('args', 'expected'),
                         ((['EN'], True),
                          (['Test'], False),
                          ))
def test_lang_check(raised, expected):
    assert raised == expected

这将产生ValueError。有没有办法使用两个参数标记相互配合?如果没有,我该如何纠正此代码?

1 个答案:

答案 0 :(得分:0)

我通过将测试函数与夹具内部的被测元素映射来解决了我的问题。无论如何,我仍然想知道使用双重参数化是否有可能达到相同的效果。其他更优雅的解决方案将不胜感激。

import pytest
import record

@pytest.fixture(name='raised')
def is_value_error_raised(request, args):
    try:
        test_name = request.node.function.__name__
        {'test_length_check': record.check_length,
         'test_lang_check': record.check_lang_code,
        }[test_name](*args)
        return True
    except ValueError:
        return False


@pytest.mark.parametrize(('args', 'expected'), (
        (('Test', 1, 100), True),
        (('', 1, 100), False),
))
def test_length_check(raised, expected):
    assert raised == expected


@pytest.mark.parametrize(('args', 'expected'), (
        (['EN'], True),
        (['Test'], False),
))
def test_lang_check(raised, expected):
    assert raised == expected