unittest

unittest supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework. The unittest module provides classes that make it easy to support these qualities for a set of tests.

calc.py


def plus(a,b):
    return a + b


def sub(a,b):
    return a - b


def times(a,b):
    return a * b


def div(a,b):
    if b == 0:
        raise TypeError('ZeroDivisionError')
    return a / b

calc_test.py

import unittest
import calc


class MyTest(unittest.TestCase):

    def test_add(self):  # the method name should be test + '_' + funcName or your won't be able to see the number of tests in results
        self.assertEqual(calc.plus(1,2),3)
        self.assertEqual(calc.plus(2,2),4)
        self.assertEqual(calc.plus(5,2),7)

    def test_sub(self):
        self.assertEqual(calc.sub(1,1),0)
        self.assertEqual(calc.sub(4,1),3)

    def test_times(self):
        self.assertEqual(calc.times(10,2),20)
        self.assertEqual(calc.times(4,2),8)
        self.assertEqual(calc.times(4,4),16)

    def test_div(self):
        self.assertEqual(calc.div(1,1),1)
        self.assertEqual(calc.div(6,3),2)
        self.assertEqual(calc.div(1,1),1)
        self.assertRaises(TypeError,calc.div,10,0)


if __name__ == '__main__':
    unittest.main()
#
output
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

Note that in order to test something, we use one of the assert*() methods provided by the TestCase base class. If the test fails, an exception will be raised, and unittest will identify the test case as a failure. Any other exceptions will be treated as errors. This helps you identify where the problem is: failures are caused by incorrect results - a 5 where you expected a 6. Errors are caused by incorrect code - e.g., a TypeError caused by an incorrect function call.

你可能感兴趣的:(unittest)