## doctest模块 import doctest def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) doctest.testmod() # 自动验证嵌入测试 >强化文档,允许 doctest 模块确认代码的结果是否与文档一致: ## unittest模块 import unittest def average(values): return sum(values) / len(values) #创建一个用于测试的类 class TestFunction(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) # 传入函数和结果 self.assertRaises(ZeroDivisionError, average, []) self.assertRaises(TypeError, average, 'as', 30, '70') unittest.main()