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

PyCharm无法识别已安装包,运行pytest测试报AttributeError求助

问题排查与解决方案

核心定位

报错AttributeError: type object 'Test_**' has no attribute 'driver'明确是driver fixture未正确注入测试类,和依赖安装无关(已确认依赖安装正常)。

排查与修复步骤

  • 校验fixture定义与作用域
    确认driver fixture的装饰器、作用域设置正确。如果是给整个测试类使用,需指定scope="class",示例:
    import pytest
    from selenium import webdriver
    
    @pytest.fixture(scope="class")
    def driver():
        driver = webdriver.Chrome()
        yield driver
        driver.quit()
    
  • 修正测试类的fixture引用方式
    测试类中必须通过实例属性访问driver,不能直接访问类属性。正确的引用方式二选一:
    1. 用装饰器标记测试类:
      @pytest.mark.usefixtures("driver")
      class Test_Example:
          def test_case(self):
              self.driver.get("https://example.com")
      
    2. 在测试方法中以参数接收fixture:
      class Test_Example:
          def test_case(self, driver):
              driver.get("https://example.com")
      
  • 检查pytest配置文件位置
    确保定义fixture的conftest.py放在项目根目录或测试目录下,pytest才能自动识别加载。
  • 清理pytest缓存
    缓存异常可能导致偶发成功的情况,执行命令清理后重新运行:
    pytest --cache-clear tests/folder/test
    
  • 调整调试器运行配置
    PyCharm调试时,确认运行配置的目标路径正确,且使用的解释器是项目对应的虚拟环境,避免调试时加载错误的环境配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:31:07