kevin1024 / vcrpy

Automatically mock your HTTP interactions to simplify and speed up testing
MIT License
2.72k stars 388 forks source link

Fix httpx async / decoded responses #825

Closed tysonholub closed 1 month ago

tysonholub commented 9 months ago

This is a follow up from #807.

I tested v6.0.1 last week and my issue recording requests against openai was resolved. However, I just uplifted my app from Flask to FastAPI for async support and ran into an issue with v6.0.1 trying to start another event loop:

Traceback (most recent call last):
  File "/app/.venv/lib/python3.11/site-packages/openai/_base_client.py", line 880, in _request
    response = self._client.send(
               ^^^^^^^^^^^^^^^^^^
  File "/app/.venv/lib/python3.11/site-packages/httpx/_client.py", line 915, in send
    response = self._send_handling_auth(
               ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/.venv/lib/python3.11/site-packages/httpx/_client.py", line 943, in _send_handling_auth
    response = self._send_handling_redirects(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/.venv/lib/python3.11/site-packages/httpx/_client.py", line 980, in _send_handling_redirects
    response = self._send_single_request(request)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/.venv/lib/python3.11/site-packages/vcr/stubs/httpx_stubs.py", line 184, in _inner_send
    return _sync_vcr_send(cassette, real_send, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app/.venv/lib/python3.11/site-packages/vcr/stubs/httpx_stubs.py", line 177, in _sync_vcr_send
    asyncio.run(_record_responses(cassette, vcr_request, real_response, aread=False))
  File "/usr/local/lib/python3.11/asyncio/runners.py", line 186, in run
    raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop

I also found assert not hasattr(resp, "_decoder") was preventing recording https://api.openai.com/v1/embeddings responses made by the openai client as they seem to already be decoded by the client before this code runs.

The changes in this PR resolve both issues and allow me to record openai responses in my uplifted FastAPI async app. It's not clear to me the benefit of the async refactor in httpx_stubs.py, but I'll note that my original patch in #807 continued to work in my uplifted FastAPI app.

tysonholub commented 1 month ago

Closed in favor of https://github.com/kevin1024/vcrpy/pull/833