You need to enable JavaScript to run this app. 使用pytest时提示自定义driver_init fixture未找到的问题
优惠活动
大模型
产品
解决方案
定价
更多

使用pytest时提示自定义driver_init fixture未找到的问题

自定义fixture driver_init 无法被pytest识别的排查方案

pytest报fixture找不到,本质是pytest启动扫描阶段没有加载到driver_init的定义,按照出现概率从高到低排查即可:

  • 第一优先级排查:fixture定义存在非法缩进
    从你贴的代码格式可以看到,def driver_init前面带有额外缩进,pytest会把这个函数识别成某个类/方法的内部嵌套函数,根本不会将其标记为可复用的fixture。fixture定义必须和所属模块的顶层代码保持一致缩进,不能嵌在类、测试方法、其他函数的内部。
  • 第二优先级排查:fixture存放路径不符合pytest自动扫描规则
    pytest默认只会自动扫描两个位置的fixture:
    • 测试目录下的所有conftest.py文件顶层的fixture,这类fixture不需要手动import,同目录及子目录下的测试用例都可以直接调用
    • 测试用例所在.py文件的全局作用域下的fixture
      如果你把fixture写在普通的utils.py、fixture.py这类自定义文件里,pytest不会自动扫描,必须在对应路径的conftest.py里手动import该fixture,才能被pytest加载。
  • 第三优先级排查:fixture所在模块加载报错被静默跳过
    只要fixture定义所在的.py文件在导入阶段出现依赖缺失、语法错误、参数报错(比如没有导入webdriver、没有导入Data配置类、新版本Selenium废弃的executable_path直接传给Chrome构造函数),pytest会直接标记整个模块加载失败,不会把里面的fixture加入可用列表,也不会弹出明确的加载失败指向。

可直接复用的正确写法示例

  1. 在测试用例同级目录新建conftest.py,写入无缩进的fixture定义:
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
# 导入项目内的配置类
from common.data import Data

@pytest.fixture(scope='class')
def driver_init(request):
    # 新版本Selenium需要通过Service对象传入驱动路径,直接给Chrome传executable_path会触发告警
    service = Service(executable_path=Data.Ch_exe_path)
    ch_driver = webdriver.Chrome(service=service)
    request.cls.driver = ch_driver
    yield
    ch_driver.close()
  1. 测试类中直接通过装饰器引用即可,不需要手动importfixture:
import pytest

@pytest.mark.usefixtures("driver_init")
class TestLogin:
    def test_open_page(self):
        # 直接通过self.driver即可拿到fixture初始化的浏览器实例
        self.driver.get("https://example.com")

内容的提问来源于stack exchange,提问作者Mohammad Azmul Haq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 22:36:02