import json import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from backend.ai_config import AsrConfig from backend.openai_asr_client import OpenAIAsrClient class FakeResponse: def __enter__(self): return self def __exit__(self, exc_type, exc, tb): return False def read(self): return json.dumps({ "text": "hello world", "segments": [ {"start": 1.25, "end": 2.5, "text": "hello world"} ], }).encode("utf-8") def test_openai_asr_client_posts_transcription_request(monkeypatch, tmp_path=None): audio_path = Path("tests") / "tmp-first10.wav" audio_path.write_bytes(b"fake wav") captured = {} def fake_urlopen(request, timeout): captured["url"] = request.full_url captured["headers"] = dict(request.header_items()) captured["body_prefix"] = request.data[:120] return FakeResponse() try: monkeypatch.setattr("backend.openai_asr_client.urllib.request.urlopen", fake_urlopen) client = OpenAIAsrClient(AsrConfig( provider="openai", api_key="openai-key", base_url="https://api.openai.com", model="whisper-1", timeout_seconds=120, enabled=True, )) result = client.transcribe(audio_path) assert captured["url"] == "https://api.openai.com/v1/audio/transcriptions" assert "authorization" in {key.lower(): value for key, value in captured["headers"].items()} assert b"whisper-1" in captured["body_prefix"] or b"model" in captured["body_prefix"] assert result["segments"][0]["start"] == 1.25 finally: audio_path.unlink(missing_ok=True) if __name__ == "__main__": class MonkeyPatch: def setattr(self, target, value): parts = target.split(".") module = __import__(".".join(parts[:2]), fromlist=[parts[1]]) current = module for part in parts[2:-1]: current = getattr(current, part) setattr(current, parts[-1], value) test_openai_asr_client_posts_transcription_request(MonkeyPatch())