如何使用pytest.raises遍历值的组合,并找出哪个组合失败?

时间:2020-04-19 13:48:21

标签: pytest

我将pytest.raises用于数组中的值的元组:

import pytest


def test_division():
    pairs = [(1, 0), (0, 1), (0, 0)]
    for a, b in pairs:
        with pytest.raises(ZeroDivisionError):
            a / b

当其中一个元组没有引起错误时,它将按预期方式失败。 但这并没有告诉我问题出在哪个元组上:

================================================ FAILURES ================================================
_____________________________________________ test_division ______________________________________________

    def test_division():
        pairs = [(1, 0), (0, 1), (0, 0)]
        for a, b in pairs:
            with pytest.raises(ZeroDivisionError):
>               a / b
E               Failed: DID NOT RAISE <class 'ZeroDivisionError'>

proj/divide_test.py:8: Failed
======================================== short test summary info =========================================
FAILED proj/divide_test.py::test_division - Failed: DID NOT RAISE <class 'ZeroDivisionError'>
====================================== 1 failed, 3 passed in 0.04s =======================================

在这种情况下,我想告诉我们(0, 1)是问题所在。
有没有办法使这些信息可访问?

1 个答案:

答案 0 :(得分:2)

使用参数化,而不是遍历测试内部的值:

import pytest

@pytest.mark.parametrize("pair", ((1, 0), (0, 1), (0, 0)), ids=str)
def test_division(pair):
    with pytest.raises(ZeroDivisionError):
        pair[0] / pair[1]

这会将每个值作为单独的测试处理,您将得到:

collecting ... collected 3 items

div_by_zero.py::test_division[(1, 0)] PASSED                             [ 33%]
div_by_zero.py::test_division[(0, 1)] FAILED                             [ 66%]
div_by_zero.py:2 (test_division[(0, 1)])
pair = (0, 1)

    @pytest.mark.parametrize("pair", ((1, 0), (0, 1), (0, 0)), ids=str)
    def test_division(pair):
        with pytest.raises(ZeroDivisionError):
>           pair[0] / pair[1]
E           Failed: DID NOT RAISE <class 'ZeroDivisionError'>

div_by_zero.py:6: Failed

div_by_zero.py::test_division[(0, 0)] PASSED                             [100%]

================================== FAILURES ===================================
...
div_by_zero.py:6: Failed
========================= 1 failed, 2 passed in 0.08s =========================

编辑:添加了ids=str,以使输出更具可读性,如@hoefling所建议