Verify membership of elements in a list using 'in' and 'not in'
Preconditions (2)
✅ Expected Result: The test passes confirming 'banana' is in the list and 'orange' is not in the list
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.
Now add data-driven testing with 3 different fruits lists and check membership for 'banana' and 'orange'
'apple' is in the list fruits = ['apple', 'banana', 'cherry'] using pytest assertions?in keyword checks if an item exists inside a collection like a list.assert 'apple' in fruits. This passes if 'apple' is found.in to check presence [OK]5 is NOT in the list numbers = [1, 2, 3, 4] using pytest?not in keyword.assert 5 not in numbers. This passes if 5 is absent.items = ['pen', 'pencil', 'eraser'] assert 'marker' not in items
colors = ['red', 'green', 'blue'] assert 'yellow' in colors not
['spam', 'scam', 'fraud'] appear in the user input string text. Which assertion correctly checks this?all(word not in text for word in forbidden_words) returns True only if every word is not in text.Pass the test and this pattern moves unknown