refactor: remove redundant comments and docstrings (#6527)

* refactor: remove redundant comments and docstrings

* fix(signal): annotate async context manager as a generator
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-30 13:07:03 +08:00
1 parent cb3ba45317
commit a4d2430140
922 files changed
+406 -7738

No files matched your search

+4 -63
View File
@@ -1,5 +1,3 @@
"""Tests for transcription retry behavior on transient errors (B10)."""
from __future__ import annotations
import asyncio
@@ -160,9 +158,6 @@ def test_resolver_supports_siliconflow_transcription_api_key_env() -> None:
def test_resolver_interpolates_env_ref_in_api_key() -> None:
# load_config() does not interpolate ${VAR}; the transcription path receives
# the raw config, so an env reference in the key must be resolved here rather
# than sent verbatim to the provider (which yields a 401).
config = Config()
config.transcription.provider = "groq"
config.providers.groq.api_key = "${MY_GROQ_KEY}"
@@ -181,8 +176,6 @@ def test_resolver_env_ref_missing_var_degrades_to_not_configured() -> None:
with patch.dict(os.environ, {}, clear=True):
resolved = resolve_transcription_config(config)
# Unresolved reference degrades to a falsy key rather than the literal
# "${...}" string, so the config reports itself as not configured.
assert resolved.api_key == ""
assert resolved.configured is False
@@ -415,11 +408,6 @@ def test_resolver_keeps_enabled_and_limits_on_effective_config() -> None:
assert resolved.max_upload_mb == 12
# ---------------------------------------------------------------------------
# OpenAI provider — retry on transient HTTP + network errors
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
@pytest.mark.parametrize("outcome", [_response(401), _response(501), httpx.LocalProtocolError("bad")])
async def test_openai_does_not_retry_terminal_errors(audio_file: Path, outcome) -> None:
@@ -442,16 +430,10 @@ async def test_openai_gives_up_after_max_attempts(audio_file: Path, outcome) ->
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", sleep):
result = await provider.transcribe(audio_file)
assert result == ""
# 4 attempts total (initial + 3 retries) with 3 sleeps between them.
assert post.await_count == 4
assert [call.args[0] for call in sleep.await_args_list] == [1.0, 2.0, 4.0]
# ---------------------------------------------------------------------------
# Groq provider — same semantics (both go through the shared helper)
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_groq_retries_on_5xx_then_succeeds(audio_file: Path) -> None:
provider = GroqTranscriptionProvider(api_key="gsk-test")
@@ -472,14 +454,8 @@ async def test_groq_does_not_retry_on_auth_error(audio_file: Path) -> None:
assert post.await_count == 1
# ---------------------------------------------------------------------------
# Regression: missing file / missing key must still short-circuit
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_openai_missing_api_key_short_circuits(audio_file: Path) -> None:
"""Missing API key short-circuits before any HTTP call, even when the file exists."""
with patch.dict("os.environ", {}, clear=True):
provider = OpenAITranscriptionProvider(api_key=None)
post = AsyncMock()
@@ -499,7 +475,6 @@ async def test_openai_missing_file_short_circuits() -> None:
@pytest.mark.asyncio
async def test_returns_empty_when_file_unreadable(audio_file: Path) -> None:
"""Existing file that cannot be read (PermissionError/OSError): "" with no HTTP attempt."""
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock()
with patch("pathlib.Path.read_bytes", side_effect=PermissionError("denied")), patch(
@@ -510,11 +485,6 @@ async def test_returns_empty_when_file_unreadable(audio_file: Path) -> None:
assert post.await_count == 0
# ---------------------------------------------------------------------------
# language: forwarded through the helper to the multipart body, on every attempt
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"provider_cls,language",
[(OpenAITranscriptionProvider, "en"), (GroqTranscriptionProvider, "ko")],
@@ -524,7 +494,6 @@ async def test_returns_empty_when_file_unreadable(audio_file: Path) -> None:
async def test_provider_forwards_language_in_multipart(
audio_file: Path, provider_cls: type, language: str
) -> None:
"""When ``language`` is set, the helper sends it as a multipart field."""
provider = provider_cls(api_key="k", language=language)
post = AsyncMock(return_value=_response(200, {"text": "ok"}))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
@@ -544,7 +513,6 @@ async def test_provider_forwards_language_in_multipart(
async def test_provider_omits_language_when_unset(
audio_file: Path, provider_cls: type
) -> None:
"""When ``language`` is None, no ``language`` field is sent."""
provider = provider_cls(api_key="k")
post = AsyncMock(return_value=_response(200, {"text": "ok"}))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
@@ -611,14 +579,8 @@ async def test_json_retry_shares_budget_and_rebuilds_cached_audio(audio_file: Pa
assert call.kwargs["timeout"] == 60.0
# ---------------------------------------------------------------------------
# Malformed / unexpected response bodies must short-circuit, not escape
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_returns_empty_on_malformed_json_body(audio_file: Path) -> None:
"""200 with invalid JSON: log and return "" immediately (no retry, no exception)."""
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(return_value=_raw_response(200, b"<html>not json</html>"))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
@@ -629,7 +591,6 @@ async def test_returns_empty_on_malformed_json_body(audio_file: Path) -> None:
@pytest.mark.asyncio
async def test_returns_empty_on_non_dict_json_body(audio_file: Path) -> None:
"""200 with a JSON array (not dict): no AttributeError leak; return "" immediately."""
provider = OpenAITranscriptionProvider(api_key="sk-test")
post = AsyncMock(return_value=_raw_response(200, b"[]"))
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
@@ -638,16 +599,6 @@ async def test_returns_empty_on_non_dict_json_body(audio_file: Path) -> None:
assert post.await_count == 1
# ---------------------------------------------------------------------------
# Pin the full advertised retry contract: all retryable statuses + exceptions
# ---------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Configurable model: forwarded to the multipart "model" field on all providers
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"provider_cls,default_model",
[(OpenAITranscriptionProvider, "whisper-1"), (GroqTranscriptionProvider, "whisper-large-v3")],
@@ -672,17 +623,12 @@ async def test_multipart_provider_sends_configured_model(audio_file: Path, provi
assert post.await_args_list[0].kwargs["files"]["model"] == (None, "my-stt-model")
# ---------------------------------------------------------------------------
# OpenRouter provider — JSON body with base64 audio + configurable STT model
# ---------------------------------------------------------------------------
def test_audio_format_maps_known_extensions() -> None:
assert _audio_format(Path("v.oga")) == "ogg" # Telegram voice notes
assert _audio_format(Path("v.oga")) == "ogg"
assert _audio_format(Path("v.opus")) == "ogg"
assert _audio_format(Path("v.mp4")) == "m4a"
assert _audio_format(Path("v.mp3")) == "mp3"
assert _audio_format(Path("v.wav")) == "wav" # passthrough for unknown
assert _audio_format(Path("v.wav")) == "wav"
def test_openrouter_defaults_and_chat_base_normalization() -> None:
@@ -690,14 +636,12 @@ def test_openrouter_defaults_and_chat_base_normalization() -> None:
assert default.api_url == "https://openrouter.ai/api/v1/audio/transcriptions"
assert default.model == "openai/whisper-1"
# A chat-style base (what users copy from provider config) gets the path appended.
chat_base = OpenRouterTranscriptionProvider(api_key="k", api_base="https://openrouter.ai/api/v1")
assert chat_base.api_url == "https://openrouter.ai/api/v1/audio/transcriptions"
@pytest.mark.asyncio
async def test_openrouter_sends_json_base64_body(audio_file: Path) -> None:
"""OpenRouter gets a JSON body with base64 audio + format — never multipart."""
provider = OpenRouterTranscriptionProvider(
api_key="k", model="nvidia/parakeet-tdt-0.6b-v3", language="en"
)
@@ -705,11 +649,11 @@ async def test_openrouter_sends_json_base64_body(audio_file: Path) -> None:
with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):
assert await provider.transcribe(audio_file) == "hi"
call = post.await_args_list[0].kwargs
assert "files" not in call # not multipart
assert "files" not in call
body = call["json"]
assert body["model"] == "nvidia/parakeet-tdt-0.6b-v3"
assert body["language"] == "en"
assert body["input_audio"]["format"] == "ogg" # .ogg fixture
assert body["input_audio"]["format"] == "ogg"
assert base64.b64decode(body["input_audio"]["data"]) == audio_file.read_bytes()
@@ -1024,9 +968,7 @@ async def test_transcription_cancellation_releases_client(monkeypatch, audio_fil
await client.aclose()
# ---------------------------------------------------------------------------
# apiBase normalization (#3637): a chat-style base must not be POSTed verbatim
# ---------------------------------------------------------------------------
def test_resolve_transcription_url_falls_back_to_default() -> None:
@@ -1040,7 +982,6 @@ def test_resolve_transcription_url_appends_path_to_chat_style_base() -> None:
_resolve_transcription_url("https://api.groq.com/openai/v1", "https://x/audio/transcriptions")
== "https://api.groq.com/openai/v1/audio/transcriptions"
)
# Trailing slash must not produce a doubled separator.
assert (
_resolve_transcription_url("https://api.groq.com/openai/v1/", "https://x/audio/transcriptions")
== "https://api.groq.com/openai/v1/audio/transcriptions"