Colin-b / pytest_httpx

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

`HTTPXMock` context manager #135

Open cbensimon opened 7 months ago

cbensimon commented 7 months ago

Hi, thanks for you work and for providing this great tool in the httpx ecosystem

Would you (maintainers) be open to making things a bit more modular by offering the option to use HTTPXMock as a context manager?

Meaning we could still do exactly the same with the current fixture style

But we could also define the fixture ourselves (or use it outside of pytest) like :

@pytest.fixture
def api_mock(scope="whatever :)"):
    httpx_mock = HTTPXMock()
    httpx_mock.add_response(...)
    with httpx_mock:
        yield

Internally this would probably mean

Let me know what you think

Colin-b commented 7 months ago

Hello,

That is an interesting proposal. Could you elaborate on the use case? Is it to enable mocking only partially for a specific part of a larger test scenario ?

cbensimon commented 7 months ago

To me one use-case would be the ability to mock outside of Pytest :

If for instance I have a service A that depends on B, I'll mock B in my tests But then it's very handy to use this same (already existing) mocking in the development environment of the service A If HTTPXMock is only available as a pytest fixture then it's not possible

I currently already do this quite successfully with requests and requests-mock This particular point is my last blocker for transitioning to httpx

mrswats commented 3 months ago

This would also allow to mocked requests with different scopes. I am now in a similar situation. I have multiple tests mocking different requests, but when I run them all with randomized order, some of the time they fail because one request is mocked through one test and not the other and vice versa.

Unless I missed something in the docs, this is not currently supported, right?