from __future__ import annotations """ Pytest 全局配置: - 在测试启动时自动加载项目根目录下的 .env 文件,把其中的变量注入到 os.environ。 - 这样可以在不手动 export 的情况下,将 H3C_NETCONF_* 等变量提供给 live 测试与 HTTP E2E。 """ import os from pathlib import Path def _load_dotenv_from_project_root() -> None: root = Path(__file__).resolve().parents[1] env_file = root / ".env" if not env_file.exists(): return try: content = env_file.read_text(encoding="utf-8") except OSError: return for line in content.splitlines(): line = line.strip() if not line or line.startswith("#"): continue if "=" not in line: continue key, value = line.split("=", 1) key = key.strip() value = value.strip() # 去掉首尾成对的引号(支持单引号或双引号) if (value.startswith("'") and value.endswith("'")) or ( value.startswith('"') and value.endswith('"') ): value = value[1:-1] # 已存在的环境变量优先生效,.env 只作为默认值 os.environ.setdefault(key, value) _load_dotenv_from_project_root()