我有多个函数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
这就产生了CCD_ 2。有没有一种方法可以使用两个相互作用的参数化标记?如果没有,我该如何更正此代码?
我通过将测试函数与fixture中的测试元素映射来解决问题。无论如何,我仍然想知道是否有可能使用双重参数化来达到同样的效果。其他更优雅的解决方案将不胜感激。
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