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

使用pytest parametrize装饰器时,首测后Web Driver未关闭的问题

问题描述

带不同参数的首次测试可正常执行,但Web Driver无法正常关闭,导致带其他参数的第二次测试无法启动。

相关代码

conftest.py

@pytest.fixture(scope="class")
def driver(request):
    driver = BrowserFactory.create_chrome_driver()
    driver.implicitly_wait(10)
    driver.maximize_window()
    driver.get("https://www.saucedemo.com")

    def teardown():
        driver.quit()

    request.addfinalizer(teardown)

    return driver

@pytest.fixture(scope="class")
def inventory_object(driver):
    # 创建Dummy类实例
    return Inventory(driver)


@pytest.fixture(scope="class")
def login_test_data():
    df = pandas.read_csv(r"C:/Users/user/PycharmProjects/pythonProject4/Testdata/login.csv")
    dicts = df.to_dict('records')
    return dicts

@pytest.fixture(scope="class")
def login_object(driver):
    return LoginPage(driver)

test_inventory.py

@pytest.mark.parametrize("values", ["za","hilo","liho"])
def test_select_za(self,values,login_test_data,login_object,inventory_object):
    self.test_login.test_login_successful(login_test_data, login_object)
    print(values)
    inventory_object.select_filter(values)
问题原因与解决方案

核心问题在于driver fixture的作用域为class,而参数化测试会生成多个测试实例,但class级别的fixture仅初始化一次,teardown也只会在整个测试类执行完毕后运行。这导致首次参数测试完成后WebDriver不会关闭,后续参数测试复用同一状态异常的Driver,进而无法启动新测试。

解决步骤:

  1. 将driver fixture的作用域改为function,让每个参数化测试用例都创建全新的Driver实例,执行完后立即关闭:
@pytest.fixture(scope="function")  # 修改作用域为function
def driver(request):
    driver = BrowserFactory.create_chrome_driver()
    driver.implicitly_wait(10)
    driver.maximize_window()
    driver.get("https://www.saucedemo.com")

    def teardown():
        driver.quit()

    request.addfinalizer(teardown)

    return driver
  1. 同步调整依赖driver的其他fixture(inventory_object、login_object)的作用域为function,确保每个测试用例都能获取全新的页面对象实例:
@pytest.fixture(scope="function")
def inventory_object(driver):
    return Inventory(driver)

@pytest.fixture(scope="function")
def login_object(driver):
    return LoginPage(driver)
  1. 调整后每个参数化测试都会使用独立的Driver,self.test_login.test_login_successful会在每次测试前重新执行登录逻辑,符合测试隔离的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 10:00:23