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

Pytest Fixture执行完成后无法终止测试的问题求助

解决Pytest Session级Fixture执行后测试无法退出的问题

你的问题大概率出在全局变量的使用以及资源清理的细节上,咱们一步步来排查修复:

1. 移除不必要的global变量

你的browser fixture用了global driver来维护实例,但session级别的fixture本身会在整个测试会话期间保持状态,完全不需要依赖全局变量。全局变量很容易导致driver实例被意外引用,无法被Python的垃圾回收机制正确处理,进而导致测试进程挂起。

优化后的conftest.py代码:

import pytest
from selenium import webdriver

@pytest.fixture(scope='session')
def browser():
    print("Setting up webdriver connection...")
    profile = webdriver.FirefoxProfile()
    profile.accept_untrusted_certs = True
    profile.set_preference("network.proxy.type", 1)
    driver = webdriver.Firefox(firefox_profile=profile)
    driver.maximize_window()
    yield driver
    # 增加异常捕获,避免清理阶段报错导致进程卡住
    try:
        driver.quit()
        print("Webdriver connection closed..")
    except Exception as e:
        print(f"Error closing webdriver: {str(e)}")

2. 检查测试类中的代码细节

如果测试类里有以下操作,也可能导致无法正常退出:

  • 测试方法中手动重新赋值了driver变量,导致fixture创建的原实例被丢失
  • 测试中打开了新窗口/标签页,没有切换回主窗口就尝试关闭driver
  • 存在未处理的弹窗、异步请求阻塞了driver的退出流程

建议在测试类的收尾逻辑中添加窗口清理:

# 关闭所有非主窗口的标签页,确保driver能正常退出
main_window = driver.current_window_handle
for window in driver.window_handles:
    if window != main_window:
        driver.switch_to.window(window)
        driver.close()
driver.switch_to.window(main_window)

3. 验证驱动兼容性

如果上述调整后还是无法退出,可能是geckodriver与Firefox版本不匹配:

  • 确认geckodriver版本和本地Firefox版本对应(可参考Mozilla官方的版本兼容说明)
  • 尝试更新到最新版的geckodriver和Firefox

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:17:56