Python单测各种模拟的使用
相关包
from unittest import mock
from unittest.mock import patch
from unittest.mock import MagicMock
模拟类方法
同《模拟函数》
模拟requests
requests.get = MagicMock(return_value=MagicMock(json=MagicMock(return_value={"data": "日志"})))
模拟变量
根据变量所在的包路径引入
with patch("path1.path2.变量名", "变量值"):
resp_data = self.handler.get_data("other", "scenelog 2023-05-06")
\# 断言返回值
self.assertEqual(resp_data, "")
模拟函数
可以通过装饰器模拟,多个模拟多行,参数顺序为装饰器从下到上
class TestTegcloudOwnScenePullHandle(object):
@mock.patch.object(HttpRequestHandle, "only_request")
@mock.patch.object(TegcloudOwnScenePullHandler, "get_dimensions")
def test_get_data_err(self, ins_get_dimensions, ins_only_request):
ins_get_dimensions.return_value = (0, [])
ins_only_request.return_value = (
404, "接口异常"
)
模拟aiohttp请求
目前GET请求是可以的,但是如果想模拟POST并携带body目前还没发现可行方案(make_mocked_request
没有body等参数)
from aiohttp.test_utils import make_mocked_request
class TestViewDataHandler(unittest.TestCase):
def test_get_health_res(self, mock_verify_url):
# 构造请求参数
request = make_mocked_request('GET', '/health',
headers={'msg_signature': 'signature'})
Pytest mock相同函数
class TestXXXclass(unittest.TestCase):
def test_func(self, scene_map_db_ins):
scene_map_db_ins.side_effect = [[{"xx": "123", "id": 21}],
[{"xx": "124", "id": 20}]]
Mock 异常
# 调用方法并捕获异常,在with内调用方法
with self.assertRaises(KeyError):
ins = test1(a=["123"],
b="2023-10-12 12:00:00",
c="2023-10-22 13:00:00",
d=s,
e=False)