zoukankan      html  css  js  c++  java
  • pyton unittest

    在说unittest之前,先说几个概念:

    TestCase 也就是测试用例

    TestSuite 多个测试用例集合在一起,就是TestSuite

    TestLoader是用来加载TestCase到TestSuite中的

    TestRunner是来执行测试用例的,测试的结果会保存到TestResult实例中,包括运行了多少测试用例,成功了多少,失败了多少等信息

    简单的单元测试用例:

     1 import unittest
     2 import HTMLTestRunner
     3 
     4 class TestCase(unittest.TestCase):
     5     def setUp(self):
     6         """每条用例执行之前运行一次"""
     7         print("-" * 20)
     8 
     9     def tearDown(self):
    10         """每条用例执行之后运行一次"""
    11         print("+" * 20)
    12 
    13     @classmethod
    14     def setUpClass(cls):
    15         """所有用例执行之前运行一次"""
    16         print("6" * 10)
    17 
    18     @classmethod
    19     def tearDownClass(cls):
    20         """所有用例执行之后运行一次"""
    21         print("9" * 10)
    22 
    23     def test_case_1(self):
    24         """assertEqual 两个值相等"""
    25         print("1 == 1")
    26         self.assertEqual(1,1)
    27 
    28     def test_case_2(self):
    29         """assertNotEqual 两个值不相等"""
    30         print("2 != 1")
    31         self.assertNotEqual(2, 1)
    32 
    33     def test_case_3(self):
    34         """assertTrue 结果为True"""
    35         print("2 > 1")
    36         self.assertTrue(2 > 1)
    37 
    38     def test_case_4(self):
    39         """assertFalse 结果为False"""
    40         print("2 < 1")
    41         self.assertFalse(2 < 1)
    42 
    43 if __name__ == "__main__":
    44     # 运行所有的测试用例
    45     unittest.main()

    执行结果:

    Launching unittests with arguments python -m unittest D:/python_file/test_func/unittest-01.py in D:python_file	est_func
    6666666666--------------------
    1 == 1
    ++++++++++++++++++++
    --------------------
    2 != 1
    ++++++++++++++++++++
    --------------------
    2 > 1
    ++++++++++++++++++++
    --------------------
    2 < 1
    ++++++++++++++++++++
    9999999999
    
    Ran 4 tests in 0.005s
    
    OK
    
    Process finished with exit code 0

    下面是一些常用的断言,也就是校验结果:

            assertEqual(a, b)     a == b      
            assertNotEqual(a, b)     a != b      
            assertTrue(x)     bool(x) is True      
            assertFalse(x)     bool(x) is False      
            assertIsNone(x)     x is None     
            assertIsNotNone(x)     x is not None   
            assertIn(a, b)     a in b    
            assertNotIn(a, b)     a not in b

    skip跳过测试用例:

    1、unittest.skip(reason):强制跳过,reason是跳过原因
    2、unittest.skipIf(condition, reason):condition为True时跳过
    3、unittest.skipUnless(condition, reason):condition为False时跳过
     1 import unittest
     2 import HTMLTestRunner
     3 
     4 class TestCase(unittest.TestCase):
     5     @classmethod
     6     def setUpClass(cls):
     7         """所有用例执行之前运行一次"""
     8         print("6" * 10)
     9 
    10     @classmethod
    11     def tearDownClass(cls):
    12         """所有用例执行之后运行一次"""
    13         print("9" * 10)
    14 
    15     def test_case_1(self):
    16         """assertEqual 两个值相等"""
    17         print("1 == 1")
    18         self.assertEqual(1,1)
    19 
    20     @unittest.skip(reason = "强制跳过,reason是跳过原因")
    21     def test_case_2(self):
    22         """assertNotEqual 两个值不相等"""
    23         print("2 != 1")
    24         self.assertNotEqual(2, 1)
    25 
    26     @unittest.skipIf(3 > 2, reason = "结果为True时跳过")
    27     def test_case_3(self):
    28         """assertTrue 结果为True"""
    29         print("2 > 1")
    30         self.assertTrue(2 > 1)
    31 
    32     @unittest.skipUnless(3 < 2, reason="结果为False时跳过")
    33     def test_case_4(self):
    34         """assertFalse 结果为False"""
    35         print("2 < 1")
    36         self.assertFalse(2 < 1)
    37 
    38 if __name__ == "__main__":
    39     # 运行所有的测试用例
    40     unittest.main()

    执行结果 :

    Launching unittests with arguments python -m unittest D:/python_file/test_func/unittest-01.py in D:python_file	est_func
    66666666661 == 1
    
    Skipped: 强制跳过,reason是跳过原因
    
    Skipped: 结果为True时跳过
    
    Skipped: 结果为False时跳过
    9999999999
    
    Ran 4 tests in 0.002s
    
    OK (skipped=3)
    
    Process finished with exit code 0

    suite测试套件

     1 import my_func
     2 import unittest
     3 
     4 class Test_MyFunc(unittest.TestCase):
     5     """test my_func"""
     6 
     7     def test_01(self):
     8         """>>>负数的绝对值"""
     9         self.assertEqual(1, abs(-1))
    10 
    11     def test_02(self):
    12         """>>>正数的绝对值"""
    13         self.assertEqual(1, abs(1))
    14 
    15     def test_03(self):
    16         """>>>0的绝对值"""
    17         self.assertEqual(0, abs(0))
    18 
    19 
    20 def suite_1():
    21     """addTest方法添加用例,可以对case进行排序"""
    22     # 构造一个套件
    23     suite = unittest.TestSuite()
    24     # 向套件例添加用例、排序
    25     tests_myfunc = [Test_MyFunc("test_01"), Test_MyFunc("test_01"), Test_MyFunc("test_01")]
    26     suite.addTests(tests_myfunc)
    27     return suite
    28 
    29 def suite_01():
    30     """addTests + TestLoader方法来添加用例,但是这种方法是无法对case进行排序的"""
    31 
    32     # 第一种方法:传入'模块名.TestCase名'
    33     # 构造测试套件
    34     suite = unittest.TestSuite()
    35     suite.addTests(unittest.TestLoader().loadTestsFromName("s.Test_MyFunc"))
    36     # 这里还可以把多个'模块名.Test_MyFunc'放到一个列表中
    37     # suite.addTests(unittest.TestLoader().loadTestsFromNames(['a.Test_a', 'b.Test_b']))
    38     return suite
    39 
    40 
    41 def suite_02():
    42     """addTests + TestLoader方法来添加用例,但是这种方法是无法对case进行排序的"""
    43     # 第二种方法:传入TestCase
    44     suite = unittest.TestSuite()
    45     suite.addTests(unittest.TestLoader().loadTestsFromTestCase(Test_MyFunc))
    46     return suite
    47 
    48 def run(suite):
    49     runner = unittest.TextTestRunner(verbosity=2)
    50     runner.run(suite)
    51 
    52 run(suite_1())

    执行结果:

    test_03 (s.Test_MyFunc)
    >>>0的绝对值 ... ok
    test_01 (s.Test_MyFunc)
    >>>负数的绝对值 ... ok
    test_02 (s.Test_MyFunc)
    >>>正数的绝对值 ... ok

    ----------------------------------------------------------------------
    Ran 3 tests in 0.000s

    OK
    Launching unittests with arguments python -m unittest D:/python_file/test_func/s.py in D:python_file est_func


    Ran 3 tests in 0.001s

    OK

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 

    使用套件执行会把case的解释给打印出来。。。

     1 import unittest
     2 import HTMLTestRunner
     3 
     4 class TestCase(unittest.TestCase):
     5     def test_case_1(self):
     6         """>>>assertEqual 两个值相等"""
     7         print("1 == 1")
     8         self.assertEqual(1,1)
     9 
    10     @unittest.skip(reason = "强制跳过,reason是跳过原因")
    11     def test_case_2(self):
    12         """>>>assertNotEqual 两个值不相等"""
    13         print("2 != 1")
    14         self.assertNotEqual(2, 1)
    15 
    16     @unittest.skipIf(3 > 2, reason = "结果为True时跳过")
    17     def test_case_3(self):
    18         """>>>assertTrue 结果为True"""
    19         print("2 > 1")
    20         self.assertTrue(2 > 1)
    21 
    22     # @unittest.skipUnless(3 < 2, reason="结果为False时跳过")
    23     def test_case_4(self):
    24         """assertFalse 结果为False"""
    25         print("2 < 1")
    26         self.assertFalse(2 < 1)
    27 
    28 # if __name__ == "__main__":
    29 #     # 运行所有的测试用例
    30 #     unittest.main()
    31 
    32 suite = unittest.TestSuite()
    33 suite.addTests([TestCase("test_case_1"), TestCase("test_case_2")])
    34 unittest.TextTestRunner(verbosity=2).run(suite)

    执行结果:

    1 == 1test_case_1 (unittest-01.TestCase)
    >>>assertEqual 两个值相等 ... ok
    test_case_2 (unittest-01.TestCase)
    >>>assertNotEqual 两个值不相等 ... skipped '强制跳过,reason是跳过原因'
    
    ----------------------------------------------------------------------
    Ran 2 tests in 0.000s
    
    OK (skipped=1)
    1 == 1

    测试结果输出到文件:

    verbosity控制测试结果的详细程度:0表示简单,1表示一般,2表示详细

     测试结果输出到TXT

    suite = unittest.TestSuite()
    suite.addTest(TestEmail("test_01"))
    suite.addTest(TestEmail("test_03"))
    with open("result1.txt", "a", encoding="utf-8") as f:
        runner = unittest.TextTestRunner(stream=f, verbosity=2).run(suite)

     测试结果输出到HTML

    suite = unittest.TestSuite()
    suite.addTests([TestEmail("test_01"), TestEmail("test_03")])
    with open(r"result1.html", "wb") as f:
        HTMLTestRunner.HTMLTestRunner(stream=f, verbosity=2, title="测试报告", description="测试报告详情").run(suite)
  • 相关阅读:
    第十五周翻译
    数据库 第十五周学习笔记
    第十四周学习笔记
    SQL Server安全级别2的楼梯:身份验证
    第十三周学习笔记
    第十三周翻译:SQL Server的安全1级楼梯:SQL Server安全概述
    MySQL修改默认存储引擎(转)
    【整理】MySQL引擎(转)
    合理配置MySQL缓存 提高缓存命中率(转)
    MySQL数据库分区的概念与2大好处
  • 原文地址:https://www.cnblogs.com/gxfaxe/p/9927675.html
Copyright © 2011-2022 走看看