Python Test使用

    • python自带的单元测试模块
      • test_listpy
      • test_with_suit
      • test_skippy
      • test_docpy

python自带的单元测试模块

unittest doctest

test_list.py

# -*- coding: utf-8 -*-
import unittest

class TestList(unittest.TestCase):
    def setUp(self):
        self.c_list = range(5)
        print("setup test module")

    def tearDown(self):
        del self.c_list
        print("teardown test module")

    def test_equal(self):
        print("test equal")
        c = self.c_list
        self.assertEqual(c, [0,1,2,3,4])

    def test_in(self):
        print("test in")
        c = self.c_list
        self.assertIn(1, c)

if __name__ == "__main__":
    unittest.main()

每个以test开头的method都会被调用,调用之前会调用setUp方法,之后会调用tearDown方法

test_with_suit

# -*- coding: utf-8 -*-
import unittest

class TestList(unittest.TestCase):
    def setUp(self):
        self.c_list = range(5)
        print("setup test module")

    def tearDown(self):
        del self.c_list
        print("teardown test module")

    def test_equal(self):
        print("test equal")
        c = self.c_list
        self.assertEqual(c, [0,1,2,3,4])

    def test_in(self):
        print("test in")
        c = self.c_list
        self.assertIn(1, c)

if __name__ == "__main__":
    suite = unittest.TestSuite()
    suite.addTest(TestList("test_equal"))  
    suite.addTest(TestList("test_in"))
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)

使用TestSuite,可以让测试更细化,将需要测试的method放入suite中

test_skip.py

# -*- coding: utf-8 -*-
import unittest
SKIP = False
class TestList(unittest.TestCase):
    def setUp(self):
        self.c_list = range(5)
        print("setup test module")

    def tearDown(self):
        del self.c_list
        print("teardown test module")

    @unittest.skip("skip this test")
    def test_equal(self):
        print("test equal")
        c = self.c_list
        self.assertEqual(c, [0,1,2,3,4])

    @unittest.skipIf(SKIP==True, "skip this test with if")
    def test_in(self):
        print("test in")
        c = self.c_list
        self.assertIn(1, c)

if __name__ == "__main__":
    unittest.main()

可以让某个测试方法直接跳过,或者使用@unittestskipIf,@unittest.skipUnless装饰器,控制测试的数量

test_doc.py

# -*- coding: utf-8 -*-

def double(num):
    """ This function calculate positive integer square value.

    Example:

        >>> double(10)
        100
        >>> double(-1)
        Traceback (most recent call last):
        ...
        ValueError: the num must is positive integer
    """

    if num < 0:
        raise ValueError('the num must is positive integer')
    return num**2

if __name__ == "__main__":
    import doctest
    doctest.testmod()

如果没有输出,就说明是测试时正确的

Github地址
(于2017年4月8日,http://blog.csdn.net/bzd_111)

你可能感兴趣的:(python)