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

Pytest启动chromedriver路径问题:不同运行目录执行报错

问题分析与解决方案

问题根源

这是相对路径不兼容工作目录变化导致的chromedriver启动失败:

  • 在项目根目录执行pytest tests/dashboard/rating_tool.py时,工作目录是项目根,conftest.py里配置的chromedriver相对路径能正确指向文件
  • 进入tests目录执行pytest rating_tool.py时,工作目录变为tests,原相对路径找不到chromedriver,直接引发启动崩溃

解决办法

1. 动态生成chromedriver绝对路径(推荐)

修改conftest.py中的fixture,通过代码自动获取tests目录的绝对路径,拼接chromedriver位置,彻底摆脱工作目录限制:

import os
import pytest
from selenium import webdriver

@pytest.fixture(scope="session")
def browser():
    # 获取当前conftest.py所在的tests目录绝对路径
    tests_dir = os.path.dirname(os.path.abspath(__file__))
    # 拼接chromedriver的完整路径(假设chromedriver在tests目录下)
    chromedriver_path = os.path.join(tests_dir, "chromedriver")
    driver = webdriver.Chrome(executable_path=chromedriver_path)
    yield driver
    driver.quit()

2. 在test_runner.py中固定工作目录

如果要通过自定义脚本运行测试,先在test_runner.py中切换到项目根目录,再执行pytest:

import os
import pytest

# 切换到项目根目录(假设test_runner.py放在项目根)
root_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(root_dir)

# 执行指定测试用例
pytest.main(["tests/dashboard/rating_tool.py"])

3. 配置pytest根目录(可选)

在项目根创建pytest.ini,指定测试根目录,让pytest始终以项目根为工作目录:

[pytest]
testpaths = tests

之后无论在哪个目录执行pytest,都会自动以项目根为基准解析路径。


验证步骤

  1. 修改conftest.py后,进入tests目录执行pytest dashboard/rating_tool.py,确认chromedriver正常启动
  2. 运行test_runner.py,检查测试流程是否正常执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:32:05