You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pytest无法识别@pytest.fixture,Fixture跨类调用失败求助

问题原因排查

核心问题:Fixture定义缩进错误

你的conftest.py中,before_start fixture函数存在Python语法缩进错误,导致pytest无法识别这个自定义fixture。

看你代码里的问题点:

@pytest.fixture(scope="class")
    def before_start(request):  # 此处多了不必要的缩进
        # ... 函数内容

Python要求装饰器下方的函数定义必须和装饰器保持正确缩进层级,当前函数前的多余缩进会让它变成嵌套函数,pytest无法扫描到它作为全局可用的fixture。

修复步骤

  1. 修正conftest.py中before_start函数的缩进,让函数定义行和上方装饰器对齐:
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service


@pytest.fixture(scope="class")
def before_start(request):  # 缩进修正,与装饰器层级对齐
    s = Service('/Users/******/PycharmProjects/Framework/chromedriver')
    driver = webdriver.Chrome(service=s)
    driver.get("https://www.keurig.com/")
    driver.maximize_window()
    driver.implicitly_wait(10)
    request.cls.driver = driver
    yield
    driver.close()
  1. 重新运行测试,pytest即可正确识别before_start fixture。

验证方法

在终端执行pytest --fixtures命令,查看输出列表中是否包含before_start,若存在则说明fixture已被正确注册。

内容的提问来源于stack exchange,提问作者Tetiana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:12:31