Debug School

rakesh kumar
rakesh kumar

Posted on

listout checklist of all assert methods to check for and report failures in unittest

In unittest, you can use various assert methods to check for and report failures in your test cases. These assert methods allow you to verify if specific conditions are met during testing. Here's a checklist of common assert methods along with examples and expected output for each:

Checklist of Assert Methods in unittest

assertEqual(a, b) - Check if a is equal to b.
assertNotEqual(a, b) - Check if a is not equal to b.
assertTrue(x) - Check if x is True.
assertFalse(x) - Check if x is False.
assertIsNone(x) - Check if x is None.
assertIsNotNone(x) - Check if x is not None.
assertIn(a, b) - Check if a is in b.
assertNotIn(a, b) - Check if a is not in b.
assertGreater(a, b) - Check if a is greater than b.
assertGreaterEqual(a, b) - Check if a is greater than or equal to b.
assertLess(a, b) - Check if a is less than b.
assertLessEqual(a, b) - Check if a is less than or equal to b.
Enter fullscreen mode Exit fullscreen mode

Example and Expected Output:

import unittest

class TestAssertions(unittest.TestCase):
    def test_equal(self):
        self.assertEqual(2 + 2, 4)

    def test_not_equal(self):
        self.assertNotEqual(3 * 5, 12)

    def test_true(self):
        self.assertTrue(True)

    def test_false(self):
        self.assertFalse(False)

    def test_is_none(self):
        self.assertIsNone(None)

    def test_is_not_none(self):
        self.assertIsNotNone("Hello")

    def test_in(self):
        items = [1, 2, 3, 4, 5]
        self.assertIn(3, items)

    def test_not_in(self):
        items = ["apple", "banana", "cherry"]
        self.assertNotIn("grape", items)

    def test_greater(self):
        self.assertGreater(10, 5)

    def test_greater_equal(self):
        self.assertGreaterEqual(7, 7)

    def test_less(self):
        self.assertLess(3, 6)

    def test_less_equal(self):
        self.assertLessEqual(4, 4)

if __name__ == '__main__':
    unittest.main()
Enter fullscreen mode Exit fullscreen mode

Expected Output:

When you run the above tests, the output will indicate which tests passed (indicated by "."), and if any test fails, it will display "F" to indicate failure.

Expected output for the example:

............
----------------------------------------------------------------------
Ran 12 tests in 0.002s

OK
Enter fullscreen mode Exit fullscreen mode

In this output, all 12 tests pass, as indicated by the "OK" message at the end. If any test were to fail, it would be marked with an "F," and the reason for failure would be displayed in the output.

Image description

Image description

Image description

Refrence

Top comments (0)