Colin-b / pytest_httpx

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

How to mock and test request with content passed as byte iterator #148

Open adamko147 opened 3 weeks ago

adamko147 commented 3 weeks ago

Hello team,

I have httpx code that passes content to request using byte iterator. When trying the test code using pytest_httpx and match_content on mocked request, I get assertion error and the aiter_bytes is never called. Here's what I'm trying...

import httpx
import pytest

async def aiter_bytes():
    yield b"h"
    yield b"e"
    yield b"l"
    yield b"l"
    yield b"o"

@pytest.mark.asyncio
async def test_httpx_get(httpx_mock):
    httpx_mock.add_response(method="PUT", url="http://put", content=b"world", match_content=b"hello")
    async with httpx.AsyncClient() as client:
        res = await client.put("http://put", content=aiter_bytes())
        assert res.text == "world"

and the exception when runnning the test

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <Request('PUT', 'http://put')>

    def read(self) -> bytes:
        """
        Read and return the request content.
        """
        if not hasattr(self, "_content"):
>           assert isinstance(self.stream, typing.Iterable)
E           AssertionError

When I remove the match_content parameter, the test passes, but the aiter_bytes is never called. Is there anything I'm missing? I'm not sure whether this is pytest_httpx or httpx issue, although when I run the code without pytest in real program, it works and sends the data properly.

Thank you, Adam