繁体   English   中英

Python:如何模仿行为

[英]Python: How to Mock behavior

如何模拟函数的行为?

例如,如果您有以下发出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)

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

如果你想让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

因此,当urlfetch.fetch返回500错误时,测试fetch_url函数的快速示例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM