0
0
PyTesttesting~20 mins

Checking identity (is, is not) in PyTest - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Identity Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this pytest assertion?
Consider the following pytest test function. What will be the result of running this test?
PyTest
def test_identity():
    a = [1, 2, 3]
    b = a
    assert a is b
ATypeError at runtime
BTest fails with AssertionError
CSyntaxError at runtime
DTest passes
Attempts:
2 left
💡 Hint
Remember that 'is' checks if two variables point to the same object in memory.
Predict Output
intermediate
2:00remaining
What happens when comparing two identical lists with 'is'?
What will be the result of this pytest test function?
PyTest
def test_identity_lists():
    a = [1, 2, 3]
    b = [1, 2, 3]
    assert a is not b
ASyntaxError at runtime
BTest passes
CNameError at runtime
DTest fails with AssertionError
Attempts:
2 left
💡 Hint
Two lists with the same content are different objects unless assigned explicitly.
assertion
advanced
2:00remaining
Which assertion correctly checks that two variables do NOT refer to the same object?
You want to write a pytest assertion to confirm that variables 'x' and 'y' are different objects. Which option is correct?
Aassert x is not y
Bassert x != y
Cassert x is y
Dassert x == y
Attempts:
2 left
💡 Hint
Remember 'is not' checks identity, while '!=' checks value equality.
🔧 Debug
advanced
2:00remaining
Why does this pytest assertion fail unexpectedly?
Given the code below, why does the assertion fail?
PyTest
def test_identity_failure():
    a = 256
    b = 256
    assert a is b

def test_identity_failure2():
    x = 257
    y = 257
    assert x is y
AThe assertion fails because 'is' compares values, not objects
BThe assertion fails because variables 'x' and 'y' are not defined
CPython caches small integers, so 'a is b' is True for 256 but not for 257
DThe assertion fails due to a syntax error in the code
Attempts:
2 left
💡 Hint
Python caches small integers from -5 to 256 for performance.
framework
expert
3:00remaining
How to write a pytest test that checks identity and reports a clear message on failure?
You want to write a pytest test that asserts two variables 'obj1' and 'obj2' are the same object. If they are not, the test should fail with the message: "Objects are not identical". Which code snippet achieves this?
A
def test_obj_identity():
    assert obj1 is obj2, "Objects are not identical"
B
def test_obj_identity():
    assert obj1 == obj2, "Objects are not identical"
C
def test_obj_identity():
    assert obj1 is not obj2, "Objects are not identical"
D
def test_obj_identity():
    assert obj1 != obj2, "Objects are not identical"
Attempts:
2 left
💡 Hint
Use 'is' for identity and provide a message after the comma in assert.