Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed Async httpx Request Handling in vcr.py Sync Contexts #833

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion vcr/stubs/httpx_stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import inspect
import logging
from unittest.mock import MagicMock, patch
from concurrent.futures import ThreadPoolExecutor

import httpx

Expand Down Expand Up @@ -166,6 +167,17 @@ def _inner_send(*args, **kwargs):
return _inner_send


def run_async_from_sync(func, *args, **kwargs):
"""
Utility function to run an async function from sync code using a ThreadPoolExecutor.
"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
with ThreadPoolExecutor() as executor:
future = executor.submit(loop.run_until_complete, func(*args, **kwargs))
return future.result()


def _sync_vcr_send(cassette, real_send, *args, **kwargs):
vcr_request, response = _shared_vcr_send(cassette, real_send, *args, **kwargs)
if response:
Expand All @@ -174,7 +186,7 @@ def _sync_vcr_send(cassette, real_send, *args, **kwargs):
return response

real_response = real_send(*args, **kwargs)
asyncio.run(_record_responses(cassette, vcr_request, real_response, aread=False))
run_async_from_sync(_record_responses, cassette, vcr_request, real_response, aread=False)
return real_response


Expand Down