Files
speaking-practice/tests/ai_routes_test.py
T

103 lines
3.4 KiB
Python

import sys
from pathlib import Path
from fastapi import HTTPException
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import ai_config, main
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_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_local_whisper_route_generates_only_english_subtitle(patch)
finally:
patch.restore()
ai_config.read_env_file = original_read_env_file