Django unittest and mocking the requests module

mocking, python, python-requests, unit-testing

Solution

Patch `json` method instead of `content`. (`content` is not used in `some_function`)

Try following code.

import unittest

from mock import Mock, patch

import utils

class UtilsTestCase(unittest.TestCase):
    def test_some_function(self):
        user = self.user = Mock()
        user.email = 'user@example.com'
        with patch('utils.requests') as mock_requests:
            mock_requests.get.return_value = mock_response = Mock()
            mock_response.status_code = 200
            mock_response.json.return_value = {"UserId":"123456"}
            results = utils.some_function(self.user)
            self.assertEqual(results['UserId'], '123456')

Problem

I am new to Mock and am writing a unit test for this function: ``` # utils.py import requests def some_function(user): payload = {'Email': user.email} url = 'http://api.example.com' response = requests.get(url, params=payload) if response.status_code == 200: return response.json() else: return None ``` I am using Michael Foord's Mock library as part of my unit test and am having difficulty mocking the `response.json()` to return a json structure. Here is my unit test: ``` # tests.py from .utils import some_function class UtilsTestCase(unittest.TestCase): def test_some_function(self): with patch('utils.requests') as mock_requests: mock_requests.get.return_value.status_code = 200 mock_requests.get.return_value.content = '{"UserId":"123456"}' results = some_function(self.user) self.assertEqual(results['UserId'], '123456') ``` I have tried numerous combinations of different mock settings after reading the docs with no luck. If I print the `results` in my unit test it always displays the following instead of the json data structure I want: ``` <MagicMock name=u'requests.get().json().__getitem__().__getitem__()' id='30315152'> ``` Thoughts on what I am doing wrong?

Original source