Chapter 4. Mocking HTTP Requests Using HTTPretty

With the Requests module, we gained the means to open URLs, post data, and get data from web services. Let us take an instance of building an application, which uses a RESTful API and unfortunately, the API on which the server is running is down. Even though we achieved interaction with the web using Requests, we failed this time because we got no response from the server's side. This condition may leave us irked and blocked from our progress, as we found no way of testing our code any further.

So, there came this idea of creating an HTTP request mock tool, which can serve us by mocking the web server on the client side. Even though HTTPretty is no way directly connected with Requests, we would like to introduce a mock tool which would help us in the previously mentioned case.

Note

HTTP mock tool helps to mock web services by faking requests.

We'll look at the following topics in this chapter:

  • Understanding HTTPretty
  • Installing HTTPretty
  • Usage in detail
  • Setting headers
  • Working with responses

Understanding HTTPretty

HTTPretty is an HTTP client mock library for Python. The basic idea of HTTPretty is inspired by Ruby's FakeWeb, which is well known to the people from the Ruby community. HTTPretty re-implements the HTTP protocol by mimicking requests and responses.

Essentially, HTTPretty works on socket level, which gives it the inward virtue of working with most of the HTTP client libraries and it is more specifically battle tested against HTTP client libraries like Requests, httplib2 and urlib2. So, we can mock the interactions from our Request library without any difficulty.

Here are the two cases in which HTTPretty comes to the rescue:

  • The condition in which the API server is down
  • The condition in which the API content has changed
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.198.174