Unit testing a python app that uses the requests library

It is in fact a little strange that the library has a blank page about end-user unit testing, while targeting user-friendliness and ease of use. There’s however an easy-to-use library by Dropbox, unsurprisingly called responses. Here is its intro post. It says they’ve failed to employ httpretty, while stating no reason of the fail, and written a library with similar API.

import unittest

import requests
import responses


class TestCase(unittest.TestCase):

  @responses.activate  
  def testExample(self):
    responses.add(**{
      'method'         : responses.GET,
      'url'            : 'http://example.com/api/123',
      'body'           : '{"error": "reason"}',
      'status'         : 404,
      'content_type'   : 'application/json',
      'adding_headers' : {'X-Foo': 'Bar'}
    })

    response = requests.get('http://example.com/api/123')

    self.assertEqual({'error': 'reason'}, response.json())
    self.assertEqual(404, response.status_code)

Leave a Comment