There are three main steps to be followed while dealing with HTTPretty:
We should enable HTTPretty initially, so that it will apply monkey patching; that is, a dynamic replacement of the attributes of the socket module. We will be using the function register_uri
for registering the uniform resource locator. The register_uri
function takes class
, uri
and body
as arguments:
method: register_uri(class, uri, body)
And at the end of our testing process, we should disable HTTPretty so that it doesn't alter the behavior of the other. Let us take a look at using HTTPretty with an example:
import httpretty import requests from sure import expect def example(): httpretty.enable() httpretty.register_uri(httpretty.GET, "http://google.com/", body="This is the mocked body", status=201) response = requests.get("http://google.com/") expect(response.status_code).to.equal(201) httpretty.disable()
In this example, we used the httpretty.GET
class in register_uri
function to register the uri
value that is "http://google.com/"
. In the next line, we used Request to get the information from the URI and then we used the expect function to assert the expected status code. In a nutshell, the preceding code tries to mock the URI and tests whether we are getting the same status code as expected.
We can simplify the preceding code using a decorator. As in the first and third step, that is, enabling and disabling HTTPretty are same all the time, we can use a decorator so that those functions get wrapped up whenever we want them to come into the picture. The decorator looks like this: @httpretty.activate
. The previous code example can be rewritten using a decorator in the following way:
import httpretty import requests from sure import expect @httpretty.activate def example(): httpretty.register_uri(httpretty.GET, "http://google.com/", body="This is the mocked body", status=201) response = requests.get("http://google.com/") expect(response.status_code).to.equal(201)
3.137.163.197