Skip to content

Instantly share code, notes, and snippets.

@typoman
Created August 19, 2020 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save typoman/26a877de86fae8b82429a88d467ea88f to your computer and use it in GitHub Desktop.
Save typoman/26a877de86fae8b82429a88d467ea88f to your computer and use it in GitHub Desktop.
Python Testing Using UnitTest Cheatsheet

Unittest structure

import unittest

class TestAModule(unittest.TestCase):

    def setUp(self):
        # create test data
        pass

    def tearDown(self):
        # delete test data
        pass

    def test_equal(self):
        self.assertEqual('hello world'.split(), ['hello', 'world'])

    def test_true(self):
        self.assertTrue('FOO'.isupper())

    def test_fail_case(self):
        with self.assertRaises(TypeError):
            'text'.split(2) # check that s.split fails when the separator is not a string

    def test_fail_message(self):
        with self.assertRaisesRegex(TypeError, "must be str or None, not in"):
            'text'.split(2) # check that s.split fails when the separator is not a string

if __name__ == '__main__':
    unittest.main()

Comparing and type checking

Method Checks that
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a, b) a is b
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)
assertAlmostEqual(a, b) round(a-b, 7) == 0
assertNotAlmostEqual(a, b) round(a-b, 7) != 0
assertGreater(a, b) a > b
assertGreaterEqual(a, b) a >= b
assertLess(a, b) a < b
assertLessEqual(a, b) a <= b
assertRegex(s, r) r.search(s)
assertNotRegex(s, r) not r.search(s)
assertCountEqual(a, b) a and b have the same elements in the same number, regardless of their order.

Checking value types

Method Used to compare
assertMultiLineEqual(a, b) strings
assertSequenceEqual(a, b) sequences
assertListEqual(a, b) lists
assertTupleEqual(a, b) tuples
assertSetEqual(a, b) sets or frozensets
assertDictEqual(a, b) dicts

Error handling

Check if a func raises an exception:

Method
assertRaises(RuntimeError, func, *args, **kwargs)
assertRaisesRegex(RuntimeError, "error message", func, *args, **kwargs)
assertWarns(DeprecationWarning, func, *args, **kwargs)
assertWarnsRegex(DeprecationWarning, "warning message", func, *args, **kwargs)
with self.assertRaises(SomeException):
    do_something()

Bulk testing using tox in shell

> pip install tox
> cd package_folder
> tox
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment