接口请求
import requests
def listCourse():
payload = {
'action': 'list_course',
'pagenum': 1,
'pagesize': 20
}
r = requests.get('http://localhost:80/api/mgr/sq_mgr/', params=payload)
return r.json()
mock的封装
from unittest import mock
def mock_test(mock_method,response_data):
mock_method = mock.Mock(return_value=response_data)
data = mock_method()
return data
data为mock返回数据
import unittest
import HTMLTestRunner
from api.base.demo import listCourse
from api.base.mock_demo import mock_test
class TestMethod(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tearDownClass(cls):
pass
def setUp(self):
pass
def tearDown(self):
print('test-->tearDown')
@unittest.skip('test_01')
def test_01(self):
self.assertEqual(listCourse['retcode'], 0, '测试失败')
def test_02(self):
#mock要返回的数据
data = {'retcode': 0, 'retlist': [{'id': 1524, 'name': '张三', 'desc': '一个描述', 'display_idx': 1}]}
api_data = mock_test(listCourse, data)
print(api_data)
self.assertEqual(api_data['retcode'], 0, '测试失败')
if __name__ == '__main__':
# unittest.main()
# 创建一个容器
# filePath = '/Users/wgz/Desktop/songqin/接口作业/report/htmlrepart.html'
# print(filePath)
# fp = open(filePath,'wb')
suite = unittest.TestSuite()
suite.addTest(TestMethod('test_02'))
# suite.addTest(TestMethod('test_03'))
# runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title='this is first report')
# runner.run(suite)
unittest.TextTestRunner().run(suite)
mock的实现也可用代理工具如fiddler、charles来实现,具体过程不再赘述
网友评论