python质量控制

        一种编写高质量软件的方式是给代码中每个函数写测试,在开发过程中经常性的进行测试。

        doctest模块可以在docstring中嵌套测试代码。例如:
  1. def average(values):
      """Computes the arithmetic mean of a list of numbers.
      >>> print average([20, 30, 70])
       40.0
       """
       return sum(values,0.0)/ len(values)
    import doctest
    doctest.testmod()# automatically validate the embedded tests
        unittest模块提供的测试没有doctest的那么有那效率,但是它可以提供更加详细的测试。
  1. import unittest
    
    class TestStatisticalFunctions(unittest.TestCase):
    
        def test_average(self):
            self.assertEqual(average([20, 30, 70]), 40.0)
            self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
            self.assertRaises(ZeroDivisionError, average, [])
            self.assertRaises(TypeError, average, 20, 30, 70)
    
    unittest.main() # Calling from the command line invokes all tests



原文地址:https://www.cnblogs.com/fireflow/p/4864818.html