Python 在pytest参数化中使用类型错误消息
我有一个函数,它在满足某些条件时会引发TypeErrorPython 在pytest参数化中使用类型错误消息,python,pytest,Python,Pytest,我有一个函数,它在满足某些条件时会引发TypeError def myfunc(..args here...): ... raise TypeError('Message') 我想使用pytest参数化测试此消息 但是,因为我使用了其他参数,所以我希望有这样的设置: testdata = [ (..args here..., 'Message'), # Message is the expected output ] @pytest.mark
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
简单地将
消息
作为参数化测试数据中的预期输出,会导致测试失败。您不能期望消息错误作为myfunc
的正常输出。这有一个特殊的上下文管理器-pytest.raises
,如果希望看到某些错误及其消息
所以,在你的情况下,这将是
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
无论我尝试什么类型的错误,它都会向我抛出
AttributeError:“TypeError”对象没有属性“message”
,或者AttributeError:“ValueError”对象没有属性“message”
@George try withstr(excinfo)(excinfo)==预期的异常消息
withstr(excinfo.value)
它工作正常!exinfo本身也提供了文件的路径!所以,为了正确,请更正您的答案。谢谢!(如果我的代码中有这样的东西,raisetypeerror('message是{0}.format(message))
,我认为没有办法将message
传递到预期的输出中,对吗?:)。当然,除非我们使用它作为函数的参数,而我不想要它。(向上投票)@George要区分异常,您还可以创建自己的异常,该异常具有ValueError
作为父项。然后您将有类似于pytest.raises(MyException)
的东西,您不需要检查消息。。。但每个案例都需要一个例外。另一个选项当然是检查ismessage
是否是的子字符串,消息是{0}。格式化(message)
。如何执行第二个?测试它是否是子字符串。
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