Ben
Ben

Reputation: 5432

Python: How to Mock behavior

How does one mock the behavior of a function?

For example, if you had the following App Engine code that issued a HTTP request, how would you mock the function to make it return a non 200 response?

def fetch_url(url, method=urlfetch.GET, data=''):
    """Send a HTTP request"""

    result = urlfetch.fetch(url=url, method=method, payload=data,
                            headers={'Access-Control-Allow-Origin': '*'})

    return result.content

Here is the mock I've written, but I don't know how to mock a non-200 response.

class TestUrlFetch(unittest.TestCase):
    """Test if fetch_url sending legitimate requests"""

    def test_fetch_url(self):
        from console.auth import fetch_url

        # Define the url
        url = 'https://google.com'

        # Mock the fetch_url function 
        mock = create_autospec(fetch_url, spec_set=True) 
        mock(url)

        # Test that the function was called with the correct param
        mock.assert_called_once_with(url)

Upvotes: 0

Views: 944

Answers (1)

BeetDemGuise
BeetDemGuise

Reputation: 974

You test really isn't doing much: its simply testing if the function was called with the parameters you passed it.

If you wanted urlfetch.fetch to return a certain value use MagicMock:

import urlfetch
from unittest.mock import MagicMock

reponse = 'Test response'

urlfetch.fetch = MagicMock(return_value=response)

assert urlfetch.fetch('www.example.com') == response

So, a quick example of testing your fetch_url function when urlfetch.fetch returns a 500-error:

def test_500_error(self):
    expected_response = 'Internal Server Error'

    urlfetch.fetch = MagicMock(return_value={'code':500,
                                             'content': 'Internal Server Error'})

    assert fetch_url('www.example.com') == expected_result

Upvotes: 2

Related Questions