如何模拟函数的行为?
例如,如果您有下面发出HTTP请求的App代码,您将如何模拟该函数以使其返回一个非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)
发布于 2014-05-23 10:26:02
您的测试实际上并没有多大作用:它只是测试函数是否使用参数调用,然后传递给它。
如果希望urlfetch.fetch
返回某个值,请使用:
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
https://stackoverflow.com/questions/23834588
复制相似问题