zoukankan      html  css  js  c++  java
  • 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当做用例。

  • 相关阅读:
    MySQL Server类型的MySQL 客户端的下载、安装和使用
    Sqoop学习笔记
    Sqoop安装部署
    Hive学习笔记
    HBase构架原理
    HBase HA分布式集群搭建
    IntelliJ IDEA(Community版本)本地模式的下载、安装及其使用
    Scala本地安装
    CALayer的隐式动画和显式动画
    简易动画两种执行方式
  • 原文地址:https://www.cnblogs.com/superhin/p/12763702.html
Copyright © 2011-2022 走看看