用例参数化(unittest+ddt)
用例参数化:把功能用例转化为代码用例,然后将所有测试数据参数化处理,只用少量代码来处理数据进行接口测试
1.excel数据读取+unittest+ddt
import unittest from ddt import ddt, data from xxx.xxx.xxx import DoExcel from xxx.xxx.xxx import GetData from xxx.xxx.xxx import HttpRequest test_data = DoExcel('test.xlsx', 'test').get_data() # 得到的测试数据格式test_data=[{},{}] @ddt class TestHttp(unittest.TestCase): def setUp(self): pass @data(*test_data) # 将数据格式处理为{},{} def test_api(self, item): # 一个个{}处理 res = HttpRequest().http_request(item['url'], item['data'], item['method'], getattr(GetData, 'Cookie')) if res.cookies: setattr(GetData, 'Cookie', res.cookies) try: self.assertEqual(item['expected'], res.json()['code']) except AssertionError as e: print("'test_api's error is{}".format(e)) raise e def tearDown(self): pass
2.excel数据读取+unittest+for循环遍历+超继承(重写初始化函数)
# 地址 测试数据 请求方法 断言期望结果 除了这几个不同 其他的都是高度相似的 # 参数化 url data method expected import unittest import HTMLTestRunner from xxx.xxx.xxx import DoExcel from xxx.xxx.xxx import HttpRequest from xxx.xxx.xxx import GetData class TestHttp(unittest.TestCase): def setUp(self): pass def __init__(self, methodName, url, data, method, expected): super(TestHttp, self).__init__(methodName) # 超继承,重写但保留父类的方法 self.url = url self.data = data self.method = method self.expected = expected def test_api(self): res = HttpRequest().http_request(self.url, self.data, self.method, getattr(GetData, 'Cookie')) if res.cookies: setattr(GetData, 'Cookie', res.cookies) try: self.assertEqual(self.expected, res.json()['code']) except AssertionError as e: print("'test_api's error is{}".format(e)) raise e def tearDown(self): pass if __name__ == '__main__': test_data = DoExcel('test.xlsx', 'test').get_data() # 得到的测试数据格式test_data=[{},{}] suite = unittest.TestSuite() for item in test_data: suite.addTest(TestHttp('test_api', item['url'], item['data'], item['method'], item['expected'])) with open('xxx.html', 'wb') as file: runner = HTMLTestRunner.HTMLTestRunner( stream=file, verbosity=2, title='自动化测试报告', description='描述一下' ) runner.run(suite)