在Pytest中,找不到fixture中定义的全局变量



我有以下名为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")

它给出了找不到变量"的错误;驱动器":

名称错误:名称"驱动程序"未定义

我错过了什么?

这看起来像是对pytest fixture功能的滥用。不需要全局变量。

我没有测试它,但沿着这些路线应该如何使用固定装置:

my_fixtures.py

from selenium import webdriver
import pytest
@pytest.fixture  # No need for autouse, and scope='function' is the default
def driver():  # Must match the name of the argument of the test function
driver = webdriver.Chrome()
driver.get("https://www.google.com/")
yield driver  # Yield the driver object to the test case
driver.quit()

测试用例:

from selenium.webdriver.common.by import By
import my_fixtures  # Makes the fixture available to pytest
def test_google_search(driver):  # Must match the name of the fixture
driver.find_element(By.CSS_SELECTOR,"input[name='q']").send_keys("hello test")

最新更新