【发布时间】:2015-06-04 14:16:17
【问题描述】:
下面是我的 api.py 模块的代码 sn-p
# -*- coding: utf-8 -*-
from urllib2 import urlopen
from urllib2 import Request
class API:
def call_api(self, url, post_data=None, header=None):
is_post_request = True if (post_data and header) else False
response = None
try:
if is_post_request:
url = Request(url = url, data = post_data, headers = header)
# Calling api
api_response = urlopen(url)
response = api_response.read()
except Exception as err:
response = err
return response
我试图在上述模块的unittest 中模拟urllib2.urlopen。我已经写了
# -*- coding: utf-8 -*-
# test_api.py
from unittest import TestCase
import mock
from api import API
class TestAPI(TestCase):
@mock.patch('urllib2.Request')
@mock.patch('urllib2.urlopen')
def test_call_api(self, urlopen, Request):
urlopen.read.return_value = 'mocked'
Request.get_host.return_value = 'google.com'
Request.type.return_value = 'https'
Request.data = {}
_api = API()
assert _api.call_api('https://google.com') == 'mocked'
运行单元测试后,出现异常
<urlopen error unknown url type: <MagicMock name='Request().get_type()' id='159846220'>>
我错过了什么?请帮帮我。
【问题讨论】:
标签: python unit-testing urllib2 python-mock