我是Mock的新手,正在为此功能编写单元测试:
# utils.py
import requests
def some_function(user):
payload = {'Email': user.email}
url = 'http://api.example.com'
response = requests.get(url, params=payload)
if response.status_code == 200:
return response.json()
else:
return None
我正在使用Michael Foord's Mock库作为我的单元测试的一部分,并且很难模拟response.json()
以返回json结构。这是我的单元测试:
# tests.py
from .utils import some_function
class UtilsTestCase(unittest.TestCase):
def test_some_function(self):
with patch('utils.requests') as mock_requests:
mock_requests.get.return_value.status_code = 200
mock_requests.get.return_value.content = '{"UserId":"123456"}'
results = some_function(self.user)
self.assertEqual(results['UserId'], '123456')
在没有运气阅读文档后,我尝试了不同模拟设置的多种组合。如果我在单元测试中打印results
,它总是显示以下内容而不是我想要的json数据结构:
<MagicMock name=u'requests.get().json().__getitem__().__getitem__()' id='30315152'>
关于我做错了什么的想法?
答案 0 :(得分:15)
修补程序json
方法而不是content
。 (content
)
some_function
请尝试以下代码。
import unittest
from mock import Mock, patch
import utils
class UtilsTestCase(unittest.TestCase):
def test_some_function(self):
user = self.user = Mock()
user.email = 'user@example.com'
with patch('utils.requests') as mock_requests:
mock_requests.get.return_value = mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"UserId":"123456"}
results = utils.some_function(self.user)
self.assertEqual(results['UserId'], '123456')
答案 1 :(得分:1)
我喜欢使用的另一种模式是更可重用的模式是在单元测试的setUp
方法中启动修补程序。检查使用预期参数调用模拟请求也很重要:
class UtilsTestCase(TestCase):
def setUp(self):
self.user = Mock(id=123, email='foo@bar.com')
patcher = patch('utils.requests.get')
self.mock_response = Mock(status_code=200)
self.mock_response.raise_for_status.return_value = None
self.mock_response.json.return_value = {'UserId': self.user.id}
self.mock_request = patcher.start()
self.mock_request.return_value = self.mock_response
def tearDown(self):
self.mock_request.stop()
def test_request(self):
results = utils.some_function(self.user)
self.assertEqual(results['UserId'], 123)
self.mock_request.assert_called_once_with(
'http://api.example.com'
payload={'Email': self.user.email},
)
def test_bad_request(self):
# override defaults and reassign
self.mock_response.status_code = 500
self.mock_request.return_value = self.mock_response
results = utils.some_function(self.user)
self.assertEqual(results, None)
self.mock_request.assert_called_once_with(
'http://api.example.com'
payload={'Email': user.email},
)
答案 2 :(得分:0)
我认为另一种方式更清晰直接:
import unittest
from mock import Mock, patch
import utils
class UtilsTestCase(unittest.TestCase):
def test_some_function(self):
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"UserId": "123456"}
with patch('utils.requests.get') as mock_requests:
results = utils.some_function(self.user)
self.assertEqual(results['UserId'], '123456')