Python自动化测试框架(Pytest)—— 深入理解 Fixture 夹具机制
·
Python自动化测试框架(Pytest) —— 夹具fixture
一、什么是Fixture
Fixture 是指: 在测试用例执行前和执行后自动运行的一段代码。
常见应用场景:
- ✅ 前置:加密参数 / 启动浏览器 / 注册/登录账号
- ✅ 后置:解密结果 / 关闭浏览器 / 删除账号
二、如何创建Fixture
只需三步:
- 定义一个普通函数
- 添加 @pytest.fixture 装饰器
- 使用 yield 分隔前置与后置操作
# conftest.py
import pytest
from datetime import datetime
print(">>> conftest.py 被加载了!") # 验证文件是否被识别
@pytest.fixture
def f():
print(f"\n{datetime.now()} | 用例开始执行")
yield # ← 用例在此处执行
print(f"\n{datetime.now()} | 用例执行完毕")
💡 注意:文件名必须是 conftest.py(不是 confest.py),否则 Pytest 无法自动发现!
三、如何使用Fixture
方式一:在用例的参数列表中,加入fixture名字即可
# test_add.py
import pytest
def add(a, b):
return a + b
class TestADD:
def test_int(self, f): # ← 注意:类中方法必须有 self
res = add(1, 4)
assert res == 5
⚠️ 常见错误:
若写成 def test_int(f):(缺少 self),Python 会把 f 当作 self,导致夹具未被注入,print 不输出!
结果:

方式二:使用 @pytest.mark.usefixtures
在用例类的前方加入标记,对类下面的所有用例都执行标记;也可以分别对类中的某一条用例加标记(加在用例的前面)
@pytest.mark.usefixtures("f")
class TestADD:
def test_int(self):
assert add(1, 4) == 5
def test_list(self):
assert add([1, 2], [3, 4, 5]) == [1, 2, 3, 4, 5]
结果:

✅ 优点:无需在每个方法中写参数 ❌ 缺点:无法获取夹具的返回值(见下文)
四、Fixture 高级用法
1. 自动执行(autouse=True)
让所有测试用例默认使用该夹具,无需显式声明:
@pytest.fixture(autouse = True)
def f():
print(datetime.now(),'用例开始执行')
yield #开始执行用例
print(datetime.now(),'用例执行完毕')
2. 夹具依赖(Fixture 之间互相调用)
一个夹具可以依赖另一个夹具:
@pytest.fixture()
def ff():
print("fixture的装饰器")
@pytest.fixture(autouse = True)
def f(ff):
print(datetime.now(),'用例开始执行')
yield #开始执行用例
print(datetime.now(),'用例执行完毕')
3. 返回值(通过 yield 传递数据)
将前置操作的结果返回给测试用例:
@pytest.fixture(autouse = True,scope='session')
def f(ff):
print(datetime.now(),'用例开始执行')
yield 123 #开始执行用例,并返回123
print(datetime.now(),'用例执行完毕')
用例:

打印结果:
(注:python语法函数可以有多个yield,但是pytest框架只有一个yield)
4. 作用域控制(scope 参数)

全局共享示例:
import pytest
from datetime import datetime
print(">>> conftest.py 被加载了!")
@pytest.fixture(scope='session')
def ff():
print("fixture的装饰器")
@pytest.fixture(autouse = True,scope='session')
def f(ff):
print(datetime.now(),'用例开始执行')
yield 123 #开始执行用例,并返回123
print(datetime.now(),'用例执行完毕')
结果如下:

五、最佳实践建议
- 优先使用 conftest.py 存放全局夹具
- 避免在夹具中写断言(应放在测试用例中)
- 合理设置 scope,避免重复初始化开销
- 返回关键对象(如 driver、token),便于用例使用
- 命名清晰:如 browser, logged_in_user, api_client

附录:上述代码结构如下:
Draft_Test/
├── main.py
├── test_add.py
├── confest.py
└── pytest.ini
更多推荐
所有评论(0)