【问题标题】:use type error message in pytest parametrize在 pytest 参数化中使用类型错误消息
【发布时间】:2017-01-30 12:54:08
【问题描述】:

我有一个函数会在满足某些条件时引发 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 作为参数化测试数据中的预期输出,给我一个失败的测试。

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    您不能期望消息错误是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
    

    【讨论】:

    • 无论我尝试什么类型的错误,它都会抛出我 AttributeError: 'TypeError' object has no attribute 'message'AttributeError: 'ValueError' object has no attribute 'message'
    • @George 试试str(excinfo) == expected_exception_message
    • 使用str(excinfo.value) 可以正常工作!单独的excinfo 也提供了文件的路径!所以,为了正确,请更正您的答案。谢谢! (如果我的代码raise TypeError('The message is {0}'.format(message)) 中有这样的东西,我认为没有办法将message 传递到预期的输出中,对吧?:)。当然,除非我们将它用作函数的参数我不想要。 (赞成)
    • @George 要区分异常,您还可以创建自己的以 ValueError 为父级的异常。然后你会有像pytest.raises(MyException) 这样的东西,你不需要检查消息......但你需要每个案例都有一个例外。另一个选项当然是检查 message'The message is {0}'.format(message) 的子字符串。
    • 第二个怎么办?测试是不是子串。
    猜你喜欢
    • 2020-02-02
    • 2017-10-27
    • 2022-05-29
    • 1970-01-01
    • 2023-02-15
    • 2019-12-21
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多