0
0
PyTesttesting~15 mins

Checking membership (in, not in) in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify membership of elements in a list using 'in' and 'not in'
Preconditions (2)
Step 1: Create a list named 'fruits' containing ['apple', 'banana', 'cherry']
Step 2: Check if 'banana' is in the list 'fruits'
Step 3: Check if 'orange' is not in the list 'fruits'
Step 4: Assert that 'banana' is found in the list
Step 5: Assert that 'orange' is not found in the list
✅ Expected Result: The test passes confirming 'banana' is in the list and 'orange' is not in the list
Automation Requirements - pytest
Assertions Needed:
Assert 'banana' in fruits
Assert 'orange' not in fruits
Best Practices:
Use clear and descriptive test function names
Use assert statements directly for membership checks
Keep test code simple and readable
Automated Solution
PyTest
import pytest

def test_membership_in_list():
    fruits = ['apple', 'banana', 'cherry']
    # Check if 'banana' is in the list
    assert 'banana' in fruits, "Expected 'banana' to be in the fruits list"
    # Check if 'orange' is not in the list
    assert 'orange' not in fruits, "Expected 'orange' to not be in the fruits list"

This test function test_membership_in_list creates a list called fruits with three items.

It uses assert statements to check membership:

  • 'banana' in fruits confirms 'banana' is present.
  • 'orange' not in fruits confirms 'orange' is absent.

If either assertion fails, pytest will show a clear message explaining what was expected.

This keeps the test simple, readable, and easy to maintain.

Common Mistakes - 3 Pitfalls
{'mistake': "Using '==' to check membership instead of 'in'", 'why_bad': 'It only compares one element, not membership in a collection', 'correct_approach': "Use 'in' keyword to check if an element exists in a list or collection"}
Not providing assertion messages
Checking membership on wrong variable or empty list
Bonus Challenge

Now add data-driven testing with 3 different fruits lists and check membership for 'banana' and 'orange'

Show Hint