Python: Standard Library - test module

One way is to develop high-quality software development test code for each function, and often tested during development

doctest module provides a tool for scanning a module and program embedded in the document string test is performed in accordance with.

Test construction is as simple it is cut and pasted into the output document string.

Examples provided by the user, it reinforces the document allows the doctest module to make sure the code is consistent with the document:

def average(values):
“”"Computes the arithmetic mean of a list of numbers.

>>> print(average([20, 30, 70]))
40.0
"""
return sum(values) / len(values)

the doctest Import
doctest.testmod () # embedded automatic verification tests

Unlike doctest module unittest module so easy to use, but it can provide a more comprehensive set of tests in a separate file:

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

Guess you like

Origin blog.csdn.net/weixin_44523387/article/details/92164972