Bird
Raised Fist0
PyTesttesting~20 mins

Asserting exceptions (pytest.raises) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Exception Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ assertion
intermediate
2:00remaining
Correct use of pytest.raises to catch ZeroDivisionError
What will be the result of this test when run with pytest?
PyTest
import pytest

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError):
        x = 1 / 0
ATest passes because ZeroDivisionError is correctly caught
BTest fails because ZeroDivisionError is not caught
CTest raises a SyntaxError due to incorrect pytest usage
DTest fails because the exception type is wrong
Attempts:
2 left
💡 Hint
Remember pytest.raises expects the exact exception type to catch.
❓ assertion
intermediate
2:00remaining
Detecting wrong exception type in pytest.raises
What happens when this test runs?
PyTest
import pytest

def test_value_error():
    with pytest.raises(KeyError):
        int('abc')
ATest fails because ValueError is raised, not KeyError
BTest passes because any exception is accepted
CTest raises a TypeError due to wrong exception type
DTest passes because KeyError is raised
Attempts:
2 left
💡 Hint
Check which exception int('abc') actually raises.
❓ Predict Output
advanced
2:00remaining
Output of pytest.raises context manager with exception info
What will be the value of 'exc_type' after running this test?
PyTest
import pytest

def test_exception_info():
    with pytest.raises(ValueError) as exc_info:
        raise ValueError('Invalid input')
    exc_type = exc_info.type
    print(exc_type.__name__)
ANone
BKeyError
CValueError
DTypeError
Attempts:
2 left
💡 Hint
exc_info.type holds the exception class caught by pytest.raises.
🔧 Debug
advanced
2:00remaining
Why does this pytest.raises test fail unexpectedly?
Identify why this test fails even though it seems to catch the exception.
PyTest
import pytest

def test_key_error():
    with pytest.raises(KeyError):
        d = {'a': 1}
        value = d['b']
        print('Accessed value:', value)
ATest fails because print statement is outside the with block
BTest fails because KeyError is not raised inside the with block
CTest fails because print statement executes after exception and causes error
DTest passes because KeyError is raised inside the with block
Attempts:
2 left
💡 Hint
Check where the exception is raised and if the with block covers it.
❓ framework
expert
3:00remaining
Using pytest.raises to assert exception message content
Which option correctly asserts that the exception message contains the word 'timeout'?
PyTest
import pytest

def test_timeout_error():
    with pytest.raises(RuntimeError) as exc_info:
        raise RuntimeError('Connection timeout occurred')
    # Assertion here
Aassert exc_info.value.message == 'timeout'
Bassert 'timeout' in str(exc_info.value)
Cassert exc_info.type == 'timeout'
Dassert exc_info.message.contains('timeout')
Attempts:
2 left
💡 Hint
Exception message is accessed via str(exc_info.value).

Practice

(1/5)
1. What is the main purpose of using pytest.raises in a test?
easy
A. To ignore exceptions and continue the test
B. To skip a test when an exception occurs
C. To print the exception message during test execution
D. To check if a specific exception is raised by the code inside the with block

Solution

  1. Step 1: Understand the role of pytest.raises

    pytest.raises is used to verify that a certain exception is raised by the code inside its with block.
  2. Step 2: Compare options with the purpose

    Only To check if a specific exception is raised by the code inside the with block correctly states that it checks for a specific exception. Other options describe unrelated behaviors.
  3. Final Answer:

    To check if a specific exception is raised by the code inside the with block -> Option D
  4. Quick Check:

    pytest.raises checks exceptions = A [OK]
Hint: Remember: pytest.raises confirms expected errors happen [OK]
Common Mistakes:
  • Thinking pytest.raises skips tests
  • Assuming it prints exceptions automatically
  • Believing it ignores exceptions
2. Which of the following is the correct syntax to assert that a ValueError is raised when calling func() using pytest.raises?
easy
A. pytest.raises(ValueError, func())
B. with pytest.raises(ValueError): func()
C. with pytest.raises('ValueError'): func()
D. pytest.raises(ValueError): func()

Solution

  1. Step 1: Recall correct pytest.raises syntax

    The correct way is to use a with statement with pytest.raises(ExceptionType): followed by the code that should raise the exception.
  2. Step 2: Evaluate each option

    with pytest.raises(ValueError): func() uses the correct with block and exception type. pytest.raises(ValueError, func()) calls the function inside the argument, which runs before checking. with pytest.raises('ValueError'): func() uses a string instead of the exception class. pytest.raises(ValueError): func() misses the with keyword.
  3. Final Answer:

    with pytest.raises(ValueError): func() -> Option B
  4. Quick Check:

    Use with + pytest.raises(Exception): code [OK]
