I have multiple functions which raise ValueError
to test. So far my solution is:
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
but in this approach I am repeating function name in each test case. I try to get rid of it. I was wondering if is it possible to make something similar to:
@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
This produces ValueError
. Is there a way to use two parametrize markers working with each other? If not how can I correct this code?
I solved my problem by mapping test function with tested element inside fixture. Anyway I still wonder if it is possible to achieve same effect using double parametrization. Other, more elegant solutions will be really appreciated.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.