Working with responses

When we mock HTTP requests using HTTPretty, it returns an httpretty.Response object. We can generate the following responses through callbacks:

  • Rotating Responses
  • Streaming Responses
  • Dynamic Responses

Rotating responses

Rotating responses are the responses we receive in a given order when we send a request to a server with the same URL and same request method. We can define as many responses as we wish with the responses argument.

The following snippet explains the mocking of Rotating Responses:

import httpretty
import requests

from sure import expect

@httpretty.activate
def rotating_responses_example():
    URL = "http://example.com/some/path"
    RESPONSE_1 = "This is Response 1."
    RESPONSE_2 = "This is Response 2."
    RESPONSE_3 = "This is Last Response."

    httpretty.register_uri(httpretty.GET,
                           URL,
                           responses=[
                               httpretty.Response(body=RESPONSE_1,
                                                  status=201),
                               httpretty.Response(body=RESPONSE_2,
                                                  status=202),
                               httpretty.Response(body=RESPONSE_3,
                                                  status=201)])

    response_1 = requests.get(URL)
    expect(response_1.status_code).to.equal(201)
    expect(response_1.text).to.equal(RESPONSE_1)

    response_2 = requests.get(URL)
    expect(response_2.status_code).to.equal(202)
    expect(response_2.text).to.equal(RESPONSE_2)

    response_3 = requests.get(URL)
    expect(response_3.status_code).to.equal(201)
    expect(response_3.text).to.equal(RESPONSE_3)

    response_4 = requests.get(URL)
    expect(response_4.status_code).to.equal(201)
    expect(response_4.text).to.equal(RESPONSE_3)

In this example, we have registered three different responses using the responses argument with the httpretty.register_uri method. And then, we sent four different requests to the server with the same URI and the same method. As a result, we received the first three responses in the sequence of registration. From the fourth request, we'll get the last response defined in the responses object.

Streaming responses

Streaming responses will not have Content-Length header. Rather, they have a Transfer-Encoding header with a value of chunked, and a body consisting of a series of chunks you write to the socket preceded by their individual sizes. These kinds of responses are also called Chunked Responses.

We can mock a Streaming response by registering a generator response body:

import httpretty
import requests
from time import sleep
from sure import expect

def mock_streaming_repos(repos):
    for repo in repos:
        sleep(.5)
        yield repo

@httpretty.activate
def streaming_responses_example():
    URL = "https://api.github.com/orgs/python/repos"
    REPOS = ['{"name": "repo-1", "id": 1}
',
             '
',
             '{"name": "repo-2", "id": 2}
']

    httpretty.register_uri(httpretty.GET,
                           URL,
                           body=mock_streaming_repos(REPOS),
                           streaming=True)

    response = requests.get(URL,
                            data={"track": "requests"})

    line_iter = response.iter_lines()
    for i in xrange(len(REPOS)):
        expect(line_iter.next().strip()).to.equal(REPOS[i].strip())

To mock a streaming response, we need to set the streaming argument to True while registering uri. In the previous example, we mocked the streaming response using the generator mock_streaming_repos, which will take the list as an argument, and will yield the list item every half second.

Dynamic responses through callbacks

If the response from the API server is generated, depending on the values from the request, then we call it a Dynamic response. To mock dynamic responses based on the request, we will use a callback method as defined in the following example:

import httpretty
import requests

from sure import expect

@httpretty.activate
def dynamic_responses_example():
    def request_callback(method, uri, headers):
        return (200, headers, "The {} response from {}".format(method, uri)
    httpretty.register_uri(
        httpretty.GET, "http://example.com/sample/path",
        body=request_callback)


        response = requests.get("http://example.com/sample/path")

        expect(response.text).to.equal(' http://example.com/sample/path')

In this example, request_callback method is registered while mocking the response, in order to generate dynamic response content.

..................Content has been hidden....................

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