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)ordelta=: floating-point comparisons, since0.1 + 0.2 != 0.3.assertGreater,assertLess,assertGreaterEqual...assertCountEqual(a, b): same elements regardless of order.assertRegex(text, pattern).assertDictEqual,assertListEqualand friends are used automatically byassertEqualfor 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.