import sys import tempfile from pathlib import Path from fastapi import HTTPException from fastapi.security import HTTPBasicCredentials sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from backend import ai_config, main from backend.ai_config import DeepSeekConfig from backend.deepseek_client import DeepSeekError class EnvPatch: def __init__(self): self.originals = {} self.attributes = [] def delenv(self, key, raising=True): import os self.originals.setdefault(key, os.environ.get(key)) if key in os.environ: del os.environ[key] elif raising: raise KeyError(key) def restore(self): import os for key, value in self.originals.items(): if value is None: os.environ.pop(key, None) else: os.environ[key] = value while self.attributes: target, name, original = self.attributes.pop() setattr(target, name, original) def setattr(self, target, name, value): self.attributes.append((target, name, getattr(target, name))) setattr(target, name, value) def test_ai_status_route_reports_missing_key(monkeypatch): monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False) status = main.api_ai_status() assert status["configured"] is False assert "TEXT_AI_API_KEY" in status["message"] def test_ai_test_route_rejects_missing_key(monkeypatch): monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False) try: main.api_ai_test() except HTTPException as error: assert error.status_code == 400 assert "TEXT_AI_API_KEY" in error.detail else: raise AssertionError("api_ai_test should reject missing DeepSeek API key") def test_admin_credentials_require_matching_env_values(monkeypatch): monkeypatch.setattr(main, "get_config_value", lambda key, default="": { "ADMIN_USERNAME": "owner", "ADMIN_PASSWORD": "secret", }.get(key, default)) result = main.require_admin(HTTPBasicCredentials(username="owner", password="secret")) assert result["username"] == "owner" def test_admin_credentials_reject_wrong_password(monkeypatch): monkeypatch.setattr(main, "get_config_value", lambda key, default="": { "ADMIN_USERNAME": "owner", "ADMIN_PASSWORD": "secret", }.get(key, default)) try: main.require_admin(HTTPBasicCredentials(username="owner", password="wrong")) except HTTPException as error: assert error.status_code == 401 else: raise AssertionError("wrong admin password should be rejected") def test_admin_credentials_reject_missing_config(monkeypatch): monkeypatch.setattr(main, "get_config_value", lambda key, default="": "") try: main.require_admin(HTTPBasicCredentials(username="owner", password="secret")) except HTTPException as error: assert error.status_code == 503 assert "ADMIN_USERNAME" in error.detail else: raise AssertionError("missing admin config should be rejected") def make_text_config() -> DeepSeekConfig: return DeepSeekConfig( api_key="test-key", base_url="https://api.example.com", model="demo-model", audio_model="demo-audio-model", provider="demo", protocol="openai", translation_batch_size=40, timeout_seconds=120, ) def test_ai_test_route_calls_model_client(monkeypatch): calls = [] class FakeClient: def __init__(self, config, timeout_seconds): calls.append(("init", config.model, timeout_seconds)) def chat_json(self, system_prompt, user_payload): calls.append(("chat_json", system_prompt, user_payload)) return {"ok": True} monkeypatch.setattr(main, "get_ai_status", lambda: {"configured": True}) monkeypatch.setattr(main, "load_text_ai_config", make_text_config) monkeypatch.setattr(main, "DeepSeekClient", FakeClient) result = main.api_ai_test() assert result["ok"] is True assert calls[0] == ("init", "demo-model", 120) assert calls[1][0] == "chat_json" assert calls[1][2]["task"] == "ping" def test_ai_test_route_reports_model_client_failure(monkeypatch): class FakeClient: def __init__(self, config, timeout_seconds): pass def chat_json(self, system_prompt, user_payload): raise DeepSeekError("bad key") monkeypatch.setattr(main, "get_ai_status", lambda: {"configured": True}) monkeypatch.setattr(main, "load_text_ai_config", make_text_config) monkeypatch.setattr(main, "DeepSeekClient", FakeClient) try: main.api_ai_test() except HTTPException as error: assert error.status_code == 400 assert "bad key" in error.detail else: raise AssertionError("api_ai_test should report model client failures") def test_ai_subtitle_route_writes_processed_vtt_files(monkeypatch): calls = [] with tempfile.TemporaryDirectory() as temp_dir: uploads_dir = Path(temp_dir) / "uploads" monkeypatch.setattr(main, "UPLOADS_DIR", uploads_dir) monkeypatch.setattr(main, "get_ai_status", lambda: {"configured": True}) monkeypatch.setattr(main, "load_text_ai_config", make_text_config) monkeypatch.setattr(main, "DeepSeekClient", lambda config, timeout_seconds: object()) monkeypatch.setattr( main, "get_video", lambda video_id: { "id": video_id, "subtitles": { "en": { "content": "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nHello.", "filePath": "/uploads/subtitles/original.vtt", } }, }, ) monkeypatch.setattr( main, "process_subtitles_with_ai", lambda content, client, batch_size: { "subtitle_en_content": "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nHello.\n", "subtitle_zh_content": "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\n你好。\n", "report": {"duplicate_count": 0, "empty_count": 0, "translation_count": 1}, }, ) def fake_upsert_video_subtitle(video_id, **kwargs): calls.append({"video_id": video_id, **kwargs}) monkeypatch.setattr(main, "upsert_video_subtitle", fake_upsert_video_subtitle) result = main.api_process_video_subtitles(9) assert result["report"]["translation_count"] == 1 assert len(calls) == 2 assert calls[0]["language_code"] == "en" assert calls[1]["language_code"] == "zh" assert calls[0]["file_path"].startswith("/uploads/subtitles/") assert calls[0]["file_path"].endswith(".ai.en.vtt") assert calls[1]["file_path"].endswith(".ai.zh.vtt") assert (uploads_dir / calls[0]["file_path"].removeprefix("/uploads/")).read_text(encoding="utf-8").startswith("WEBVTT") assert "你好" in (uploads_dir / calls[1]["file_path"].removeprefix("/uploads/")).read_text(encoding="utf-8") def test_local_whisper_route_generates_only_english_subtitle(monkeypatch): calls = [] monkeypatch.setattr(main, "get_video", lambda video_id: {"id": video_id, "videoUrl": "/uploads/videos/demo.mp4", "subtitles": {}}) monkeypatch.setattr(main, "upload_url_to_path", lambda value: Path("uploads/videos/demo.mp4")) monkeypatch.setattr(main, "load_local_whisper_config", lambda: object()) monkeypatch.setattr(main, "transcribe_video_to_vtt", lambda video_path, config: "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nHello.\n") def fake_process_subtitles_with_ai(*args, **kwargs): raise AssertionError("local whisper route should not call AI translation") def fake_upsert_video_subtitle(video_id, **kwargs): calls.append({"video_id": video_id, **kwargs}) monkeypatch.setattr(main, "process_subtitles_with_ai", fake_process_subtitles_with_ai) monkeypatch.setattr(main, "upsert_video_subtitle", fake_upsert_video_subtitle) result = main.api_generate_local_whisper_subtitles(7) assert result["report"]["local_whisper_generated"] is True assert result["report"]["english_count"] == 1 assert len(calls) == 1 assert calls[0]["video_id"] == 7 assert calls[0]["language_code"] == "en" assert "subtitle_zh_content" not in calls[0] if __name__ == "__main__": patch = EnvPatch() original_read_env_file = ai_config.read_env_file ai_config.read_env_file = lambda path=ai_config.ENV_PATH: {} try: test_ai_status_route_reports_missing_key(patch) patch.restore() test_ai_test_route_rejects_missing_key(patch) patch.restore() test_admin_credentials_require_matching_env_values(patch) patch.restore() test_admin_credentials_reject_wrong_password(patch) patch.restore() test_admin_credentials_reject_missing_config(patch) patch.restore() test_ai_test_route_calls_model_client(patch) patch.restore() test_ai_test_route_reports_model_client_failure(patch) patch.restore() test_ai_subtitle_route_writes_processed_vtt_files(patch) patch.restore() test_local_whisper_route_generates_only_english_subtitle(patch) finally: patch.restore() ai_config.read_env_file = original_read_env_file