test_deepinfra.py
Language Python3.3 KB87 lines
"""The DeepInfra engine against a local stand-in server: request shape, errors, normalization."""import jsonimport threadingfrom http.server import BaseHTTPRequestHandler, HTTPServerimport pytestfrom transcription_pipeline.engines import deepinfraclass Stub:status = 200body = {}seen = {}class Handler(BaseHTTPRequestHandler):def do_POST(self):n = int(self.headers["Content-Length"])Stub.seen = {"auth": self.headers["Authorization"], "ctype": self.headers["Content-Type"],"body": self.rfile.read(n), "path": self.path}payload = json.dumps(Stub.body).encode()self.send_response(Stub.status)self.send_header("Content-Type", "application/json")self.send_header("Content-Length", str(len(payload)))self.end_headers()self.wfile.write(payload)def log_message(self, *a):pass@pytest.fixturedef server():srv = HTTPServer(("127.0.0.1", 0), Handler)threading.Thread(target=srv.serve_forever, daemon=True).start()yield f"http://127.0.0.1:{srv.server_address[1]}/v1/inference/openai/whisper-large-v3-turbo"srv.shutdown()@pytest.fixturedef clip(tmp_path):p = tmp_path / "call.flac"p.write_bytes(b"fLaC-not-really")return pdef test_request_shape_and_segments(server, clip):Stub.status, Stub.body = 200, {"text": " Hi there. Bye.", "language": "en", "segments": [{"start": 0.0, "end": 1.2, "text": " Hi there."}, {"start": 1.2, "end": 2.0, "text": " "},{"start": 2.0, "end": 2.6, "text": " Bye."}]}out = deepinfra.transcribe(clip, "tok-123", language="en", api_url=server)assert Stub.seen["auth"] == "bearer tok-123"assert Stub.seen["ctype"].startswith("multipart/form-data; boundary=")body = Stub.seen["body"]assert b'name="audio"; filename="call.flac"' in body and b"fLaC-not-really" in bodyassert b'name="language"\r\n\r\nen\r\n' in bodyassert out["segments"] == [{"start": 0.0, "end": 1.2, "text": "Hi there."},{"start": 2.0, "end": 2.6, "text": "Bye."}]assert out["language"] == "en" and "DeepInfra" in out["model"]def test_text_only_response_becomes_one_segment(server, clip):Stub.status, Stub.body = 200, {"text": "Just text.", "segments": None}out = deepinfra.transcribe(clip, "t", api_url=server)assert out["segments"] == [{"start": 0.0, "end": 0.0, "text": "Just text."}]assert b'name="language"' not in Stub.seen["body"]@pytest.mark.parametrize("code,needle", [(401, "rejected the token"), (403, "rejected the token"),(429, "out of credit"), (413, "too large"),(500, "DeepInfra error 500")])def test_error_mapping(server, clip, code, needle):Stub.status, Stub.body = code, {"detail": "nope"}with pytest.raises(deepinfra.EngineError, match=needle):deepinfra.transcribe(clip, "t", api_url=server)def test_missing_token(clip):with pytest.raises(deepinfra.EngineError, match="No DeepInfra token"):deepinfra.transcribe(clip, None)def test_unreachable(clip):with pytest.raises(deepinfra.EngineError, match="Could not reach"):deepinfra.transcribe(clip, "t", api_url="http://127.0.0.1:9/x", timeout=2)