import unittest # 模拟从配置文件或数据库解析后得到的数据 data = [ { 'url': 'http://www.httpbin.org/get', 'method': 'GET', 'params': {} }, { 'url': 'http://www.httpbin.org/post', 'method': 'POST', 'params': {'a': 1, 'b': 2} }, ] # 采用的闭包的形式将用例执行需要的参数传入testcase method 中,不然无法将需要的参数传入testcase里面 # 相当于测试类中的测试方法 def test_01(self):pass def test(**kwargs): def _test(self): import requests resp = requests.request(kwargs.get('method'), kwargs.get('url'), data=kwargs.get('params')) print(resp.json()) self.assertTrue(resp.status_code == 201) return resp return _test # 使用元类动态创建测试类,相当于:class MyTest(unittest.TestCase):pass TestSequence = type('TestSequence', (unittest.TestCase,), {}) # 使用反射动态往测试类中添加测试方法 for index, item in enumerate(data): test_method_name = 'test_{:04}_{:03}'.format(index, index) test_method = test(**item) setattr(TestSequence, test_method_name, test_method) # 执行测试类 test_cases = unittest.TestLoader().loadTestsFromTestCase(TestSequence) test_suite = unittest.TestSuite() test_suite.addTest(test_cases) unittest.TextTestRunner().run(test_suite)