
pytest 的内置 request 固件无法直接通过方法签名注入到 setup_method/teardown_method 等钩子方法中;必须改用 @pytest.fixture(autouse=True) 方式,在函数作用域内显式声明并利用其生命周期控制逻辑。
pytest 的内置 `request` 固件无法直接通过方法签名注入到 `setup_method`/`teardown_method` 等钩子方法中;必须改用 `@pytest.fixture(autouse=true)` 方式,在函数作用域内显式声明并利用其生命周期控制逻辑。
在 pytest 中,request 是一个函数作用域(function-scoped)的内置 fixture,它仅在测试函数或显式声明为 fixture 依赖的函数体内自动注入。值得注意的是:setup_method 和 teardown_method 并非 pytest 原生 fixture,而是 unittest 风格的钩子方法——它们不参与 pytest 的 fixture 解析机制,因此即使你在签名中添加 request 参数,pytest 也不会为其注入值,从而导致 TypeError: teardown_method() missing 1 required positional argument: 'request'。
✅ 正确做法是:弃用 teardown_method,转而使用 autouse=True 的函数级 fixture,通过 yield 实现 setup/teardown 分离,并自然获得 request fixture 的访问权。
以下是一个推荐实现方案:
# conftest.py
import pytest
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
setattr(item, f"rep_{call.when}", rep)
# 在基类中定义 fixture(推荐放在 conftest.py 或基类所在模块)
@pytest.fixture(autouse=True, scope="function")
def method_lifecycle(self, request):
# ✅ setup 阶段:可访问 request、测试名称、参数等
print(f"Starting test: {request.node.name}")
yield # 暂停,等待测试执行
# ✅ teardown 阶段:此时可获取测试结果
outcome = getattr(request.node, "rep_call", None)
if outcome and hasattr(outcome, "outcome"):
status = outcome.outcome # 'passed', 'failed', 'skipped'
print(f"Test {request.node.name} finished with status: {status}")
if status == "failed":
# 可在此处执行失败后清理(如截图、日志归档等)
pass? 关键要点说明:
- @pytest.fixture(autouse=True, scope="function") 确保该 fixture 对每个测试函数自动生效,无需显式声明依赖;
- self 参数仅在测试类实例方法中有效(pytest 会自动将 self 注入 fixture,前提是 fixture 在类内被调用或通过 self 显式引用);但更健壮的做法是避免在 fixture 中依赖 self,改用 request.instance 获取当前测试实例:
@pytest.fixture(autouse=True) def method_lifecycle(self, request): instance = request.instance # 安全获取测试类实例(若存在) if instance and hasattr(instance, 'some_setup_attr'): # 执行实例相关逻辑 pass - pytest_runtest_makereport 钩子用于捕获测试执行各阶段(setup/call/teardown)的结果,使 request.node.rep_call 在 teardown 阶段可用;
- 若需区分 setup/teardown 行为,也可拆分为两个独立 fixture(一个 scope="function" 无 yield 作 setup,另一个 autouse=True + yield 作 teardown),但单 fixture yield 方式更简洁可控。
⚠️ 注意事项:
- 不要在 setup_method/teardown_method 中尝试接收 request —— 这是设计限制,非 bug;
- request fixture 在 fixture 函数体内才有效,不能“跨层”注入到普通方法;
- 若基类需复用 teardown 逻辑,建议将 fixture 定义在 conftest.py 中(对整个测试包生效),或通过 @pytest.mark.usefixtures("method_lifecycle") 显式标记基类。
综上,拥抱 pytest 的 fixture 模型而非 unittest 风格钩子,是实现灵活、可维护、可扩展测试生命周期管理的最佳实践。

















