# Python : Testing : unittest #### Overview - **test fixture** — Represents the preparation needed to perform one or more tests, and any associated cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process. - **test case** — The individual unit of testing. It checks for a specific response to a particular set of inputs. Provides class `TestCase` which may be used to create new test cases. - **test suite** — A collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together. - **test runner** — A component which orchestrates the execution of tests and provides the outcome to the user. The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests. Each `test_*` method is a test. A new instance of each test class is created for each test run. ```python import unittest #@unittest.skip( "...reason..." ) #@unittest.skipIf( <condition>, "...reason..." ) #@unittest.skipUnless( <condition>, "...reason..." ) class TestFoo( unittest.TestCase ): def setUpClass( self ): # before any tests def setUp( self ): # before each test ... def tearDownClass( self ): def tearDown( self ): ... #@unittest.skip*( ... ) def test_foo1( self ): ... self.assertEqual( ..., ... ) def test_foo2( self ): ... unittest.main() ``` ```bash $ python -m unittest [options] <module> ... $ python -m unittest [options] <module>.<TestClass> ... $ python -m unittest [options] <module>.<TestClass>.<test_method> ... $ python -m unittest [options] <path> $ python -m unittest [options] discover [discover_options] ``` ``` -b | --buffer stdout/stderr buffered during test run; output from passing tests is discarded -f | --failfast step on first error or failure --locals show local vars in tracebacks -v | --verbose # discover_options -s | --start-directory <path> default: "." -p | --patern <pattern> default: "test*.py" ``` #### Assertions ```python self.assertEqual( ..., ..., msg=None ) self.assertNotEqual( ..., ..., msg=None ) self.assertTrue( ..., msg=None ) self.assertFalse( ..., msg=None ) self.assertIs( ..., ..., msg=None ) self.assertIsNot( ..., ..., msg=None ) self.assertIsNone( ..., msg=None ) self.assertIsNotNone( ..., msg=None ) self.assertIn( ..., ..., msg=None ) self.assertNotIn( ..., ..., msg=None ) self.assertIsInstance( ..., ..., msg=None ) self.assertNotIsInstance( ..., ..., msg=None ) ...many more... with self.assertRaises( <error> ): ... with self.assertRaisesRegex( <error>, "pattern" ): ... ``` Also... - `unittest.IsolatedAsyncioTestCase`