Pytest N 次测试失败后停止测试套件


在实际场景中,一旦准备好部署新版本的代码,首先将其部署到预生产/登台环境中。然后在其上运行一个测试套件。

仅当测试套件通过时,代码才有资格部署到生产环境。如果测试失败,无论是一个还是多个,代码都没有准备好生产。

因此,如果我们想在 n 次测试失败后立即停止执行测试套件怎么办。这可以在 pytest 中使用 maxfail 来完成。

在 n 次测试失败后立即停止执行测试套件的语法如下:

pytest --maxfail = <num>

使用以下代码创建文件 test_failure.py。

import pytest
import math

def test_sqrt_failure():
    num = 25
    assert math.sqrt(num) == 6

def test_square_failure():
    num = 7
    assert 7*7 == 40

def test_equality_failure():
    assert 10 == 11

执行此测试文件时,所有 3 个测试都将失败。在这里,我们将停止执行 一次失败后的测试本身由:

pytest test_failure.py -v --maxfail 1
test_failure.py::test_sqrt_failure FAILED
=================================== FAILURES
=================================== _______________________________________
test_sqrt_failure __________________________________________
    def test_sqrt_failure():
    num = 25
>  assert math.sqrt(num) == 6
E  assert 5.0 == 6
E  + where 5.0 = <built-in function sqrt>(25)
E  + where <built-in function sqrt>= math.sqrt
test_failure.py执行此测试文件时,所有 3 个测试都将失败。在这里,我们将停止执行 AssertionError
=============================== 1 failed in 0.04 seconds
===============================

在上面的结果中,我们可以看到执行在一次失败时停止。