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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 15 views 0 copies

Python code

36 lines
Python 3.9+
import 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

stdout
{
  "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

  1. Use `unittest.mock.patch` to swap the real API client with the mock function in test code.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.