97 lines
2.8 KiB
Python
97 lines
2.8 KiB
Python
"""配置加载模块测试."""
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
from src.core.config import AppConfig, EmbedConfig, load_config
|
|
|
|
|
|
class TestEmbedConfig:
|
|
"""嵌入配置解析."""
|
|
|
|
def test_local_mode_defaults(self):
|
|
"""默认 local 模式,带默认模型名."""
|
|
data = {"embed": {"mode": "local"}}
|
|
cfg = AppConfig.from_dict(data)
|
|
assert cfg.embed.mode == "local"
|
|
assert cfg.embed.local_model == "BAAI/bge-small-zh-v1.5"
|
|
assert cfg.embed.api_base == ""
|
|
|
|
def test_api_mode_fields(self):
|
|
"""api 模式下 api_base 和 api_key 可设置."""
|
|
data = {
|
|
"embed": {
|
|
"mode": "api",
|
|
"api_base": "https://api.openai.com/v1",
|
|
"api_key": "sk-test",
|
|
}
|
|
}
|
|
cfg = AppConfig.from_dict(data)
|
|
assert cfg.embed.mode == "api"
|
|
assert cfg.embed.api_base == "https://api.openai.com/v1"
|
|
assert cfg.embed.api_key == "sk-test"
|
|
|
|
|
|
class TestChunkConfig:
|
|
"""分块配置解析."""
|
|
|
|
def test_default_values(self):
|
|
"""分块默认值正确."""
|
|
data = {"chunk": {}}
|
|
cfg = AppConfig.from_dict(data)
|
|
assert cfg.chunk.max_size == 1000
|
|
assert cfg.chunk.overlap == 100
|
|
|
|
|
|
class TestLoadConfig:
|
|
"""load_config 函数测试."""
|
|
|
|
def test_load_from_yaml_file(self):
|
|
"""从 YAML 文件加载配置."""
|
|
yaml_content = """
|
|
chroma:
|
|
persist_dir: /tmp/test_data
|
|
collection_name: test_collection
|
|
embed:
|
|
mode: local
|
|
chunk:
|
|
max_size: 500
|
|
server:
|
|
port: 9000
|
|
"""
|
|
with tempfile.NamedTemporaryFile(
|
|
mode="w", suffix=".yaml", delete=False
|
|
) as f:
|
|
f.write(yaml_content)
|
|
tmp_path = f.name
|
|
|
|
try:
|
|
cfg = load_config(tmp_path)
|
|
assert cfg.chroma.persist_dir == "/tmp/test_data"
|
|
assert cfg.chroma.collection_name == "test_collection"
|
|
assert cfg.chunk.max_size == 500
|
|
assert cfg.server.port == 9000
|
|
finally:
|
|
Path(tmp_path).unlink()
|
|
|
|
def test_load_missing_file_uses_defaults(self):
|
|
"""配置文件不存在时使用默认值."""
|
|
cfg = load_config("/nonexistent/config.yaml")
|
|
assert cfg.chroma.persist_dir == "./data"
|
|
assert cfg.embed.mode == "local"
|
|
|
|
|
|
class TestEmbedConfigEnvVar:
|
|
"""api_key 从环境变量读取."""
|
|
|
|
def test_api_key_from_env(self, monkeypatch):
|
|
"""从环境变量读取 API Key."""
|
|
monkeypatch.setenv("EMBED_API_KEY", "sk-env-test")
|
|
cfg = EmbedConfig(mode="api")
|
|
assert cfg.api_key == "sk-env-test"
|
|
|
|
def test_api_key_empty_when_not_set(self, monkeypatch):
|
|
"""未设置时返回空字符串."""
|
|
monkeypatch.delenv("EMBED_API_KEY", raising=False)
|
|
cfg = EmbedConfig(mode="api")
|
|
assert cfg.api_key == ""
|