如何为 async fixture 设置作用域并缓存?

解读

国内一线互联网公司的 Python 服务端测试面试里,这道题出现的频率极高。面试官真正想考察的是:

  1. 你是否理解 pytest 的 fixture 作用域(scope)与缓存机制;
  2. 你是否知道 asyncio 事件循环与 pytest-asyncio 插件的交互细节;
  3. 你能否在生产级代码里避免“异步 fixture 被反复实例化”带来的性能损耗与数据污染。

很多候选人只回答“加 scope='session' 就行”,却忽略了 async fixture 的缓存必须满足“同一事件循环”这一前提,导致在分布式或多 worker 场景下出现诡异 bug。这道题要求你给出可落地的、符合 pytest 原生设计思想的完整方案。

知识点

  1. pytest fixture 的 scope 五级别:function、class、module、package、session。
  2. fixture 缓存 key 由 (fixture_name, scope, params) 组成;async fixture 的返回值会被包装成协程对象,缓存的是协程对象而非真实资源。
  3. pytest-asyncio 默认会为每个测试函数新建一个事件循环,导致 session/module 级 async fixture 在缓存命中时事件循环已关闭,抛出 RuntimeError: Event loop is closed。
  4. 解决思路: a. 使用 pytest-asyncio 提供的 event_loop fixture 并显式声明 scope=session,保证整个 pytest 进程只建一个循环; b. 在 async fixture 内部用 asyncstdlib 或 asyncer 等库实现“异步单例”,确保资源只初始化一次; c. 对需要惰性清理的共享资源(如数据库连接池、Redis 集群句柄)实现 async def aenter/aexit,并通过 request.addfinalizer 注册异步清理回调; d. 若使用 pytest-xdist 并行,需要把“可序列化”状态放到文件或外部缓存(如 Redis),否则每个 worker 会各自初始化一次,突破 session 级缓存语义。
  5. 面试加分项:提到 3.12 引入的 asyncio.Runner 以及 pytest-asyncio 0.21+ 的 asyncio_default_fixture_loop_scope 配置项,可一行配置全局事件循环作用域,无需手写 event_loop fixture。

答案

下面给出一段可直接放进国内公司代码库的工程级示例,满足“session 级异步缓存 + 自动清理 + 兼容 xdist”三大要求。

# conftest.py
import asyncio
import pytest_asyncio
from typing import AsyncGenerator
from redis.asyncio import Redis

# 1. 全局唯一事件循环,保证 session 级 async fixture 缓存命中时循环仍存活
@pytest_asyncio.fixture(scope="session")
def event_loop():
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

# 2. session 级异步单例:Redis 客户端
@pytest_asyncio.fixture(scope="session")
async def redis_client() -> AsyncGenerator[Redis, None]:
    # 使用 asyncstdlib.once 或自己实现异步锁,确保只连接一次
    client = Redis.from_url("redis://localhost:6379/9", decode_responses=True)
    await client.ping()          # 真正建立连接
    yield client
    await client.close()         # 会话结束优雅关闭

# 3. 测试用例侧零感知
async def test_order_flow(redis_client: Redis):
    await redis_client.set("order:1", "ok", ex=10)
    assert await redis_client.get("order:1") == "ok"

关键点说明

  • event_loop 显式声明 scope="session",与 redis_client 同一作用域,确保缓存 key 匹配。
  • async generator fixture 的 yield 语句把资源交给 pytest 缓存,finalizer 阶段自动跳转回协程做清理。
  • 若启用 pytest-xdist,需把 redis_client 换成外部连接池服务(如独立容器),否则每个 worker 会各自创建一次,符合 xdist 的设计哲学——进程级隔离。

拓展思考

  1. 如果公司已经把业务代码迁到 Python 3.11+,可以废弃自定义 event_loop,直接在 pyproject.toml 写:
    [tool.pytest.ini_options]
    asyncio_default_fixture_loop_scope = "session"
    
    一行配置即可让所有 async fixture 默认复用全局事件循环,减少样板代码。
  2. 对于“module”级数据库事务回滚场景,可在 async fixture 里结合 pytest-lazy-fixture 与 aiomysql.sa.create_engine 实现“每个模块一个事务模板”,在模块内所有测试函数间共享连接但隔离数据,兼顾速度与一致性。
  3. 当项目出现“异步 fixture 循环已关闭”偶发报错时,优先检查是否混用了 pytest-asyncio 与 pytest-tornasync、pytest-aiohttp 等多循环插件;国内不少老项目会同时引入,导致事件循环生命周期错乱,解决策略是统一使用 pytest-asyncio>=0.21 并显式关闭其他插件的循环创建逻辑。