jvc26
jvc26

Reputation: 6523

Unit testing Django with remote calls to another server

So I have a Django app, which as part of its functionality makes a request (using the requests module) to another server. What I want to do is have a server available for unittesting which gives me canned responses to test requests from the Django app (allowing to test how Django handles the different potential responses).

An example of the code would be:

payload = {'access_key': key,
          'username': name}
response = requests.get(downstream_url, params=payload)

# Handle response here ...

I've read that you can use SimpleHTTPServer to accomplish this, but I'm not sure of how I use it to this end, any thoughts would be much appreciated!

Upvotes: 2

Views: 362

Answers (1)

Krzysztof Szularz
Krzysztof Szularz

Reputation: 5249

Use the mock module.

from mock import patch, MagicMock

@patch('your.module.requests')
def test_something(self, requests_mock):
    response = MagicMock()
    response.json.return_value = {'key': 'value'}
    requests_mock.get.return_value = response
    … 
    requests_mock.get.assert_called_once_with(…)
    response.json.assert_called_once()

Much more examples in the docs.

You don't need to (and should not) test the code that makes the request. You want to mock out that part and focus on testing the logic that handles the response.

Upvotes: 1

Related Questions