关于fakefs中add_real_file通用访问真实文件的技术问询
解决fakefs中通用加载真实配置文件的方案
给你几个通用的解决思路,不用硬写专属绝对路径:
利用测试脚本的真实路径拼接
fakefs不会干扰__file__变量的取值,这个变量能拿到当前测试脚本的真实绝对路径。只要项目结构统一,不管谁运行测试都能通过它拼接出正确的配置文件路径:import os # 获取当前测试脚本所在的真实目录 test_script_dir = os.path.dirname(os.path.abspath(__file__)) # 根据项目实际结构调整相对路径,这里假设配置在项目根目录的logs文件夹下 real_config_path = os.path.join(test_script_dir, "../logs/config.cfg") # 将真实文件加入fakefs环境 fs.add_real_file( real_config_path, target_path="/logs/config.cfg" )用环境变量指定路径
让不同用户自行通过环境变量配置真实配置文件的路径,测试脚本读取这个变量即可,灵活度拉满:import os # 从环境变量获取真实配置文件路径 real_config_path = os.environ.get("TEST_CONFIG_FILE") if not real_config_path: raise ValueError("请先设置TEST_CONFIG_FILE环境变量,指向真实的config.cfg文件") fs.add_real_file( real_config_path, target_path="/logs/config.cfg" )运行测试前,Linux/macOS用户可以执行:
export TEST_CONFIG_FILE="/home/xxx/development/logs/config.cfg";Windows用户执行:set TEST_CONFIG_FILE="C:\xxx\development\logs\config.cfg"。通过项目根目录标记自动定位
如果项目里有固定的根目录标识(比如.git文件夹、pyproject.toml或requirements.txt),可以写个小函数向上遍历找到根目录,再拼接配置路径,完全不用用户手动设置:import os def find_project_root(): current_dir = os.path.dirname(os.path.abspath(__file__)) while True: # 这里用.git作为根目录标记,可替换为你项目里的固定文件/文件夹 if os.path.exists(os.path.join(current_dir, ".git")): return current_dir parent_dir = os.path.dirname(current_dir) # 遍历到系统根目录还没找到就报错 if parent_dir == current_dir: raise FileNotFoundError("找不到项目根目录,未检测到.git标记") current_dir = parent_dir project_root = find_project_root() real_config_path = os.path.join(project_root, "logs/config.cfg") fs.add_real_file( real_config_path, target_path="/logs/config.cfg" )
内容的提问来源于stack exchange,提问作者MaKaNu
相关产品推荐
相关产品推荐

