-
-
Notifications
You must be signed in to change notification settings - Fork 857
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add httpx.MockTransport()
#1401
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Superb! Excitingly clean. :-)
Hooray 🎉 Latest release of RESPX ( import httpx
import respx
mock_router = respx.MockRouter(using=None)
route = mock_router.get("https://example.org/").mock(return_value=httpx.Response(204))
transport = httpx.MockTransport(mock_router.handler)
with httpx.Client(transport=transport) as client:
response = client.get("https://example.org/")
assert response.status_code == 204
assert route.called |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💯
Last minute suggestion: it looks like the httpx/httpx/_transports/mock.py Lines 43 to 56 in 1816393
I can imagine cases where I might want to be able to write a handler function that uses Maybe apply something like the await me maybe pattern here, so users can define a regular function or an async function for their handler? |
@simonw Yes, that sounds pretty sensible, thanks for noticing! :) I also think async mock views could be useful to me in some cases. I'm not sure we need to impose "async def for async client", so something like await me maybe sounds sensible... |
Closes #1303
Docs as follows...
Mock transports
During testing it can often be useful to be able to mock out a transport, and return pre-determined responses, rather than making actual network requests.
The
httpx.MockTransport
class accepts a handler function, which can be used to map requests onto pre-determined responses:For more advanced use-cases you might want to take a look at the third-party mocking library, RESPX, or the pytest-httpx library.