|
| 1 | +import os |
| 2 | +from typing import Any |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from app.core import upstream as upstream_module |
| 7 | +from app.core.upstream import UpstreamClient, _extract_user_id_from_token |
| 8 | + |
| 9 | +REAL_AUTH_TOKEN_ENV = "REAL_AUTH_TOKEN_ENV" |
| 10 | +RED_2X2_PNG_DATA_URL = ( |
| 11 | + "data:image/png;base64," |
| 12 | + "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR42mP4z8AARAwQCgAf7gP9Y167WwAAAABJRU5ErkJggg==" |
| 13 | +) |
| 14 | + |
| 15 | +def install_real_auth(monkeypatch) -> str: |
| 16 | + token = os.getenv(REAL_AUTH_TOKEN_ENV, "").strip() |
| 17 | + if not token: |
| 18 | + pytest.skip(f"需要设置环境变量 {REAL_AUTH_TOKEN_ENV}") |
| 19 | + |
| 20 | + user_id = _extract_user_id_from_token(token) |
| 21 | + if not user_id or user_id == "guest": |
| 22 | + raise AssertionError(f"{REAL_AUTH_TOKEN_ENV} 不是可解析的认证 token") |
| 23 | + |
| 24 | + async def fake_get_auth_info( |
| 25 | + self, |
| 26 | + excluded_tokens=None, |
| 27 | + excluded_guest_user_ids=None, |
| 28 | + ): |
| 29 | + return { |
| 30 | + "token": token, |
| 31 | + "user_id": user_id, |
| 32 | + "username": "RealUser", |
| 33 | + "auth_mode": "authenticated", |
| 34 | + "token_source": "env", |
| 35 | + "guest_user_id": None, |
| 36 | + } |
| 37 | + |
| 38 | + monkeypatch.setattr(UpstreamClient, "get_auth_info", fake_get_auth_info) |
| 39 | + monkeypatch.setattr(upstream_module, "get_token_pool", lambda: None) |
| 40 | + monkeypatch.setattr(upstream_module, "get_guest_session_pool", lambda: None) |
| 41 | + return token |
| 42 | + |
| 43 | + |
| 44 | +def install_real_anonymous(monkeypatch) -> None: |
| 45 | + monkeypatch.setattr(upstream_module, "get_token_pool", lambda: None) |
| 46 | + monkeypatch.setattr(upstream_module, "get_guest_session_pool", lambda: None) |
| 47 | + monkeypatch.setattr(upstream_module.settings, "ANONYMOUS_MODE", True) |
| 48 | + |
| 49 | + |
| 50 | +def extract_content(payload: dict[str, Any]) -> str: |
| 51 | + assert isinstance(payload, dict), payload |
| 52 | + assert "error" not in payload, payload |
| 53 | + |
| 54 | + choices = payload.get("choices") or [] |
| 55 | + assert choices, payload |
| 56 | + |
| 57 | + message = choices[0].get("message") or {} |
| 58 | + content = str(message.get("content") or "").strip() |
| 59 | + assert content, payload |
| 60 | + return content |
| 61 | + |
| 62 | + |
| 63 | +def assert_usage_present(payload: dict[str, Any]) -> None: |
| 64 | + usage = payload.get("usage") or {} |
| 65 | + assert int(usage.get("total_tokens") or 0) > 0, payload |
0 commit comments