Colin-b/pytest_httpx

`HTTPXMock` context manager

Opened this issue · 3 comments

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

  • Moving the monkey patching inside HTTPXMock.__enter__
  • Calling self.reset inside HTTPXMock.__exit__
  • Using HTTPXMock as a context manager in the httpx_mock fixture definition

Let me know what you think

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 ?

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

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?