Python assertIn()

Summary: in this tutorial, you’ll learn how to use the Python assertIn() method to test if a member is in a container.

Introduction to the Python assertIn() method

The assertIn() is a method of the TestCase class of the unittest module. The assertIn() method tests if a member is in a container:

assertIn(member, container, msg=None)Code language: Python (python)

If the member is in the container, the test will pass. Otherwise, it’ll fail. The msg is optional. It’ll be displayed in the test result when the test fails.

Internally, the assertIn() method uses the in operator to check:

member in containerCode language: Python (python)

Python assertIn() method examples

The following example uses the assertIn() method to test if a number is in a list and a string is in another string:

import unittest


class TestIn(unittest.TestCase):
    def test_in_list(self):
        self.assertIn(1, [1, 2, 3])

    def test_in_string(self):
        self.assertIn('python', 'python tutorial')Code language: Python (python)

Run the test:

python -m unittest -vCode language: Python (python)

Output:

test_in_list (test_in.TestIn) ... ok
test_in_string (test_in.TestIn) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.001s

OKCode language: Python (python)

Python assertNotIn() method

The assertNotIn() method is the opposite of the assertIn() method. The assertNotIn() method tests if a member is not in a container:

assertNotIn(member, container, msg=None)Code language: Python (python)

For example:

import unittest


class TestNotIn(unittest.TestCase):
    def test_not_in_list(self):
        self.assertNotIn(0, [1, 2, 3])

    def test_not_in_string(self):
        self.assertNotIn('java', 'python tutorial')Code language: Python (python)

Run the test:

python -m unittest -vCode language: Python (python)

Output:

test_not_in_list (test_not_in.TestNotIn) ... ok
test_not_in_string (test_not_in.TestNotIn) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OKCode language: Python (python)

Summary

  • Use the assertIn() method to test if a member is in a container.
  • Use the assertNotIn() method to test if a member is not in a container.
Did you find this tutorial helpful ?