Python:如何模仿行为

时间:2014-05-23 16:50:01

标签: python google-app-engine mocking

如何模拟函数的行为?

例如,如果您有以下发出HTTP请求的App Engine代码,您将如何模拟该函数以使其返回非200响应?

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

这是我写的模拟,但我不知道如何嘲笑非200响应。

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)

1 个答案:

答案 0 :(得分:2)

你测试真的没有做太多:它只是测试是否使用你传递的参数来调用函数

如果您希望urlfetch.fetch返回某个值,请使用MagicMock:

import urlfetch
from unittest.mock import MagicMock

reponse = 'Test response'

urlfetch.fetch = MagicMock(return_value=response)

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

这是一个在fetch_url返回500错误时测试urlfetch.fetch函数的快速示例:

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