config.cache 使用

官方地址: https://docs.pytest.org/en/8.0.x/reference/reference.html#config-cache

pytest 中,cache 是一个非常有用的功能,它允许你在测试会话之间持久化状态。这意味着你可以在一次测试运行中存储一些值,并在后续的测试运行中访问这些值。这对于需要重用昂贵的计算结果或避免重复执行时间密集型操作的场景特别有用。

如何使用 cache

cache 对象通过 pytestFixtureRequest 对象提供,通常在一个 fixture 中获取并返回它

python 复制代码
@fixture
def cache(request: FixtureRequest) -> Cache:
    """Return a cache object that can persist state between testing sessions.

    cache.get(key, default)
    cache.set(key, value)

    Keys must be ``/`` separated strings, where the first part is usually the
    name of your plugin or application to avoid clashes with other cache users.

    Values can be any object handled by the json stdlib module.
    """
    assert request.config.cache is not None
    return request.config.cache

是一个本地缓存,并且是存储到了本地的 .pytest_cache 文件夹中,一个key 一个文件

存储和检索数据

cache 对象提供了两个主要方法:getset

  • get(key, default=None) 方法用于检索之前存储的值。如果指定的 key 不存在,则返回 default 值。
  • set(key, value) 方法用于存储值。key 应该是一个字符串,而 value 可以是任何可以被 json 标准库模块处理的对象。

键应该使用 / 分隔的字符串,其中第一部分通常是你的插件或应用程序的名称,以避免与其他使用 cache 的代码冲突。

示例

假设你有一个测试,需要从外部API获取数据,但这个操作很耗时。你可以在第一次运行测试时从API获取数据,并将其存储在 cache 中。在后续的测试运行中,你可以直接从 cache 中检索数据,避免重复的API调用。

python 复制代码
def test_external_api(cache):
    # 尝试从缓存中获取数据
    data = cache.get('external_api/data', default=None)
    if data is None:
        # 如果缓存中没有数据,则从API获取并存储到缓存中
        data = fetch_data_from_external_api()  # 假设这是一个函数来获取数据
        cache.set('external_api/data', data)
    
    # 使用数据进行测试
    assert data is not None

注意事项

  • cache 在 CI 环境中可能不会像预期那样工作,因为每次构建可能使用全新的环境。
  • 使用 cache 时要小心避免过度依赖它,确保测试仍然可以独立运行而不是依赖于先前的测试结果。
  • 清晰地命名你的缓存键,以避免潜在的冲突和混淆。

通过合理使用 pytestcache 功能,可以显著提高测试效率,特别是在处理需要大量计算资源的测试时。