0
0
PyTesttesting~15 mins

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

Choose your learning style9 modes available
Verify identity comparison using 'is' and 'is not' operators
Preconditions (2)
Step 1: Create two variables a and b referencing the same list object
Step 2: Create a third variable c referencing a different list object with the same content
Step 3: Use 'is' operator to check if a and b are the same object
Step 4: Use 'is not' operator to check if a and c are not the same object
Step 5: Assert that a is b returns True
Step 6: Assert that a is not c returns True
✅ Expected Result: The test passes confirming that 'is' correctly identifies identical objects and 'is not' correctly identifies different objects
Automation Requirements - pytest
Assertions Needed:
Assert that 'a is b' is True
Assert that 'a is not c' is True
Best Practices:
Use clear variable names
Use pytest assert statements
Keep test functions small and focused
Add comments explaining identity checks
Automated Solution
PyTest
import pytest

def test_identity_operators():
    # Two variables referencing the same list object
    a = [1, 2, 3]
    b = a
    # A different list object with the same content
    c = [1, 2, 3]

    # Assert that a and b are the same object
    assert a is b, "a and b should be the same object"
    # Assert that a and c are not the same object
    assert a is not c, "a and c should not be the same object"

This test defines three variables: a and b point to the same list object, while c points to a different list with the same content.

Using is checks if two variables point to the exact same object in memory. The assertion assert a is b confirms this.

Using is not checks if two variables do not point to the same object. The assertion assert a is not c confirms that although a and c have the same content, they are different objects.

Comments explain each step clearly for beginners.

Common Mistakes - 3 Pitfalls
{'mistake': "Using '==' instead of 'is' to check identity", 'why_bad': "'==' checks value equality, not if two variables point to the same object", 'correct_approach': "Use 'is' to check if two variables reference the same object"}
{'mistake': "Comparing mutable objects with 'is' expecting value equality", 'why_bad': "'is' only checks object identity, not content equality, which can cause confusion", 'correct_approach': "Use '==' for content equality and 'is' for identity checks"}
{'mistake': 'Not assigning variables properly leading to unexpected identity results', 'why_bad': "If variables do not reference the same object, 'is' will fail even if contents match", 'correct_approach': 'Explicitly assign variables to the same object when testing identity'}
Bonus Challenge

Now add data-driven testing with 3 different pairs of variables to check identity and non-identity

Show Hint