Colin-b / pytest_httpx

pytest fixture to mock HTTPX
https://colin-b.github.io/pytest_httpx/
MIT License
358 stars 30 forks source link

Don't use single Response instance for all requests. #99

Closed T-256 closed 1 year ago

T-256 commented 1 year ago
import httpx
import pytest
import pytest_httpx

@pytest.mark.asyncio
async def test_something(httpx_mock):
    httpx_mock.add_response(json={"abc": "def"})
    with httpx.Client() as client:
        # response.stream will be a BoundSyncStream
        client.get("https://example.com/")
        # response.stream will be a BoundSyncStream, referencing a BoundSyncStream
        client.get("https://example.com/")
        # response.stream will be a BoundSyncStream, referencing a BoundSyncStream, referencing a BoundSyncStream
        client.get("https://example.com/")

The issue is essentially that a single response instance is being returned by the httpx_mock transport, and being reused.

_Originally posted by @tomchristie in https://github.com/encode/httpx/pull/2777#discussion_r1277523022_

Colin-b commented 1 year ago

Hi @T-256 ,

Thanks for taking the time to investigate this. Indeed if this is an issue, we could consider creating the response only upon entering the callback. This should not break any compatibility (as you are already not expected to provide mutables, unless you know what you are doing anyway). The performance impact should be rather small, and somehow closer to real httpx performances anyway.

Colin-b commented 1 year ago

This should be fixed in version 0.23.0 available on pypi.

Colin-b commented 1 year ago

I added a test case to ensure non regression on this in 0.23.1.