GitLab CI中Robot Framework测试遇SessionNotCreatedException问题
解决GitLab CI中Robot Framework Selenium的SessionNotCreatedException错误
问题根源
GitLab CI容器环境中,Chrome浏览器的用户数据目录出现占用冲突。尽管测试代码生成了随机目录,但CI环境的进程残留、权限特性,加上冗余的CI配置操作,共同导致了目录占用问题;而本地环境无此类容器隔离限制,因此测试正常运行。
解决方案
1. 移除自定义用户数据目录(推荐方案)
若测试无需复用浏览器会话或配置,直接省略--user-data-dir参数,Chrome会自动生成独立临时目录,从根源避免冲突。同时添加CI必需的无头启动参数:
*** Keywords *** Begin Test ${options}= Create List --no-sandbox --disable-dev-shm-usage --headless=new Set selenium speed .2s Set selenium timeout 10s Open Browser about:blank ${BROWSER} chrome_options=${options} Maximize Browser Window
2. 保留自定义目录时,确保唯一性与强制清理
若必须使用自定义用户数据目录,需在测试结束后强制删除目录,避免残留占用:
- 先导入
OperatingSystem库到测试文件:
*** Settings *** Library SeleniumLibrary Library String Library OperatingSystem
- 修改关键字,添加目录清理逻辑:
*** Keywords *** Begin Test ${random_string} Generate Random String 8 [LETTERS] ${profile_dir}= Set Variable /tmp/selenium-profile-${random_string} ${options}= Create List --user-data-dir=${profile_dir} --no-sandbox --disable-dev-shm-usage --headless=new Set selenium speed .2s Set selenium timeout 10s Open Browser about:blank ${BROWSER} chrome_options=${options} Maximize Browser Window Set Suite Variable ${profile_dir} # 传递目录路径到清理步骤 End Test Sleep 2s Close All Browsers Remove Directory ${profile_dir} recursive=True # 强制删除目录
3. 清理GitLab CI配置中的冗余操作
删除gitlab-ci.yml中未使用的环境变量、无效目录创建操作,并确保Chrome与Chromedriver版本严格匹配:
stages: - test robot_tests: stage: test image: python:3.13 before_script: - apt-get install -y wget gnupg unzip curl # 安装与Chromedriver同版本的Chrome,避免版本不匹配 - wget -O /tmp/chrome.zip https://storage.googleapis.com/chrome-for-testing-public/124.0.6367.60/linux64/chrome-linux64.zip - unzip /tmp/chrome.zip -d /usr/local/bin/ - ln -s /usr/local/bin/chrome-linux64/chrome /usr/local/bin/google-chrome - wget -O /tmp/chromedriver.zip https://storage.googleapis.com/chrome-for-testing-public/124.0.6367.60/linux64/chromedriver-linux64.zip - unzip /tmp/chromedriver.zip -d /usr/local/bin/ - chmod +x /usr/local/bin/chromedriver-linux64/chromedriver - rm /tmp/chrome.zip /tmp/chromedriver.zip - pip3 install -r requirements.txt - rm -rf /root/.cache/selenium script: - mkdir -p reports - robot -d reports Tests - pkill -f chrome || true # 强制清理残留Chrome进程 artifacts: when: always paths: - reports/ expire_in: 7 days
内容的提问来源于stack exchange,提问作者sabrine tounsi
相关产品推荐
相关产品推荐

