How to Mock a Whisper API Transcription Stub in Python
Simulate an OpenAI Whisper-style transcription response with a dataclass request model and a mock function that returns structured audio transcription output.
Python code
36 linesimport json
from dataclasses import dataclass
from typing import Optional
@dataclass
class AudioRequest:
file_path: str
language: Optional[str] = None
def to_api_payload(self) -> dict:
return {"file": self.file_path, "language": self.language}
def mock_whisper_transcribe(payload: dict) -> dict:
# Simulates OpenAI Whisper API response structure
transcriptions = {
"meeting_notes.wav": "The project deadline has been moved to Friday.",
"podcast_ep1.mp3": "Welcome back to the show, today we discuss Python.",
"default": "This is a mock transcription of the audio file."
}
filename = payload.get("file", "default")
text = transcriptions.get(filename, transcriptions["default"])
return {
"text": text,
"language": payload.get("language") or "en",
"duration": 12.5,
"status": "completed"
}
if __name__ == "__main__":
req = AudioRequest(file_path="meeting_notes.wav", language="en")
api_payload = req.to_api_payload()
result = mock_whisper_transcribe(api_payload)
print(json.dumps({
"request": api_payload,
"transcription": result
}, indent=2))
Output
{
"request": {
"file": "meeting_notes.wav",
"language": "en"
},
"transcription": {
"text": "The project deadline has been moved to Friday.",
"language": "en",
"duration": 12.5,
"status": "completed"
}
}
How it works
The AudioRequest dataclass encapsulates an audio file path and optional language, with a to_api_payload method that shapes the data into the same JSON structure the real Whisper endpoint expects. The mock_whisper_transcribe function mimics the response contract of the Whisper API: it returns a dict containing the transcribed text, detected or defaulted language, a simulated duration in seconds, and a status field. The mock looks up the transcription by filename and falls back to a generic "default" string when the file is unknown, which keeps the stub stable for testing. This pattern is useful in CI pipelines or local development when you want deterministic behavior without hitting the paid API.
Common mistakes
- Forgetting to fall back to a default transcription when the filename is not in the mock dict, causing KeyError.
- Hardcoding the duration instead of varying it per file, which can mask real timing logic in tests.
- Not including a status field, which breaks consumers that expect the completed state.
- Returning a plain string instead of the structured dict that mirrors the real API response.
Variations
- Use `unittest.mock.patch` to swap the real API client with the mock function in test code.
- Load transcriptions from a JSON file instead of a hardcoded dict for easier maintenance.
Real-world use cases
- Running unit tests for an audio processing pipeline without incurring API costs.
- Developing and debugging a frontend or CLI tool that consumes transcription results, before wiring the real model.
- Simulating slow or flaky external service behavior in integration test suites to verify retry logic.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.