astrbot_plugin_imagestudio/tests/test_probe_session_api_key.py

95 行
2.9 KiB
Python

from __future__ import annotations
from pathlib import Path
import pytest
from backend.services.api_discovery_service import _saved_provider_probe_payload
SETTINGS_PAGE = (
Path(__file__).resolve().parents[1]
/ "frontend"
/ "standalone-web"
/ "src"
/ "features"
/ "settings"
/ "SettingsPage.vue"
)
SAVED_CONFIG = {
"generation": {
"adapters": [
{
"id": "adapter-1",
"base_url": "https://api.example.com",
"model_id": "img-1",
"api_key_plaintext": "sk-stored",
}
]
}
}
@pytest.fixture()
def saved_config(monkeypatch: pytest.MonkeyPatch):
import backend.services.api_discovery_service as module
monkeypatch.setattr(module, "load_config_payload", lambda: SAVED_CONFIG)
def test_session_key_overrides_the_stored_one(saved_config) -> None:
"""The probe must authenticate with a session key that is never persisted."""
resolved = _saved_provider_probe_payload(
{"provider_id": "adapter-1", "api_key_plaintext": "sk-session"}
)
assert resolved["api_key_plaintext"] == "sk-session"
def test_stored_key_is_used_when_no_session_key_is_supplied(saved_config) -> None:
resolved = _saved_provider_probe_payload({"provider_id": "adapter-1"})
assert resolved["api_key_plaintext"] == "sk-stored"
def test_blank_session_key_does_not_clobber_the_stored_one(saved_config) -> None:
resolved = _saved_provider_probe_payload(
{"provider_id": "adapter-1", "api_key_plaintext": " "}
)
assert resolved["api_key_plaintext"] == "sk-stored"
def test_settings_page_does_not_persist_the_probe_key() -> None:
"""The UI promises 「仅本次页面会话使用…不写入配置或日志」 — keep it true.
``saveAndProbeAdapter`` used to splice the probe key into
``generation.adapters[].api_key_plaintext`` and POST that to
``settings/save``, writing the credential into config.yaml.
"""
source = SETTINGS_PAGE.read_text(encoding="utf-8")
start = source.index("async function saveAndProbeAdapter(")
end = source.index("function probeModelsFromResult(", start)
body = source[start:end]
save_call = body.index("endpoints.settingsSave")
before_save = body[:save_call]
assert "api_key_plaintext" not in before_save, (
"the probe key must not be written into the config that gets saved"
)
# It must still reach the probe endpoint, otherwise the field is useless.
assert "api_key_plaintext" in body[save_call:], (
"the probe key must be passed to the probe request"
)
def test_settings_page_still_advertises_session_only_semantics() -> None:
"""If this promise is ever removed, the test above stops being meaningful."""
source = SETTINGS_PAGE.read_text(encoding="utf-8")
assert "仅本次页面会话使用" in source
assert "不写入配置或日志" in source