Skip to content
Prev Previous commit
Next Next commit
Created PrereadCompatibleAiohttpResponseStream work around for karpet…
  • Loading branch information
jamesbraza committed Sep 23, 2025
commit 0de942acaa5eee85f04f5ac7959ee8b65319a45c
26 changes: 25 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

import os
import shutil
from collections.abc import Iterator
from collections.abc import AsyncIterator, Iterator
from pathlib import Path
from typing import TYPE_CHECKING, Any
from unittest.mock import patch

import httpx_aiohttp
import pytest
from dotenv import load_dotenv
from lmi.utils import (
Expand Down Expand Up @@ -139,3 +140,26 @@ def stub_data_dir_w_near_dupes(stub_data_dir: Path, tmp_path: Path) -> Iterator[

if tmp_path.exists():
shutil.rmtree(tmp_path, ignore_errors=True)


class PreReadCompatibleAiohttpResponseStream(
httpx_aiohttp.transport.AiohttpResponseStream
):
"""aiohttp-backed response stream that works if the response was pre-read."""

async def __aiter__(self) -> AsyncIterator[bytes]:
with httpx_aiohttp.transport.map_aiohttp_exceptions():
if self._aiohttp_response._body is not None:
# Happens if some intermediary called `await _aiohttp_response.read()`
# TODO: take into account chunk size
yield self._aiohttp_response._body
else:
async for chunk in self._aiohttp_response.content.iter_chunked(
self.CHUNK_SIZE
):
yield chunk


# Permanently patch the original response stream,
# to work around https://github.com/karpetrosyan/httpx-aiohttp/issues/23
httpx_aiohttp.transport.AiohttpResponseStream = PreReadCompatibleAiohttpResponseStream # type: ignore[misc]