Bird
Raised Fist0
PyTesttesting~20 mins

Checking exception attributes in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Exception Attribute 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 exception attribute check?
Consider the following pytest test code. What will be the value of exc_info.value.args[0] after the test runs?
PyTest
import pytest

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError) as exc_info:
        result = 1 / 0
    assert exc_info.value.args[0] == 'division by zero'
    print(exc_info.value.args[0])
A"division by zero"
B"ZeroDivisionError"
C"float division by zero"
DIndexError
Attempts:
2 left
💡 Hint
Check the message stored in the exception's args attribute.
❓ assertion
intermediate
2:00remaining
Which assertion correctly checks the exception message in pytest?
You want to verify that a ValueError is raised with the message 'invalid input'. Which assertion line is correct inside a pytest test using pytest.raises?
PyTest
import pytest

def test_invalid_input():
    with pytest.raises(ValueError) as exc_info:
        raise ValueError('invalid input')
    # Which assertion below is correct?
Aassert exc_info.value.args == ('invalid input',)
Bassert exc_info.value.message == 'invalid input'
Cassert str(exc_info.value) == 'invalid input'
Dassert exc_info.message == 'invalid input'
Attempts:
2 left
💡 Hint
Use the string representation of the exception to check the message.
🔧 Debug
advanced
2:00remaining
Why does this pytest exception attribute check fail?
This test is supposed to check the exception message but fails. What is the cause?
PyTest
import pytest

def test_key_error():
    with pytest.raises(KeyError) as exc_info:
        raise KeyError('missing_key')
    assert exc_info.value.args[0] == 'missing_key'
    assert str(exc_info.value) == 'missing_key'

# The test fails on the second assertion.
AThe args attribute is empty, so args[0] raises IndexError
BThe string representation of KeyError includes quotes, so str(exc_info.value) is "'missing_key'" not "missing_key"
CKeyError does not have args attribute
DThe exception was not raised, so exc_info is None
Attempts:
2 left
💡 Hint
Print the string form of the exception to see its exact content.
🧠 Conceptual
advanced
1:30remaining
What attribute of the pytest exception info object holds the caught exception instance?
When using with pytest.raises(SomeError) as exc_info:, which attribute of exc_info contains the actual exception instance?
Aexc_info.value
Bexc_info.type
Cexc_info.message
Dexc_info.args
Attempts:
2 left
💡 Hint
The exception instance is stored in an attribute named 'value'.
❓ framework
expert
3:00remaining
How to correctly check multiple exception attributes in pytest?
You want to test that a function raises a RuntimeError with message 'fail' and has a custom attribute code equal to 500. Which pytest test code is correct?
PyTest
import pytest

class CustomError(RuntimeError):
    def __init__(self, message, code):
        super().__init__(message)
        self.code = code

def func():
    raise CustomError('fail', 500)

# Which test below is correct?
A
def test_func():
    with pytest.raises(RuntimeError) as exc_info:
        func()
    assert exc_info.value.args[0] == 'fail'
    assert exc_info.code == 500
B
def test_func():
    with pytest.raises(CustomError) as exc_info:
        func()
    assert exc_info.value.args == ('fail', 500)
    assert exc_info.value.code == 500
C
def test_func():
    with pytest.raises(CustomError) as exc_info:
        func()
    assert exc_info.message == 'fail'
    assert exc_info.value.code == 500
D
def test_func():
    with pytest.raises(CustomError) as exc_info:
        func()
    assert str(exc_info.value) == 'fail'
    assert exc_info.value.code == 500
Attempts:
2 left
💡 Hint
Check the exception instance's string and custom attribute separately.

Practice

(1/5)
1. What is the correct way to capture an exception and check its message using pytest.raises?
easy
A. Use pytest.raises(ValueError) as exc_info: outside a with block.
B. Use pytest.raises(ValueError) without as exc_info and check exc_info.message.
C. Use with pytest.raises() as exc_info: and check exc_info.error.
D. Use with pytest.raises(ValueError) as exc_info: and then check exc_info.value.

Solution

  1. Step 1: Use pytest.raises with as exc_info

    This syntax captures the exception info object for inspection.
  2. Step 2: Access the exception instance via exc_info.value

    The actual exception object is stored in exc_info.value, allowing attribute checks like the message.
  3. Final Answer:

    Use with pytest.raises(ValueError) as exc_info: and then check exc_info.value. -> Option D
  4. Quick Check:

    Exception captured = exc_info.value [OK]
Hint: Always use 'as exc_info' to access exception details [OK]
Common Mistakes:
  • Not using 'as exc_info' to capture exception
  • Trying to access exc_info.message instead of exc_info.value
  • Using pytest.raises outside a with block
