zoukankan      html  css  js  c++  java
  • python unittest自动化数据驱动demo

    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)
  • 相关阅读:
    转:发一个自己用过的makefile .
    转:TCP/IP协议选项——TCP_KEEPALIVE .
    转:Socket常用选项
    转:sock_ev——linux平台socket事件框架(event loop) .
    Spring Boot logback
    Spring Boot 连接池
    Spring Boot AOP
    spring boot 配置 freemarker
    maven package install deploy
    idea下maven项目打包
  • 原文地址:https://www.cnblogs.com/yaoqingzhuan/p/12455611.html
Copyright © 2011-2022 走看看