Pytest Fixture 作用域详解:Function、Class、Module、Session 怎么选

在做接口或 UI 自动化测试时,pytest 的 fixture(夹具) 是前置/后置管理、数据准备和资源复用的利器。

很多新手最迷惑的就是 scope(作用域),比如:

  • scope="function" 是不是每个用例都用同一份?
  • scope="class" 为什么模块级函数不共享?
  • 怎么保证测试用例互不干扰?

今天我们就用 直觉 + 示例 + 面试回答 三步,把 fixture 作用域讲清楚。


一、fixture 基本语法回顾

python 复制代码
import pytest

@pytest.fixture
def data_box():
    print("\n👉 创建一份新数据")
    box = {"count": 0}
    yield box
    print("👉 清理数据")

拆解

语法部分 作用
@pytest.fixture 声明这是一个 fixture,可在测试函数中使用
def data_box(): 函数名 = 测试函数里引用 fixture 的名字
yield 前 前置操作,测试执行前运行
yield 返回值 传给测试函数,作为参数使用
yield 后 后置操作,测试执行后运行

口诀yield 前 = 前置,yield = 给用例,yield 后 = 后置


二、fixture scope 详解

pytest 提供四种作用域:

scope 意义 什么时候创建 fixture
function 默认 每个测试函数/方法都会重新创建一次
class 类级 同一个类内所有方法共用一份 fixture
module 文件级 同一个文件内所有测试函数共用一份
session 会话级 整个 pytest 运行过程中共享一份

三、scope=function:互不干扰

python 复制代码
@pytest.fixture
def data_box():
    box = {"count": 0}
    yield box
python 复制代码
def test_a(data_box):
    data_box["count"] += 1
    print("test_a:", data_box)

def test_b(data_box):
    print("test_b:", data_box)

执行结果:

复制代码
创建一份新数据
test_a: {'count': 1}
清理数据

创建一份新数据
test_b: {'count': 0}
清理数据

解释

  • 每个函数都会 重新创建 fixture
  • 所以 test_a 的修改不会影响 test_b
  • function 作用域天然隔离,用于保证用例互不干扰

直观比喻:

  • ❌ 错误:所有用例用同一桶水 → 污染
  • ✅ 正确:每个用例接新水 → 独立互不影响

四、scope=class:类内共享

python 复制代码
@pytest.fixture(scope="class")
def data_box():
    box = {"count": 0}
    yield box

注意 :class 作用域 只对类内方法生效,模块级函数不会共享。

python 复制代码
class TestDemo:
    def test_a(self, data_box):
        data_box["count"] += 1
        print("test_a:", data_box)

    def test_b(self, data_box):
        print("test_b:", data_box)

输出:

复制代码
创建一份新数据
test_a: {'count': 1}
test_b: {'count': 1}
清理数据

✅ 两个方法共享同一个 data_box,互相影响。


五、scope=session 或 module:全局共享

python 复制代码
@pytest.fixture(scope="session")
def data_box():
    box = {"count": 0}
    yield box

所有测试函数,无论是否在同一个文件或类中,都会共用同一份 fixture:

复制代码
创建全局数据
test_a: {'count': 1}
test_b: {'count': 1}   # 被污染

适合登录、数据库连接、全局客户端等场景,但要注意 清理数据


六、常见踩坑

  1. 模块级函数 + scope="class"

    • class 作用域只在类内方法生效,模块级函数还是每个用例新建。
  2. 使用全局变量

python 复制代码
GLOBAL_BOX = {"count": 0}

@pytest.fixture
def bad_fixture():
    yield GLOBAL_BOX  # 所有用例都共用 GLOBAL_BOX
  • 即使 function 作用域,也会污染用例。
  • 正确做法:在 fixture 内新建对象
  1. 操作数据库不清理
python 复制代码
@pytest.fixture
def create_order():
    order_id = insert_order_into_db()
    yield order_id
    delete_order(order_id)  # ✅ 清理数据
相关推荐
feathered-feathered32 分钟前
测试实战【用例设计】自己写的项目+功能测试(1)
java·服务器·后端·功能测试·jmeter·单元测试·压力测试
茶杯梦轩34 分钟前
从零起步学习并发编程 || 第八章:线程池实战(避坑指南与最佳实践)
服务器·后端·面试
Trouvaille ~1 小时前
【动态规划篇】专题(一):斐波那契模型——从数学递推到算法思维
c++·算法·leetcode·青少年编程·面试·动态规划·入门
callJJ2 小时前
深入浅出 MVCC —— 从零理解 MySQL 并发控制
数据库·mysql·面试·并发·mvcc
测试渣2 小时前
持续集成中的自动化测试框架优化实战指南
python·ci/cd·单元测试·自动化·pytest
银发控、3 小时前
MySQL覆盖索引与索引下推
数据库·mysql·面试
NEXT063 小时前
数组转树与树转数组
前端·数据结构·面试
We་ct3 小时前
浏览器 Reflow(重排)与Repaint(重绘)全解析
前端·面试·edge·edge浏览器
ssshooter3 小时前
看完就懂 useLayoutEffect
前端·react.js·面试