Basic example
1 import unittest 2 3 class TestStringMethods(unittest.TestCase): 4 5 def test_upper(self): 6 self.assertEqual('foo'.upper(), 'FOO') 7 8 def test_isupper(self): 9 self.assertTrue('FOO'.isupper()) 10 self.assertFalse('Foo'.isupper()) 11 12 def test_split(self): 13 s = 'hello world' 14 self.assertEqual(s.split(), ['hello', 'world']) 15 # check that s.split fails when the separator is not a string 16 with self.assertRaises(TypeError): 17 s.split(2) 18 19 if __name__ == '__main__': 20 unittest.main()
The setUp()
and tearDown()
methods allow you to define instructions that will be executed before and after each test method.
unittest.main()
provides a command-line interface to the test script
Command-Line Interface
1 python -m unittest test_module1 test_module2
2 python -m unittest test_module.TestClass
3 python -m unittest test_module.TestClass.test_method
You can pass in a list with any combination of module names, and fully qualified class or method names.
Organizing test code
Tests can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called setUp()
, which the testing framework will automatically call for every single test we run:
1 import unittest 2 3 class WidgetTestCase(unittest.TestCase): 4 def setUp(self): 5 self.widget = Widget('The widget') 6 7 def test_default_widget_size(self): 8 self.assertEqual(self.widget.size(), (50,50), 9 'incorrect default size') 10 11 def test_widget_resize(self): 12 self.widget.resize(100,150) 13 self.assertEqual(self.widget.size(), (100,150), 14 'wrong size after resize')
tearDown()
method that tidies up after the test method has been run
If setUp()
succeeded, tearDown()
will be run whether the test method succeeded or not