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

Selenium webdriver未被识别?pytest fixture使用问题排查

pytest Fixture 使用错误排查

问题场景

你编写了如下pytest的fixture和测试用例:

@pytest.fixture()
def init_driver():
    return webdriver.Chrome(executable_path=TestParams.CHROME_EXECUTABLE_PATH)


@pytest.mark.usefixtures('init_driver')
def test_1():
    driver = init_driver
    login(driver)

运行时出现错误:

AttributeError: 'function' object has no attribute 'get'

此时driver的类型为<class 'function'>,而非预期的WebDriver实例。你通过直接在测试用例中实例化WebDriver解决了问题,但不清楚原代码的错误点。

错误原因

使用@pytest.mark.usefixtures('init_driver')装饰测试函数时,fixture的返回值不会自动绑定到同名变量。此时你直接赋值的driver = init_driver,拿到的是fixture函数本身,而不是它执行后返回的WebDriver实例,自然无法调用get等WebDriver方法。

正确解决方案

方案1:直接将fixture作为测试函数参数(推荐)

去掉@pytest.mark.usefixtures装饰器,把fixture名称作为测试函数的参数传入,pytest会自动执行fixture并将返回的实例注入:

@pytest.fixture()
def init_driver():
    # 建议添加yield实现资源清理,比如用例结束后关闭浏览器
    driver = webdriver.Chrome(executable_path=TestParams.CHROME_EXECUTABLE_PATH)
    yield driver
    driver.quit()

def test_1(init_driver):
    # 此时init_driver就是WebDriver实例
    login(init_driver)
    # 可直接调用WebDriver方法,比如init_driver.get("https://example.com")

方案2:结合request fixture获取实例(若需保留usefixtures)

如果必须使用@pytest.mark.usefixtures,可以通过request fixture的getfixturevalue方法获取fixture的返回实例:

@pytest.fixture()
def init_driver():
    return webdriver.Chrome(executable_path=TestParams.CHROME_EXECUTABLE_PATH)

@pytest.mark.usefixtures('init_driver')
def test_1(request):
    driver = request.getfixturevalue('init_driver')
    login(driver)

临时解决方法的问题

你直接在测试用例中实例化WebDriver的方式虽然能运行,但失去了fixture的核心优势:

  • 无法复用WebDriver实例,每个测试用例会重复创建新实例,降低运行效率
  • 无法统一管理资源清理(比如用例结束后关闭浏览器)
  • 不利于后续维护,若需修改WebDriver的初始化逻辑,要逐个修改测试用例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:25:32