Testing in Python
There are many ways to write unit tests in Python. unittest Here the focus is living off the land with built-in unittest. unittest is both a framework and test runner, meaning it can execute your tests and return the results. In order to write unittest tests, you must: Write your tests as methods within classes These TestCase classes must subclass unittest.TestCase Names of test functions must begin with test_ Import the code to be tested Use a series of built-in assertion methods Basic example import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) # check that s.split fails when the separator is not a string with self.assertRaises(TypeError): s.split(2) if __name__ == '__main__': unittest.main() Assertions The TestCase class provides several assert methods to check for and report failures. ...