【问题标题】:Pytest Testing Try Catch Exception print messagePytest 测试尝试捕获异常打印消息
【发布时间】:2022-01-12 22:59:04
【问题描述】:

需要创建一个 Pytest 来测试函数是否打印出错误消息,而不是在 try/catch 异常打印块之后引发异常。

实际功能:

def location2index(loc: str) -> tuple[int, int]: #将棋子位置转换为对应的x和y坐标

try:
    if (loc[0].isalpha() and loc[1:].isnumeric()):
        a = ord(loc[0]) - 96
        b = int(loc[1:])
        return (a, b)
    else:
        raise ValueError ('The format of the location in the file is not correct')
except ValueError as V:
        print(V)

Pytest函数:

def test_location2index5():  
    with pytest.raises (ValueError): location2index('aa2')

一如既往地非常感谢您的建议!

【问题讨论】:

    标签: python exception printing try-catch


    【解决方案1】:

    我认为你应该使用capsys 夹具来检查标准输出:

    def test_location2index5(capsys):
        location2index('aa2')
        out, err = capsys.readouterr()
        assert "The format of the location in the file is not correct" in out
        
    

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2011-12-05
      • 2014-05-11
      • 2011-07-14
      • 2011-08-20
      相关资源
      最近更新 更多