• unittest subTests上下文管理器的使用


    unittest3.4版本后新增的subTests上下文管理器,用于处理类似数据驱动的循环操作,如:

    import unittest
    
    data = [1,2,3,4,5]
    
    class TestsDemo(unittest.TestCase):
        def test_a(self):
            for item in data:
                with self.subTest(item=item):
                    self.assertGreater(item, 2)
    
    if __name__ == '__main__':
        unittest.main()
    

    作用主要用于显示每一个数据的结果,当一个数据失败时,不会中断运行。
    类似于ddt的功能,但实际仍只有一个用例(testMethod)。
    运行结果:

    ======================================================================
    FAIL: test_a (__main__.TestsDemo) (item=1)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "/Users/apple/Documents/Projects/Self/PyPi/runnerz/httprunner/demo.py", line 42, in test_a
        self.assertGreater(item, 2)
    AssertionError: 1 not greater than 2
    ======================================================================
    FAIL: test_a (__main__.TestsDemo) (item=2)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "/Users/apple/Documents/Projects/Self/PyPi/runnerz/httprunner/demo.py", line 42, in test_a
        self.assertGreater(item, 2)
    AssertionError: 2 not greater than 2
    ----------------------------------------------------------------------
    Ran 1 test in 0.002s
    FAILED (failures=2)
    

    结果有点让人凌乱,运行1条用例,失败2条。可以通过自定义unittest.TestResult类来自己定义是否把subTest当做用例。

  • 相关阅读:
    模块-- HASH
    模块 –SYS
    所谓情商高,就是要有分寸感
    20个很有用的CSS技巧
    CSS3中文手册基础知识
    赠书《JavaScript高级程序设计(第三版)》5本
    能走多远,取决于你与谁同行
    谷歌网站
    开发头条精选0724
    开发头条精选0723
  • 原文地址:https://www.cnblogs.com/superhin/p/12763702.html
Copyright © 2020-2023  润新知