Skip to content

Commit

Permalink
[test] Refine RESPX mock
Browse files Browse the repository at this point in the history
  • Loading branch information
ftnext committed Dec 7, 2024
1 parent ee7234d commit 26e5165
Showing 1 changed file with 6 additions and 42 deletions.
48 changes: 6 additions & 42 deletions tests/recognizers/test_openai.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from unittest import TestCase
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock

import httpx
import pytest
import respx

from speech_recognition import AudioData, Recognizer
Expand All @@ -13,7 +11,11 @@
def test_transcribe_with_openai_whisper(respx_mock, monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "sk_openai_api_key")

respx_mock.post("https://api.openai.com/v1/audio/transcriptions").mock(
respx_mock.post(
"https://api.openai.com/v1/audio/transcriptions",
headers__contains={"Authorization": "Bearer sk_openai_api_key"},
data__contains={"model": "whisper-1"},
).mock(
return_value=httpx.Response(
200,
json={"text": "Transcription by OpenAI Whisper"},
Expand All @@ -28,41 +30,3 @@ def test_transcribe_with_openai_whisper(respx_mock, monkeypatch):
)

assert actual == "Transcription by OpenAI Whisper"


@pytest.mark.skip
@patch("speech_recognition.recognizers.whisper.os.environ")
@patch("speech_recognition.recognizers.whisper.BytesIO")
@patch("openai.OpenAI")
class RecognizeWhisperApiTestCase(TestCase):
def test_recognize_default_arguments(self, OpenAI, BytesIO, environ):
client = OpenAI.return_value
transcript = client.audio.transcriptions.create.return_value

recognizer = MagicMock(spec=Recognizer)
audio_data = MagicMock(spec=AudioData)

actual = whisper.recognize_whisper_api(recognizer, audio_data)

self.assertEqual(actual, transcript.text)
audio_data.get_wav_data.assert_called_once_with()
BytesIO.assert_called_once_with(audio_data.get_wav_data.return_value)
OpenAI.assert_called_once_with(api_key=None)
client.audio.transcriptions.create.assert_called_once_with(
file=BytesIO.return_value, model="whisper-1"
)

def test_recognize_pass_arguments(self, OpenAI, BytesIO, environ):
client = OpenAI.return_value

recognizer = MagicMock(spec=Recognizer)
audio_data = MagicMock(spec=AudioData)

_ = whisper.recognize_whisper_api(
recognizer, audio_data, model="x-whisper", api_key="OPENAI_API_KEY"
)

OpenAI.assert_called_once_with(api_key="OPENAI_API_KEY")
client.audio.transcriptions.create.assert_called_once_with(
file=BytesIO.return_value, model="x-whisper"
)

0 comments on commit 26e5165

Please sign in to comment.