系统学习 测试与质量四阶段学习路径:从单元与接口测试,到端到端、性能、契约和 CI 门禁

用 fixture 管理测试的前置数据、外部连接、临时文件和清理逻辑

适用场景

多个用例需要重复创建数据库连接、临时文件、HTTP 客户端或登录态;或者需要在测试结束后可靠清理资源。fixture 比 setUp、tearDown 更灵活,可以组合、参数化并控制作用域。

核心概念 / 语法

声明、注入与作用域

用 @pytest.fixture 装饰函数,测试函数把 fixture 名写成参数即可注入。作用域由小到大为 function(默认)、class、module、package、session;高作用域 fixture 不能依赖低作用域 fixture,否则报 ScopeMismatch。跨文件共享放进 conftest.py,pytest 会自动发现,不需要 import,且只对所在目录及子目录生效。

yield 与清理

fixture 可以用 yield 把准备和清理写在一起:

@pytest.fixture
def resource():
    obj = create_resource()
    yield obj
    obj.close()

yield 之前是 setup,之后是 teardown;测试失败时 teardown 仍会执行。多个 fixture 的清理顺序与创建顺序相反,依赖方先清理,被依赖方后清理。如果 setup 在 yield 之前就抛异常,yield 之后的代码不会执行;这种场景用 request.addfinalizer 注册清理。

factory、autouse 与内置 fixture

factory fixture 不直接返回资源,而是返回一个创建资源的函数,让一个用例按需创建多份实例,并统一收集清理。

autouse=True 让 fixture 自动作用于当前作用域的每个测试,适合设置环境变量;副作用不明显的场景应显式注入,避免隐藏依赖。

常用内置 fixture:tmp_path 提供函数级临时目录,tmp_path_factory 提供会话级目录工厂,monkeypatch 临时修改环境变量和属性,capsys 捕获输出,request 访问参数、节点和终结器。

常用示例

1. conftest 中的 yield fixture

# conftest.py
import pytest


@pytest.fixture
def user():
    data = {"name": "alice", "active": True}
    yield data
    data.clear()
# test_user.py
def test_user_active(user):
    assert user["active"] is True
python -m pytest -q test_user.py

2. factory fixture 配合 tmp_path

import pytest


@pytest.fixture
def make_file(tmp_path):
    created = []

    def _make(name, text):
        path = tmp_path / name
        path.write_text(text, encoding="utf-8")
        created.append(path)
        return path

    yield _make
    for path in created:
        path.unlink(missing_ok=True)


def test_make_file(make_file):
    path = make_file("a.txt", "hello")
    assert path.read_text(encoding="utf-8") == "hello"

3. 会话级连接与 autouse 环境变量

import sqlite3
import pytest


@pytest.fixture(scope="session")
def db():
    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
    yield conn
    conn.close()


@pytest.fixture(autouse=True)
def test_env(monkeypatch):
    monkeypatch.setenv("APP_ENV", "test")


def test_insert(db):
    db.execute("INSERT INTO users (name) VALUES (?)", ("alice",))
    assert db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1

易错点

相关条目

参考链接

读完自测

  1. 默认 fixture 作用域是什么?改成 session 后有什么代价?
  2. 为什么 yield 之前的 setup 失败时,写在 yield 之后的清理可能不执行?
  3. 一个测试要创建多个临时资源,应该用普通 fixture 还是 factory fixture?
答案
  1. 默认是 function;改为 session 后只创建一次,但共享可变状态可能污染后续测试。
  2. 只有执行到 yield 才会登记后续 teardown;setup 提前抛异常时,后面的代码不会运行。
  3. 用 factory fixture 返回创建函数,便于按需创建多份并统一清理。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令