pytest_httpx icon indicating copy to clipboard operation
pytest_httpx copied to clipboard

`HTTPXMock` context manager

Open cbensimon opened this issue 1 year ago • 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

cbensimon avatar Feb 02 '24 10:02 cbensimon

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 ?

Colin-b avatar Feb 12 '24 23:02 Colin-b

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

cbensimon avatar Feb 16 '24 13:02 cbensimon

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?

mrswats avatar May 28 '24 15:05 mrswats