Hint: Always use 'with pytest.raises(Exception):' before the code [OK]
Common Mistakes:
  • Calling the function inside pytest.raises() arguments
  • Using exception name as string instead of class
  • Omitting the 'with' keyword
3. What will be the output of the following test code?
import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError) as exc_info:
        1 / 0
    assert 'division by zero' in str(exc_info.value)
medium
A. Test passes because ZeroDivisionError is raised and message matches
B. Test fails because exception message is not checked correctly
C. Test fails because ZeroDivisionError is not raised
D. SyntaxError due to incorrect use of pytest.raises

Solution

  1. Step 1: Analyze the code behavior

    The code inside the with pytest.raises(ZeroDivisionError) as exc_info: block raises a ZeroDivisionError by dividing 1 by 0.
  2. Step 2: Check the assertion

    The assertion verifies that the exception message contains 'division by zero', which is true for this error.
  3. Final Answer:

    Test passes because ZeroDivisionError is raised and message matches -> Option A
  4. Quick Check:

    Exception raised and message checked = D [OK]
Hint: Use exc_info.value to check exception message text [OK]
Common Mistakes:
  • Not using 'as exc_info' to capture exception details
  • Checking wrong exception message text
  • Expecting no exception raised
4. Identify the error in this test code snippet:
def test_key_error():
    with pytest.raises(KeyError):
        d = {'a': 1}
        value = d['b']
    assert value == 1
medium
A. The variable 'value' is used outside the with block where it may not be assigned
B. The exception type should be ValueError, not KeyError
C. The dictionary key 'b' exists, so no exception is raised
D. pytest.raises cannot be used with dictionary lookups

Solution

  1. Step 1: Understand variable scope and exception flow

    The line value = d['b'] raises a KeyError, so value is never assigned inside the with block.
  2. Step 2: Identify the error in assertion

    After the with block, the code tries to assert value == 1, but value is undefined because the assignment never happened due to the exception.
  3. Final Answer:

    The variable 'value' is used outside the with block where it may not be assigned -> Option A
  4. Quick Check:

    Exception stops assignment, so variable undefined after [OK]
Hint: Don't use variables assigned inside exception blocks outside [OK]
Common Mistakes:
  • Assuming variable is assigned despite exception
  • Confusing exception types
  • Thinking pytest.raises can't handle dict key errors
5. You want to test a function parse_int(s) that should raise ValueError with message containing 'invalid literal' when given a non-integer string. Which pytest code correctly asserts this behavior and checks the error message?
hard
A. with pytest.raises(ValueError): parse_int('abc') assert 'invalid literal' in e.value
B. pytest.raises(ValueError, parse_int('abc')) assert 'invalid literal' in e.value
C. with pytest.raises(ValueError) as e: parse_int('abc') assert 'invalid literal' in str(e.value)
D. with pytest.raises('ValueError') as e: parse_int('abc') assert 'invalid literal' in str(e.value)

Solution

  1. Step 1: Use correct syntax to capture exception info

    Use with pytest.raises(ValueError) as e: to catch the exception and store info in e.
  2. Step 2: Check error message properly

    After the block, check if the string 'invalid literal' is in str(e.value). This converts the exception to string for message checking.
  3. Step 3: Eliminate incorrect options

    with pytest.raises(ValueError): parse_int('abc') assert 'invalid literal' in e.value tries to use e outside the block without capturing it. pytest.raises(ValueError, parse_int('abc')) assert 'invalid literal' in e.value calls the function inside pytest.raises incorrectly and uses e undefined. with pytest.raises('ValueError') as e: parse_int('abc') assert 'invalid literal' in str(e.value) uses exception name as string instead of class.
  4. Final Answer:

    with pytest.raises(ValueError) as e: parse_int('abc') assert 'invalid literal' in str(e.value) -> Option C
  5. Quick Check:

    Capture exception with 'as' and check message string [OK]
Hint: Use 'as' to capture exception and check message with str(e.value) [OK]
Common Mistakes:
  • Using exception name as string instead of class
  • Calling function inside pytest.raises arguments
  • Accessing exception info outside 'with' without 'as'
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