pytest如何重新运行失败的测试并在测试运行之间维护状态

  1. 有了这个插件提供了两个命令行选项来重新运行上次pytest调用的失败:
# 在运行完用例后,再次运行,只重新运行之前失败的用例
--lf, --last-failed
# 首先运行失败,然后运行其余的测试
--ff, --failed-first

pytest -ff test_demo.py
pytest -lf test_demo.py
  1. 对于清理(通常不需要),——cache-clear选项允许在测试运行之前删除所有跨会话的缓存内容。
    其他插件可以访问配置。在pytest调用之间设置/获取json可编码值的缓存对象。

  2. 上次运行中没有测试失败时的行为:
    具体是:如果在最近一次运行中没有失败的测试,或者没有找到缓存的最后一次失败数据,可以使用——last-failed-no-failure选项将pytest配置为运行所有测试或不运行测试,该选项采用以下值之一:

pytest --last-failed --last-failed-no-failures all    # run all tests (default behavior)
pytest --last-failed --last-failed-no-failures none   # run no tests
  1. 配置新的缓存对象(The new config.cache object):
    插件或conftest.py支持代码可以使用pytest配置对象获得一个缓存值。下面是一个基本的插件示例,它实现了一个fixture,可以在调用pytest时重用以前创建的状态:
# -*- coding: utf-8 -*-
import pytest
import time


def expensive_computation():
    print("running expensive computation...")

@pytest.fixture
def mydata(request):
    val = request.config.cache.get("example/value", None)
    if val is None:
        expensive_computation()
        val = 42
        request.config.cache.set("example/value", val)
    return val

def test_function(mydata):
    assert mydata == 23

然后检查缓存的内容:
你可以使用命令行选项--cache-show查看缓存的内容:

pytest --cache-show
  1. 清除缓存(Clearing Cache content):
# 你可以像这样通过添加——cache-clear选项来指示pytest清除所有缓存文件和值:
pytest --cache-clear
# 强烈建议:对于来自持续集成服务器的调用,建议这样做,因为隔离和正确性比速度更重要。
posted @ 2022-03-12 23:03  清风吹拂啊狂风肆虐  阅读(284)  评论(0编辑  收藏  举报