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

在Pytest中无法找到fixture定义的全局变量driver问题求助

问题:运行Selenium+pytest测试时提示driver未定义

现有代码情况

functions.py 文件内容

from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest

@pytest.fixture(scope='function', autouse=True)
def create_driver():
    global driver
    driver = webdriver.Chrome()
    driver.get("https://www.google.com/")
    yield
    driver.quit()

测试用例文件内容

from functions import *

def test_google_search(create_driver):
    driver.find_element(By.CSS_SELECTOR,"input[name='q']").send_keys("hello test")

报错信息

NameError: name 'driver' is not defined

问题原因及解决方法

你使用global driver的方式存在问题:fixture里声明的全局变量仅在functions.py模块内部有效,测试用例所在的模块无法直接访问到这个变量。pytest的fixture设计是通过依赖注入传递实例,而非全局变量共享。

修改步骤

  1. 修改functions.py的fixture,返回driver实例
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest

@pytest.fixture(scope='function', autouse=True)
def create_driver():
    driver = webdriver.Chrome()
    driver.get("https://www.google.com/")
    yield driver  # 将driver实例返回给测试用例
    driver.quit()
  1. 修改测试用例,通过fixture参数接收driver
from functions import *
from selenium.webdriver.common.by import By

def test_google_search(create_driver):
    # 直接使用fixture参数对应的driver实例
    create_driver.find_element(By.CSS_SELECTOR,"input[name='q']").send_keys("hello test")

更直观的写法(可选)

可以把fixture名称改为driver,让代码逻辑更清晰:

修改后的functions.py

from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest

@pytest.fixture(scope='function', autouse=True)
def driver():
    driver = webdriver.Chrome()
    driver.get("https://www.google.com/")
    yield driver
    driver.quit()

修改后的测试用例

from functions import *
from selenium.webdriver.common.by import By

def test_google_search(driver):
    driver.find_element(By.CSS_SELECTOR,"input[name='q']").send_keys("hello test")

这种依赖注入的方式不仅符合pytest的设计规范,还能避免全局变量带来的模块耦合、并行测试冲突等问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:25:28