代码之家  ›  专栏  ›  技术社区  ›  The Illusive Man

如何在pytest中捕获异常后打印消息

  •  3
  • The Illusive Man  · 技术社区  · 8 年前

    假设此示例代码:

    def test_foo():
        dict = load_dict()
        try:
            value = dict[foo][bar]
        except KeyError:
            print('missing foo or bar')
    

    如果它上升 KeyError 因为要么 foo 或 bar 不存在,测试不会因为捕获异常而失败。如果我加一个 raise SystemExit(1) ,它失败,打印消息并显示所有回溯。

    我的问题是,如果 键错误 是不是意味着测试失败了,所以我不需要 SystemExit ?

    2 回复  |  直到 8 年前
        1
  •  2
  •   hoefling    8 年前

    有一个函数 pytest.fail 显然没有通过测试:

    import pytest
    
    def test_foo():
        d1 = {'foo': 'bar'}
        try:
            value = d1['baz']
        except KeyError as err:
            pytest.fail('this was unexpected: {}'.format(err))
    

    然而,惯用的方法是使用 pytest.raises 验证引发异常的上下文管理器,使用一些方便的实用程序捕获异常以进行分析:

    import pytest
    
    def test_foo():
        d1 = {'foo': 'bar'}
        with pytest.raises(KeyError) as excinfo:
            value = d1['baz']
        assert excinfo.type == KeyError
        assert excinfo.match('baz')
    

    查看文档以获取更多示例。如果你熟悉 unittest , pytest.raises测试 吊坠是用来 unittest.TestCase.assertRaises ,而 pytest.fail测试失败 吊坠是用来 unittest.TestCase.fail .

        2
  •  1
  •   andrea-f    8 年前

    你可以使用 with pytest.raises 施工单位:

    def test_connection_fails(self,):
        with pytest.raises(KeyError) as excinfo:
            buckets = list_all_buckets()
    

    然后您可以不使用 sys.exit