| 1 |
from collections.abc import Generator |
| 2 |
from operator import methodcaller |
| 3 |
|
| 4 |
import httpx |
| 5 |
import pytest |
| 6 |
from pytest import Config, FixtureRequest, MonkeyPatch |
| 7 |
|
| 8 |
from pytest_httpx._httpx_mock import HTTPXMock |
| 9 |
from pytest_httpx._httpx_internals import IteratorStream |
| 10 |
from pytest_httpx._options import _HTTPXMockOptions |
| 11 |
from pytest_httpx.version import __version__ |
| 12 |
|
| 13 |
__all__ = ( |
| 14 |
"HTTPXMock", |
| 15 |
"IteratorStream", |
| 16 |
"__version__", |
| 17 |
) |
| 18 |
|
| 19 |
|
| 20 |
@pytest.fixture |
| 21 |
def httpx_mock( |
| 22 |
monkeypatch: MonkeyPatch, |
| 23 |
request: FixtureRequest, |
| 24 |
) -> Generator[HTTPXMock, None, None]: |
| 25 |
options = {} |
| 26 |
for marker in request.node.iter_markers("httpx_mock"): |
| 27 |
options = marker.kwargs | options |
| 28 |
__tracebackhide__ = methodcaller("errisinstance", TypeError) |
| 29 |
options = _HTTPXMockOptions(**options) |
| 30 |
|
| 31 |
mock = HTTPXMock(options) |
| 32 |
|
| 33 |
# Mock synchronous requests |
| 34 |
real_handle_request = httpx.HTTPTransport.handle_request |
| 35 |
|
| 36 |
def mocked_handle_request( |
| 37 |
transport: httpx.HTTPTransport, request: httpx.Request |
| 38 |
) -> httpx.Response: |
| 39 |
if options.should_mock(request): |
| 40 |
return mock._handle_request(transport, request) |
| 41 |
return real_handle_request(transport, request) |
| 42 |
|
| 43 |
monkeypatch.setattr( |
| 44 |
httpx.HTTPTransport, |
| 45 |
"handle_request", |
| 46 |
mocked_handle_request, |
| 47 |
) |
| 48 |
|
| 49 |
# Mock asynchronous requests |
| 50 |
real_handle_async_request = httpx.AsyncHTTPTransport.handle_async_request |
| 51 |
|
| 52 |
async def mocked_handle_async_request( |
| 53 |
transport: httpx.AsyncHTTPTransport, request: httpx.Request |
| 54 |
) -> httpx.Response: |
| 55 |
if options.should_mock(request): |
| 56 |
return await mock._handle_async_request(transport, request) |
| 57 |
return await real_handle_async_request(transport, request) |
| 58 |
|
| 59 |
monkeypatch.setattr( |
| 60 |
httpx.AsyncHTTPTransport, |
| 61 |
"handle_async_request", |
| 62 |
mocked_handle_async_request, |
| 63 |
) |
| 64 |
|
| 65 |
yield mock |
| 66 |
try: |
| 67 |
mock._assert_options() |
| 68 |
finally: |
| 69 |
mock.reset() |
| 70 |
|
| 71 |
|
| 72 |
def pytest_configure(config: Config) -> None: |
| 73 |
config.addinivalue_line( |
| 74 |
"markers", |
| 75 |
"httpx_mock(*, assert_all_responses_were_requested=True, assert_all_requests_were_expected=True, can_send_already_matched_responses=False, should_mock=lambda request: True): Configure httpx_mock fixture.", |
| 76 |
) |