python-unittest

Posted .Tang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-unittest相关的知识,希望对你有一定的参考价值。

1. unittest.TestCase类中的常用的断言方法

方法用途
assertEqual(a, b) 核实 a == b
assertNotEqual(a, b) 核实 a != b
assertTrue(x) 核实 x 为True
assertFalse(x) 核实 x 为False
assertIn(itemlist) 核实itemlist
assertNotIn(itemlist) 核实item不在list

 

1.1 子测试:记录错误并测试完所有的代码

class DemoTest(unittest.TestCase):
    def test_subtest(self):
        for i in range(5):
            with self.subTest(name=i):  # 子测试参数用于输出
                self.assertEqual(i % 2, 0)

>>>
(djProj_py3) appledeMacBook-Air-7:tests apple$ python -m unittest test_a.DemoTest.test_subtest

======================================================================
FAIL: test_subtest (test_a.DemoTest) (name=1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/apple/PycharmProjects/work/practice/tests/test_a.py", line 19, in test_subtest
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

======================================================================
FAIL: test_subtest (test_a.DemoTest) (name=3)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/apple/PycharmProjects/work/practice/tests/test_a.py", line 19, in test_subtest
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=2)

 

1.2测试套件:将多个用例或套件的实例组合起来,完成产品功能组级别的测试。

分别为每个参与测试方法创建实例,并加入套件。

class UserTest(unittest.TestCase):

    def test_user(self):
        self.assertTrue(True)  # 判断是否为真


class CartTest(unittest.TestCase):

    def test_cart(self):
        self.assertFalse(False)


suite = unittest.TestSuite()
suite.addTests((UserTest(test_user),  # 创建实例并加入套件suite
               CartTest(test_cart),)
               )
unittest.TextTestRunner(verbosity=2).run(suite)

# code end!!
>>> (djProj_py3) appledeMacBook-Air-7:tests apple$ python test_a.py test_user (__main__.UserTest) ... ok test_cart (__main__.CartTest) ... ok ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK

批量测试单个用例,可通过重写runTest

class TestDamo(unittest.TestCase):
    def add(self):
        self.assertTrue(1)

    def add1(self):
        self.assertFalse(‘‘)

    def runTest(self):
        tests = (self.add, self.add1)
        for test in tests:
            with self.subTest(t=test):
                test()

>>>
(djProj_py3) appledeMacBook-Air-7:tests apple$ python -m unittest -v test_a.py 
runTest (test_a.TestDamo) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

 


以上是关于python-unittest的主要内容,如果未能解决你的问题,请参考以下文章

python——unittest(单元测试)

Python Unittest Discover即使失败也返回退出代码0

Python接口测试之unittest框架

Python unittest模块心得

Python接口测试之unittest

python 单元测试,unittest 测试框架