2. Which of the following is the correct syntax to check the exception message text inside a pytest test?
easy
A. assert exc_info.message == 'error occurred'
B. assert exc_info.value.message == 'error occurred'
C. assert str(exc_info.value) == 'error occurred'
D. assert exc_info.error == 'error occurred'

Solution

  1. Step 1: Access exception instance via exc_info.value

    The exception object is stored in exc_info.value.
  2. Step 2: Convert exception to string to get message

    Using str(exc_info.value) returns the exception message text.
  3. Final Answer:

    assert str(exc_info.value) == 'error occurred' -> Option C
  4. Quick Check:

    Exception message = str(exc_info.value) [OK]
Hint: Use str(exc_info.value) to get exception message text [OK]
Common Mistakes:
  • Trying to access exc_info.message which does not exist
  • Using exc_info.error which is invalid
  • Assuming exc_info.value.message always exists
3. Given the code below, what will the assertion check inside the test?
def divide(x, y):
    if y == 0:
        raise ZeroDivisionError('Cannot divide by zero')
    return x / y

def test_divide():
    with pytest.raises(ZeroDivisionError) as exc_info:
        divide(5, 0)
    assert str(exc_info.value) == 'Cannot divide by zero'
medium
A. The test raises an error because exc_info is not defined.
B. The test passes because the exception message matches exactly.
C. The test fails because the exception message is different.
D. The test fails because the exception type is wrong.

Solution

  1. Step 1: The function raises ZeroDivisionError with correct message

    Calling divide(5, 0) raises ZeroDivisionError with message 'Cannot divide by zero'.
  2. Step 2: The test captures exception and asserts message

    Using pytest.raises captures the exception, and str(exc_info.value) matches the expected message.
  3. Final Answer:

    The test passes because the exception message matches exactly. -> Option B
  4. Quick Check:

    Exception type and message match = pass [OK]
Hint: Match exception message string exactly with str(exc_info.value) [OK]
Common Mistakes:
  • Assuming exception message is accessed by exc_info.message
  • Not using 'as exc_info' to capture exception
  • Confusing exception type with message
4. Identify the error in the following pytest test code that checks exception attributes:
def test_error():
    with pytest.raises(ValueError) as exc_info:
        raise ValueError('Invalid input')
    assert exc_info.message == 'Invalid input'
medium
A. Using exc_info.message instead of str(exc_info.value) to check message.
B. Not raising the exception inside the with block.
C. Missing parentheses in pytest.raises call.
D. Using as exc_info outside the with block.

Solution

  1. Step 1: Check how exception message is accessed

    The exception message is not stored in exc_info.message, but must be accessed via str(exc_info.value).
  2. Step 2: Correct assertion syntax

    Replace assert exc_info.message == 'Invalid input' with assert str(exc_info.value) == 'Invalid input'.
  3. Final Answer:

    Using exc_info.message instead of str(exc_info.value) to check message. -> Option A
  4. Quick Check:

    Exception message accessed via str(exc_info.value) [OK]
Hint: Use str(exc_info.value) to get exception message, not exc_info.message [OK]
Common Mistakes:
  • Trying to access exc_info.message which does not exist
  • Not raising exception inside with block
  • Incorrect pytest.raises syntax
5. You want to test a custom exception MyError that has an attribute code. Which pytest code correctly checks both the exception type and the code attribute value?
hard
A. with pytest.raises(MyError) as exc_info: raise MyError('fail', code=404) assert exc_info.value.code == 404
B. with pytest.raises(MyError) as exc_info: raise MyError('fail', code=404) assert exc_info.code == 404
C. with pytest.raises(MyError): raise MyError('fail', code=404) assert exc_info.value.code == 404
D. with pytest.raises(MyError) as exc_info: raise MyError('fail', code=404) assert str(exc_info.value) == 404

Solution

  1. Step 1: Capture exception with as exc_info

    This allows access to the exception instance and its attributes.
  2. Step 2: Access custom attribute code on exc_info.value

    The exception instance is exc_info.value, so exc_info.value.code accesses the attribute.
  3. Final Answer:

    with pytest.raises(MyError) as exc_info: raise MyError('fail', code=404) assert exc_info.value.code == 404 -> Option A
  4. Quick Check:

    Custom attribute checked via exc_info.value.code [OK]
Hint: Check custom attributes on exc_info.value, not exc_info directly [OK]
Common Mistakes:
  • Trying to access exc_info.code instead of exc_info.value.code
  • Not using 'as exc_info' to capture exception
  • Comparing str(exc_info.value) to a number
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard