Python 在pytest参数化中使用类型错误消息

Python 在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

我有一个函数,它在满足某些条件时会引发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

简单地将
消息
作为参数化测试数据中的预期输出,会导致测试失败。

您不能期望消息错误作为
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 with
str(excinfo)(excinfo)==预期的异常消息
with
str(excinfo.value)
它工作正常!exinfo本身也提供了文件的路径!所以,为了正确,请更正您的答案。谢谢!(如果我的代码中有这样的东西,
raisetypeerror('message是{0}.format(message))
,我认为没有办法将
message
传递到预期的输出中,对吗?:)。当然,除非我们使用它作为函数的参数,而我不想要它。(向上投票)@George要区分异常,您还可以创建自己的异常,该异常具有
ValueError
作为父项。然后您将有类似于
pytest.raises(MyException)
的东西,您不需要检查消息。。。但每个案例都需要一个例外。另一个选项当然是检查is
message
是否是
的子字符串,消息是{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