在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设计是通过依赖注入传递实例,而非全局变量共享。
修改步骤
- 修改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()
- 修改测试用例,通过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
相关产品推荐
相关产品推荐

