Mocking HTTP requests with HTTPretty
Today it is quite common to write applications that depend on third-party APIs, or even internal APIs, in this modularized digital world. But it makes testing tricky because dependency has an impact during the testing process:
- Test cases will be slow
- Test cases might fail if the third-party service is down
- Test cases will consume resources in the external service (allowed rate limits)
- Sensitive information must be available to make them work (API Keys, secrets, etc)
That’s enough reasons to think of better ways to improve the process, and this is where HTTPretty comes to the rescue.
HTTPretty is just a mocking library for HTTP requests. Quoting their original words:
Once upon a time a python developer wanted to use a RESTful api, everything was fine but until the day he needed to test the code that hits the RESTful API: what if the API server is down? What if its content has changed?
Lucky for us HTTPretty has a really simple interface and since it monkey patches Python’s socket module, it works independently of the HTTP library used.
Lets start with a simple example, let’s
200 response (we
will be using the
requests library for its simplicity):
We can override the response content of course:
We can make the response content to be of any type, JSON for example:
For simplicity, there’s a decorator that will call
disable() for us:
HTTPretty also support the many HTTP methods beside
GET, they can be
Other features are:
- Add custom headers with the
- Define multiple response values with the
responsesparameter, the responses will be returned in order they are defined.
- Set a function as
URIcan be defined as a regular expression.
HTTPretty is great tool that helps to speed up the test cases that depend on external APIs. It also help to ensure that the application logic is well defined with the expected responses from the services, and if the third-party changes, it’s not a fault in your code.