Assertion methods

unittest · Essentials · 9 min

A precise assertion turns a failing test into an instant diagnosis instead of 'False is not true'.

TestCase has many assertion methods. Using the most specific one gives the best failure message.

  • assertEqual(a, b) / assertNotEqual: for lists, dicts, sets and multi-line strings it shows a diff.
  • assertTrue(x) / assertFalse(x): only for genuinely boolean checks; assertTrue(a == b) just says "False is not true".
  • assertIs(a, b), assertIsNone(x), assertIsNotNone(x): identity.
  • assertIn(item, container), assertNotIn.
  • assertIsInstance(obj, cls).
  • assertAlmostEqual(a, b, places=7) or delta=: floating-point comparisons, since 0.1 + 0.2 != 0.3.
  • assertGreater, assertLess, assertGreaterEqual...
  • assertCountEqual(a, b): same elements regardless of order.
  • assertRegex(text, pattern).
  • assertDictEqual, assertListEqual and friends are used automatically by assertEqual for those types.

Every method takes an optional msg= argument added to the failure output, which is useful in loops. self.fail("reason") fails unconditionally.

Convention: put the actual value first and the expected value second; the diff output labels them as first and second, so consistency helps when reading failures.

Example

import unittest

class TestExamples(unittest.TestCase):
    def test_float(self):
        self.assertAlmostEqual(0.1 + 0.2, 0.3)            # passes

    def test_unordered(self):
        self.assertCountEqual([3, 1, 2], [1, 2, 3])      # passes

    def test_dict_diff(self):
        self.assertEqual({"a": 1, "b": 2}, {"a": 1, "b": 3})

unittest.main(exit=False, argv=["x", "-q"])
# FAIL: test_dict_diff ...
# AssertionError: {'a': 1, 'b': 2} != {'a': 1, 'b': 3}
# - {'a': 1, 'b': 2}
# ?               ^
# + {'a': 1, 'b': 3}
# ?               ^

Remember

  • Use the most specific assert method for the best failure message
  • assertAlmostEqual for floats, assertCountEqual for order-independent comparisons
  • assertEqual shows diffs for containers and long strings

Watch out for

  • assertTrue(result == expected), which hides both values in the failure message.

Check yourself

  1. Which assertion is right for checking a computed float like 0.1 + 0.2 against 0.3?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/unittest.html#assert-methods