Fedir Zadniprovskyi 2024-10-01
test: switch to async http client
@875890de74d5e375fc33225b3abdf4a140cfa9f7
pyproject.toml
--- pyproject.toml
+++ pyproject.toml
@@ -30,6 +30,7 @@
     "basedpyright==1.13.0",
     "pytest-xdist==3.6.1",
     "pytest-asyncio>=0.24.0",
+    "anyio>=4.4.0",
 ]
 
 [build-system]
tests/api_timestamp_granularities_test.py
--- tests/api_timestamp_granularities_test.py
+++ tests/api_timestamp_granularities_test.py
@@ -1,5 +1,7 @@
 """See `tests/openai_timestamp_granularities_test.py` to understand how OpenAI handles `response_type` and `timestamp_granularities`."""  # noqa: E501
 
+from pathlib import Path
+
 from faster_whisper_server.api_models import TIMESTAMP_GRANULARITIES_COMBINATIONS, TimestampGranularities
 from openai import AsyncOpenAI
 import pytest
@@ -11,10 +13,10 @@
     openai_client: AsyncOpenAI,
     timestamp_granularities: TimestampGranularities,
 ) -> None:
-    audio_file = open("audio.wav", "rb")  # noqa: SIM115, ASYNC230
+    file_path = Path("audio.wav")
 
     await openai_client.audio.transcriptions.create(
-        file=audio_file, model="whisper-1", response_format="json", timestamp_granularities=timestamp_granularities
+        file=file_path, model="whisper-1", response_format="json", timestamp_granularities=timestamp_granularities
     )
 
 
@@ -24,10 +26,10 @@
     openai_client: AsyncOpenAI,
     timestamp_granularities: TimestampGranularities,
 ) -> None:
-    audio_file = open("audio.wav", "rb")  # noqa: SIM115, ASYNC230
+    file_path = Path("audio.wav")
 
     transcription = await openai_client.audio.transcriptions.create(
-        file=audio_file,
+        file=file_path,
         model="whisper-1",
         response_format="verbose_json",
         timestamp_granularities=timestamp_granularities,
tests/conftest.py
--- tests/conftest.py
+++ tests/conftest.py
@@ -18,6 +18,7 @@
         logger.disabled = True
 
 
+# NOTE: not being used. Keeping just in case
 @pytest.fixture()
 def client() -> Generator[TestClient, None, None]:
     os.environ["WHISPER__MODEL"] = "Systran/faster-whisper-tiny.en"
tests/openai_timestamp_granularities_test.py
--- tests/openai_timestamp_granularities_test.py
+++ tests/openai_timestamp_granularities_test.py
@@ -1,5 +1,7 @@
 """OpenAI's handling of `response_format` and `timestamp_granularities` is a bit confusing and inconsistent. This test module exists to capture the OpenAI API's behavior with respect to these parameters."""  # noqa: E501
 
+from pathlib import Path
+
 from faster_whisper_server.api_models import TIMESTAMP_GRANULARITIES_COMBINATIONS, TimestampGranularities
 from openai import AsyncOpenAI, BadRequestError
 import pytest
@@ -12,19 +14,18 @@
     actual_openai_client: AsyncOpenAI,
     timestamp_granularities: TimestampGranularities,
 ) -> None:
-    audio_file = open("audio.wav", "rb")  # noqa: SIM115, ASYNC230
-
+    file_path = Path("audio.wav")
     if "word" in timestamp_granularities:
         with pytest.raises(BadRequestError):
             await actual_openai_client.audio.transcriptions.create(
-                file=audio_file,
+                file=file_path,
                 model="whisper-1",
                 response_format="json",
                 timestamp_granularities=timestamp_granularities,
             )
     else:
         await actual_openai_client.audio.transcriptions.create(
-            file=audio_file, model="whisper-1", response_format="json", timestamp_granularities=timestamp_granularities
+            file=file_path, model="whisper-1", response_format="json", timestamp_granularities=timestamp_granularities
         )
 
 
@@ -35,10 +36,10 @@
     actual_openai_client: AsyncOpenAI,
     timestamp_granularities: TimestampGranularities,
 ) -> None:
