• python3 unittest


    一、概念介绍:

    unittest最核心的四部分是:TestCase,TestSuite,TestRunner,TestFixture;

    
    

    TestCase:用户自定义的测试case的基类,在此类里填写需要写的测试方法;  调用run()方法,会依次调用setUp方法、执行用例的方法、tearDown方法。

    
    

    TestSuite:测试用例集合,可以通过addTest()、addTests()方法手动增加Test Case,也可以通过TestLoader自动添加Test Case,TestLoader在添加用例时,会没有顺序。

    
    

    TestRunner:运行测试用例的驱动类,可以执行TestCase,也可以执行TestSuite,执行后TestCase和TestSuite会自动管理TESTResult。

    
    

    TestFixture:简单来说就是做一些测试过程中需要准备的东西,比如创建临时的数据库,文件和目录等,其中setUp()和setDown()是最常用的方法

    
    

    整个的流程就是首先要写好TestCase,然后由TestLoader加载TestCase到TestSuite,然后由TestTestRunner来运行TestSuite,运行的结果保存在TextTestReusult中,整个过程集成在unittest.main模块中;


    二、测试所有脚本代码:

    # -*-encoding:utf-8 -*-


    import unittest
    import HTMLTestRunner


    class T():
    """
    被测试类
    """

    def __init__(self, var1, var2):
    self.var1 = var1
    self.var2 = var2

    def plus(self):
    """
    被测试方法
    :return:
    """
    return self.var1 + self.var2

    def minus(self):
    return self.var1 - self.var2

    def multiply(self):
    return self.var1 * self.var2

    def divide(self):
    return self.var1 / self.var2


    class Test1(unittest.TestCase):
    """
    继承于unittest.TestCase
    """

    def setUp(self):
    print('当前类的每个测试方法执行前先执行此方法')

    def tearDown(self) -> None:
    print('当前类的每个方法执行完成后执行此方法')

    t = T(2, 1)

    def test_plus(self):
    """
    测试方法;
    :return:
    """
    print('Test1 plus method')
    self.assertEqual(self.t.plus(), 3)
    """
    添加断言来判断来判断结果是否执行成功;
    """

    def test_minus(self):
    print('Test1 minus method')
    self.assertEqual(self.t.minus(), 1)

    def test_multiply(self):
    print('Test1 multiply method')
    self.assertEqual(self.t.multiply(), 2)

    def test_divide(self):
    print('Test1 divide method')
    self.assertEqual(self.t.divide(), 2)


    class Test2(unittest.TestCase):
    # @classmethod
    # def setUpClass(self):
    # print("execute setUpClass")
    #
    # @classmethod
    # def tearDownClass(self):
    # print("execute tearDownClass")

    def setUp(self):
    """
    每个测试方法均执行一次;
    :return:
    """
    print("execute setUp")

    def tearDown(self):
    print("execute tearDown")

    @unittest.skipIf(True, '不需要执行')
    def test_one(self):
    # 这里因为使用了条件装饰器,在执行测试的时候会跳过;
    print('execute test_one')
    self.assertTrue('FOO'.isupper())

    # @unittest.skip('这里也不需要执行')
    def test_two(self):
    # 这里因为使用了条件装饰器,在执行测试的时候会跳过;
    print('execute test_two')
    self.assertEqual(True, 0, msg='isnot equal')


    if __name__ == '__main__':
    print('进入了主方法')
    suite = unittest.TestSuite()
    suite.debug()
    # Test2是要测试的类名,test_one是要执行的测试方法
    # 执行其余的方法直接依照添加
    suite.addTest(Test2("test_two"))
    suite.addTest(Test2("test_one"))
    suite.addTest(Test1("test_plus"))
    suite.addTest(Test1("test_minus"))
    suite.addTest(Test1("test_multiply"))
    suite.addTest(Test1("test_divide"))

    # suite.addTests()
    runner = unittest.TextTestRunner()
    print(suite.countTestCases())

    filename = 'F:\unit_test_result.html'
    fb = open(filename, 'wb')

    # runner = HtmlTestRunner.HTMLTestRunner(stream=fb, descriptions='测试报告', report_title='Title', add_timestamp=True)
    runner = HTMLTestRunner.HTMLTestRunner(stream=fb, title="测试HTMLTestRunner", description="测试HTMLTestRunner",verbosity=2)
    runner.run(suite)
    fb.close()




    三、执行单元测试的结果:


    Testing started at 14:09 ...
    C:UserswenlongAppDataLocalProgramsPythonPython37python.exe "C:Program FilesJetBrainsPyCharm Community Edition 2020.1.2pluginspython-cehelperspycharm\_jb_unittest_runner.py" --path C:/Users/wenlong/PycharmProjects/无线项目 -- -v
    Launching unittests with arguments python -m unittest discover -s C:/Users/wenlong/PycharmProjects/无线项目 -t C:UserswenlongPycharmProjects无线项目 -v in C:UserswenlongPycharmProjects无线项目

    当前类的每个测试方法执行前先执行此方法
    Test1 divide method
    当前类的每个方法执行完成后执行此方法
    当前类的每个测试方法执行前先执行此方法
    Test1 minus method
    当前类的每个方法执行完成后执行此方法
    当前类的每个测试方法执行前先执行此方法
    Test1 multiply method
    当前类的每个方法执行完成后执行此方法
    当前类的每个测试方法执行前先执行此方法
    Test1 plus method
    当前类的每个方法执行完成后执行此方法

    Skipped: 不需要执行
    execute setUp
    execute test_two
    execute tearDown

    isnot equal
    0 != True

    Expected :True
    Actual   :0
    <Click to see difference>

    Traceback (most recent call last):
      File "C:Program FilesJetBrainsPyCharm Community Edition 2020.1.2pluginspython-cehelperspycharm eamcitydiff_tools.py", line 32, in _patched_equals
        old(self, first, second, msg)
      File "C:UserswenlongAppDataLocalProgramsPythonPython37libunittestcase.py", line 852, in assertEqual
        assertion_func(first, second, msg=msg)
      File "C:UserswenlongAppDataLocalProgramsPythonPython37libunittestcase.py", line 845, in _baseAssertEqual
        raise self.failureException(msg)
    AssertionError: True != 0 : isnot equal

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:UserswenlongAppDataLocalProgramsPythonPython37libunittestcase.py", line 59, in testPartExecutor
        yield
      File "C:UserswenlongAppDataLocalProgramsPythonPython37libunittestcase.py", line 628, in run
        testMethod()
      File "C:UserswenlongPycharmProjects无线项目utest est_1.py", line 100, in test_two
        self.assertEqual(True, 0, msg='isnot equal')



    Ran 6 tests in 0.009s

    FAILED (failures=1, skipped=1)

    Process finished with exit code 1

    Assertion failed

    Assertion failed

    Assertion failed

    Assertion failed
    四、执行测试脚本生成的报告:

    
    
    


  • 相关阅读:
    MySQL事务处理
    MySQL触发器
    MySQL游标
    MySQL存储过程
    MySQL视图
    MySQL创建和操纵表
    Java异常体系结构以及异常处理机制、自定义异常
    Java的面向对象和抽象类、接口、内部类以及OOP实战
    Java数组声明创建和使用以及多维数组、Arrays类、稀疏数组
    Java通过循环结构和switch实现简易计算器
  • 原文地址:https://www.cnblogs.com/juzib/p/14420687.html
Copyright © 2020-2023  润新知