Labs ICT
โญ Pro Login

assertIn & assertNotIn

Testing membership in sequences and collections

assertIn & assertNotIn

assertIn(a, b) checks that element a is found in sequence b, while assertNotIn(a, b) checks that it is not. Perfect for testing membership in lists, strings, sets, and dictionaries.

Basic Usage

import unittest

class TestMembership(unittest.TestCase):
    def test_user_in_list(self):
        users = ["alice", "bob", "charlie"]
        self.assertIn("alice", users)

    def test_invalid_email_not_in_valid(self):
        valid_emails = ["a@test.com", "b@test.com"]
        self.assertNotIn("hacker@evil.com", valid_emails)

    def test_char_in_string(self):
        self.assertIn("P", "Python")

    def test_key_in_dict(self):
        config = {"debug": True, "version": "1.0"}
        self.assertIn("debug", config)

    def test_element_not_in_set(self):
        allowed = {1, 2, 3}
        self.assertNotIn(5, allowed)

With Custom Messages

def test_item_in_cart(self):
    cart = get_cart(user_id=1)
    self.assertIn(
        "laptop",
        [item.name for item in cart.items],
        "Laptop should be in the cart after adding it"
    )

Works With

  • Lists: assertIn("x", ["x", "y"])
  • Tuples: assertIn(1, (1, 2, 3))
  • Sets: assertIn("a", {"a", "b"})
  • Strings: assertIn("py", "python")
  • Dictionaries: checks keys โ€” assertIn("k", {"k": 1})

Key Takeaway

Use assertIn and assertNotIn to test membership in any iterable or collection. They work with lists, strings, sets, tuples, and dict keys.

๐Ÿงช Quick Quiz

Which assertion checks if an element is in a sequence?