Skip to content

Commit 887c087

Browse files
committed
test(unittests): Add an automatic fixture for test environment variable isolation
- Added an `autouse` fixture to automatically clean up environment variables related to the SDK configuration. - Prevents local `.env` files from interfering with the environment variable settings used in unit tests. - Cleans up specific environment variables to prevent assertion failures within `respx` mocks. - Ensures environment variable isolation between test cases, thereby enhancing test stability. - Cleans up only those environment variables that the SDK reads by default, without affecting user-defined variables. Signed-off-by: 寒光 <2510399607@qq.com>
1 parent 1f291b5 commit 887c087

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

tests/unittests/conftest.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""Unit test fixtures / 单元测试公共 fixture.
2+
3+
本模块统一为 tests/unittests/ 目录提供测试隔离保障。
4+
5+
Why:
6+
agentrun.utils.config 在模块导入时调用 load_dotenv(), 会把仓库根目录
7+
的 .env 注入到 os.environ。Config() 在构造时会用 get_env_with_default
8+
读取这些环境变量作为默认值, 导致:
9+
- respx mock 的 URL 是基于 SDK 默认 account_id / region 构造,
10+
而实际请求打到开发者本地 .env 里的真实 account / region,
11+
触发 "AllMockedAssertionError: ... not mocked!"
12+
- 硬编码期望默认 account_id / region 的断言直接 AssertionError
13+
14+
How:
15+
autouse fixture 在每个 test 进入前, 通过 monkeypatch.delenv 清理
16+
Config.__init__ 读取的那一组 env。monkeypatch 会在 test 结束时
17+
自动恢复原值, 不影响仓库 .env 文件本身, 也不影响显式使用
18+
patch.dict(os.environ, ...) 设置 test 用凭据的测试 (patch.dict
19+
会覆盖 delenv 的结果)。
20+
"""
21+
22+
from typing import List
23+
24+
import pytest
25+
26+
# Config.__init__ 默认值会读取的环境变量白名单
27+
# 仅清理这些 key, 不动用户测试自己 set 的其他 AGENTRUN_* 变量
28+
# (例如 memory_collection test 里的 AGENTRUN_MYSQL_PUBLIC_HOST)
29+
_SDK_CONFIG_ENV_KEYS: List[str] = [
30+
# 凭据类 / Credentials
31+
"AGENTRUN_ACCESS_KEY_ID",
32+
"ALIBABA_CLOUD_ACCESS_KEY_ID",
33+
"AGENTRUN_ACCESS_KEY_SECRET",
34+
"ALIBABA_CLOUD_ACCESS_KEY_SECRET",
35+
"AGENTRUN_SECURITY_TOKEN",
36+
"ALIBABA_CLOUD_SECURITY_TOKEN",
37+
# 账号与区域 / Account & Region
38+
"AGENTRUN_ACCOUNT_ID",
39+
"FC_ACCOUNT_ID",
40+
"AGENTRUN_REGION",
41+
"FC_REGION",
42+
# Endpoint 类 / Endpoints
43+
"AGENTRUN_CONTROL_ENDPOINT",
44+
"AGENTRUN_DATA_ENDPOINT",
45+
"DEVS_ENDPOINT",
46+
"BAILIAN_ENDPOINT",
47+
]
48+
49+
50+
@pytest.fixture(autouse=True)
51+
def _isolate_sdk_config_env(monkeypatch: pytest.MonkeyPatch) -> None:
52+
"""自动为每个 unit test 清理 SDK Config 相关 env, 避免被本地 .env 污染."""
53+
for key in _SDK_CONFIG_ENV_KEYS:
54+
monkeypatch.delenv(key, raising=False)

0 commit comments

Comments
 (0)