0
0
PyTesttesting~5 mins

Checking membership (in, not in) in PyTest

Choose your learning style9 modes available
Introduction

We check if something is inside a group or not. This helps us confirm if data is where it should be.

To verify if a username exists in a list of registered users.
To check if an error message appears in the output logs.
To confirm that a product ID is not in the list of discontinued items.
To ensure a keyword is present in a text response.
To test if a value is missing from a set of expected results.
Syntax
PyTest
assert item in collection
assert item not in collection

item is what you want to find.

collection can be a list, string, set, or other container.

Examples
Check if 'apple' is in the list of fruits.
PyTest
assert 'apple' in ['apple', 'banana', 'cherry']
Check that the word 'error' is not in the message string.
PyTest
assert 'error' not in 'All tests passed successfully'
Check if number 5 is in the set of numbers.
PyTest
assert 5 in {1, 3, 5, 7}
Sample Program

This test checks if certain items are in or not in collections. All assertions should pass.

PyTest
import pytest

def test_membership():
    fruits = ['apple', 'banana', 'cherry']
    message = 'All tests passed successfully'
    numbers = {1, 3, 5, 7}

    assert 'banana' in fruits
    assert 'error' not in message
    assert 5 in numbers
    assert 'grape' not in fruits
OutputSuccess
Important Notes

Using in and not in makes tests easy to read and understand.

These checks work with many types like lists, strings, sets, and tuples.

Failed assertions will show which item was missing or wrongly present.

Summary

Use in to check if an item is inside a collection.

Use not in to check if an item is not inside a collection.

These checks help confirm data presence or absence simply and clearly.