在 pytest 参数化中使用类型错误消息
use type error message in pytest parametrize
我有一个函数,当满足某些条件时会引发 TypeError。
def myfunc(..args here...):
...
raise TypeError('Message')
我想使用 pytest 参数化测试此消息。
但是,因为我还使用了其他参数,所以我想要这样的设置:
testdata = [
(..args here..., 'Message'), # Message is the expected output
]
@pytest.mark.parametrize(
"..args here..., expected_output", testdata)
def test_myfunc(
..args here..., expected_output):
obs = myfunc()
assert obs == expected_output
简单地将 Message
作为参数化测试数据中的预期输出,给我一个失败的测试。
您不能将消息错误视为 myfunc
的正常输出。为此有一个特殊的上下文管理器 - pytest.raises
.
For example,如果您希望出现一些错误及其消息
def test_raises():
with pytest.raises(Exception) as excinfo:
raise Exception('some info')
assert str(excinfo.value) == 'some info'
因此,在您的情况下,这将类似于
testdata = [
(..args here..., 'Message')
]
@pytest.mark.parametrize("..args here..., expected_exception_message", testdata)
def test_myfunc(..args here..., expected_exception_message):
with pytest.raises(TypeError) as excinfo:
obs = myfunc(..args here...)
assert str(excinfo.value) == expected_exception_message
我有一个函数,当满足某些条件时会引发 TypeError。
def myfunc(..args here...):
...
raise TypeError('Message')
我想使用 pytest 参数化测试此消息。
但是,因为我还使用了其他参数,所以我想要这样的设置:
testdata = [
(..args here..., 'Message'), # Message is the expected output
]
@pytest.mark.parametrize(
"..args here..., expected_output", testdata)
def test_myfunc(
..args here..., expected_output):
obs = myfunc()
assert obs == expected_output
简单地将 Message
作为参数化测试数据中的预期输出,给我一个失败的测试。
您不能将消息错误视为 myfunc
的正常输出。为此有一个特殊的上下文管理器 - pytest.raises
.
For example,如果您希望出现一些错误及其消息
def test_raises(): with pytest.raises(Exception) as excinfo: raise Exception('some info') assert str(excinfo.value) == 'some info'
因此,在您的情况下,这将类似于
testdata = [
(..args here..., 'Message')
]
@pytest.mark.parametrize("..args here..., expected_exception_message", testdata)
def test_myfunc(..args here..., expected_exception_message):
with pytest.raises(TypeError) as excinfo:
obs = myfunc(..args here...)
assert str(excinfo.value) == expected_exception_message