-    audio_file = open("audio.wav", "rb")  # noqa: SIM115, ASYNC230
+    file_path = Path("audio.wav")
 
     transcription = await actual_openai_client.audio.transcriptions.create(
-        file=audio_file,
+        file=file_path,
         model="whisper-1",
         response_format="verbose_json",
         timestamp_granularities=timestamp_granularities,
tests/sse_test.py
--- tests/sse_test.py
+++ tests/sse_test.py
@@ -1,12 +1,13 @@
 import json
 import os
 
-from fastapi.testclient import TestClient
+import anyio
 from faster_whisper_server.api_models import (
     CreateTranscriptionResponseJson,
     CreateTranscriptionResponseVerboseJson,
 )
-from httpx_sse import connect_sse
+from httpx import AsyncClient
+from httpx_sse import aconnect_sse
 import pytest
 import srt
 import webvtt
@@ -22,57 +23,61 @@
 parameters = [(file_path, endpoint) for endpoint in ENDPOINTS for file_path in FILE_PATHS]
 
 
+@pytest.mark.asyncio()
 @pytest.mark.parametrize(("file_path", "endpoint"), parameters)
-def test_streaming_transcription_text(client: TestClient, file_path: str, endpoint: str) -> None:
+async def test_streaming_transcription_text(aclient: AsyncClient, file_path: str, endpoint: str) -> None:
     extension = os.path.splitext(file_path)[1]
-    with open(file_path, "rb") as f:
-        data = f.read()
+    async with await anyio.open_file(file_path, "rb") as f:
+        data = await f.read()
     kwargs = {
         "files": {"file": (f"audio.{extension}", data, f"audio/{extension}")},
         "data": {"response_format": "text", "stream": True},
     }
-    with connect_sse(client, "POST", endpoint, **kwargs) as event_source:
-        for event in event_source.iter_sse():
+    async with aconnect_sse(aclient, "POST", endpoint, **kwargs) as event_source:
+        async for event in event_source.aiter_sse():
             print(event)
             assert len(event.data) > 1  # HACK: 1 because of the space character that's always prepended
 
 
+@pytest.mark.asyncio()
 @pytest.mark.parametrize(("file_path", "endpoint"), parameters)
-def test_streaming_transcription_json(client: TestClient, file_path: str, endpoint: str) -> None:
+async def test_streaming_transcription_json(aclient: AsyncClient, file_path: str, endpoint: str) -> None:
     extension = os.path.splitext(file_path)[1]
-    with open(file_path, "rb") as f:
-        data = f.read()
+    async with await anyio.open_file(file_path, "rb") as f:
+        data = await f.read()
     kwargs = {
         "files": {"file": (f"audio.{extension}", data, f"audio/{extension}")},
         "data": {"response_format": "json", "stream": True},
     }
-    with connect_sse(client, "POST", endpoint, **kwargs) as event_source:
-        for event in event_source.iter_sse():
+    async with aconnect_sse(aclient, "POST", endpoint, **kwargs) as event_source:
+        async for event in event_source.aiter_sse():
             CreateTranscriptionResponseJson(**json.loads(event.data))
 
 
+@pytest.mark.asyncio()
 @pytest.mark.parametrize(("file_path", "endpoint"), parameters)
-def test_streaming_transcription_verbose_json(client: TestClient, file_path: str, endpoint: str) -> None:
+async def test_streaming_transcription_verbose_json(aclient: AsyncClient, file_path: str, endpoint: str) -> None:
     extension = os.path.splitext(file_path)[1]
-    with open(file_path, "rb") as f:
-        data = f.read()
+    async with await anyio.open_file(file_path, "rb") as f:
+        data = await f.read()
     kwargs = {
         "files": {"file": (f"audio.{extension}", data, f"audio/{extension}")},
         "data": {"response_format": "verbose_json", "stream": True},
     }
-    with connect_sse(client, "POST", endpoint, **kwargs) as event_source:
-        for event in event_source.iter_sse():
+    async with aconnect_sse(aclient, "POST", endpoint, **kwargs) as event_source:
+        async for event in event_source.aiter_sse():
             CreateTranscriptionResponseVerboseJson(**json.loads(event.data))
 
 
-def test_transcription_vtt(client: TestClient) -> None:
-    with open("audio.wav", "rb") as f:
-        data = f.read()
+@pytest.mark.asyncio()
+async def test_transcription_vtt(aclient: AsyncClient) -> None:
+    async with await anyio.open_file("audio.wav", "rb") as f:
+        data = await f.read()
     kwargs = {
         "files": {"file": ("audio.wav", data, "audio/wav")},
         "data": {"response_format": "vtt", "stream": False},
     }
-    response = client.post("/v1/audio/transcriptions", **kwargs)
+    response = await aclient.post("/v1/audio/transcriptions", **kwargs)
     assert response.status_code == 200
     assert response.headers["content-type"] == "text/vtt; charset=utf-8"
     text = response.text
@@ -82,14 +87,15 @@
         webvtt.from_string(text)
 
 
-def test_transcription_srt(client: TestClient) -> None:
-    with open("audio.wav", "rb") as f:
-        data = f.read()
+@pytest.mark.asyncio()
+async def test_transcription_srt(aclient: AsyncClient) -> None:
+    async with await anyio.open_file("audio.wav", "rb") as f:
+        data = await f.read()
     kwargs = {
         "files": {"file": ("audio.wav", data, "audio/wav")},
         "data": {"response_format": "srt", "stream": False},
     }
-    response = client.post("/v1/audio/transcriptions", **kwargs)
+    response = await aclient.post("/v1/audio/transcriptions", **kwargs)
     assert response.status_code == 200
     assert "text/plain" in response.headers["content-type"]
 
uv.lock
--- uv.lock
+++ uv.lock
@@ -295,6 +295,7 @@
     { name = "keyboard" },
 ]
 dev = [
+    { name = "anyio" },
     { name = "basedpyright" },
     { name = "pytest" },
     { name = "pytest-asyncio" },
@@ -306,6 +307,7 @@
 
 [package.metadata]
 requires-dist = [
+    { name = "anyio", marker = "extra == 'dev'", specifier = ">=4.4.0" },
     { name = "basedpyright", marker = "extra == 'dev'", specifier = "==1.13.0" },
     { name = "fastapi", specifier = "==0.112.4" },
     { name = "faster-whisper", specifier = "==1.0.3" },
Add a comment
List