如何在pytest-parallel中获取类似pytest-xdist的worker_id及进程ID?
解决pytest-parallel中获取进程ID及session级fixture缓存问题
1. 获取进程ID的方法
pytest-parallel未提供worker_id这类专属fixture,可直接通过Python标准库os模块获取当前进程ID:
import os current_pid = os.getpid()
2. 适配pytest-parallel的session级WebDriver缓存fixture
针对pytest-parallel会忽略session作用域的问题,可通过文件锁+共享临时文件实现驱动缓存,同时用进程ID替代worker_id做进程标识:
import os import json from filelock import FileLock import pytest from your_module import SeleniumConfig, install_driver @pytest.fixture(scope='session') def driver_path_lock(selenium_config: SeleniumConfig, tmp_path_factory) -> str: """ 下载WebDriver并在session级别缓存,适配pytest-parallel """ current_pid = os.getpid() # 获取所有并行进程共享的临时目录父级 root_tmp_dir = tmp_path_factory.getbasetemp().parent fn = root_tmp_dir / "driver_cache.json" lock_fn = root_tmp_dir / "driver_cache.lock" with FileLock(str(lock_fn)): if fn.is_file(): data = json.loads(fn.read_text()) print(f"进程 {current_pid} 读取缓存的驱动路径") else: data = install_driver(selenium_config) fn.write_text(json.dumps(data)) print(f"进程 {current_pid} 首次安装驱动并写入缓存") return data
3. 关键说明
- 用
os.getpid()替代worker_id标识当前进程,无需依赖pytest-xdist专属fixture - 通过
tmp_path_factory.getbasetemp().parent获取所有并行进程共享的临时目录,确保缓存文件可跨进程访问 - 借助
FileLock保证多进程下仅一个进程执行驱动安装逻辑,避免重复下载浪费资源
内容的提问来源于stack exchange,提问作者sutkyne
相关产品推荐
相关产品推荐

