问题描述:

直接运行测试用例时能正常运行,通过主入口(main.py)运行测试用例时找不到ChromeDriver报“Unable to obtain ..\driver\chromedriver.exe using Selenium Manager”。

报错原因:

Python 中所有相对路径的解析,都是以程序运行时的 CWD(当前工作目录)为基准,而非“测试用例文件” 或 “主入口文件” 本身。

运行方式

相对路径基准(CWD)

相对路径解析结果

直接运行测试用例(test_login.py)

测试用例所在目录(G:\test\testcase\)

../driver/ → G:\test\driver\

通过主入口(main.py)运行测试用例

主入口所在目录(G:\test\)

../driver/ → G:\driver\(错误)

解决方法:获取ChromeDriver绝对路径

# test_login.py 中的 setUp 方法
import os
import unittest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from page.login_page import Login_Page

class Test_Login(unittest.TestCase):
   def setUp(self):
       # 1. 获取当前测试用例文件(test_login.py)的绝对路径
       current_file_path = os.path.abspath(__file__)  # G:\test\testcase\test_login.py
       # 2. 获取测试用例所在目录
       current_dir = os.path.dirname(current_file_path)  # G:\test\testcase\
       # 3. 向上跳一级(到项目根目录),再找 driver 文件夹
       project_root = os.path.dirname(current_dir)  # G:\test\
       driver_path = os.path.join(project_root, "driver", "chromedriver.exe")
       # 4. 初始化 driver
       service = Service(executable_path=driver_path)
       options = webdriver.ChromeOptions()
       self.driver = webdriver.Chrome(service=service,options=options)

核心函数说明:

__file__:当前代码文件(test_login.py)的路径(可能是相对 / 绝对,取决于运行方式);

os.path.abspath(__file__):转为绝对路径,消除歧义;

os.path.dirname():获取文件 / 目录的上级目录;

os.path.join():拼接路径。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