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

运行Pytest时fixture 'driver_init'未找到的问题求助

排查Pytest Fixture 'driver_init'未找到的问题

以下是几个常见的排查方向和解决办法:

  • 检查Fixture的定义位置
    Pytest只会自动加载conftest.py文件里的fixture,如果你的driver_init是写在普通测试文件或者其他命名的文件里,要么把它移到测试目录下的conftest.py,要么在测试文件里手动导入:from your_module import driver_init,再通过参数或装饰器引用。

  • 核对Fixture的拼写与定义
    先确认driver_init的函数名完全匹配,大小写、字符一个都不能错,比如别写成driver_init_或者DriverInit。另外要确保函数上方加了@pytest.fixture()装饰器,正确定义示例:

    import pytest
    from selenium import webdriver
    
    @pytest.fixture()
    def driver_init():
        driver = webdriver.Chrome()
        yield driver
        driver.quit()
    
  • 检查测试函数的引用方式
    引用fixture有两种正确方式:

    1. 直接作为测试函数的参数传入:
      def test_open_page(driver_init):
          driver_init.get("https://example.com")
          assert driver_init.title == "Example Domain"
      
    2. 用@pytest.mark.usefixtures("driver_init")装饰测试函数或类,注意如果要在类里直接用driver,需要在fixture里通过request参数把driver绑定到测试实例:
      @pytest.fixture()
      def driver_init(request):
          driver = webdriver.Chrome()
          request.instance.driver = driver
          yield driver
          driver.quit()
      
      @pytest.mark.usefixtures("driver_init")
      class TestWebsite:
          def test_title(self):
              self.driver.get("https://example.com")
              assert self.driver.title == "Example Domain"
      
  • 排查目录结构与Pytest配置
    确认测试文件命名符合Pytest规则(以test_开头或_test.py结尾),如果用了pytest.ini或pyproject.toml,检查testpaths配置有没有包含fixture所在的目录,别把它排除在外。

  • 检查虚拟环境与依赖
    有时候依赖冲突或安装不完整也会导致问题,试试卸载重装相关包:

    pip uninstall pytest selenium -y
    pip install pytest selenium
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:45:39