Bird
Raised Fist0
PyTesttesting~20 mins

pytest.raises context manager - Practice Problems & Coding Challenges

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

def test_division():
    with pytest.raises(ZeroDivisionError):
        x = 1 / 0
    print("Test passed")
ANo output because test is skipped
BZeroDivisionError is raised and test fails
CSyntaxError due to incorrect pytest usage
DTest passed
Attempts:
2 left
💡 Hint
pytest.raises expects the code inside to raise the specified error to pass.
❓ assertion
intermediate
2:00remaining
Correct assertion to check exception message with pytest.raises
Which option correctly asserts that a ValueError with message 'invalid input' is raised?
PyTest
import pytest

def func():
    raise ValueError('invalid input')

def test_func():
    with pytest.raises(ValueError) as excinfo:
        func()
    # Which assertion below is correct?
Aassert excinfo.value.message == 'invalid input'
Bassert excinfo.message == 'invalid input'
Cassert 'invalid input' in str(excinfo.value)
Dassert excinfo == 'invalid input'
Attempts:
2 left
💡 Hint
Exception message is accessed via str(excinfo.value).
🔧 Debug
advanced
2:00remaining
Why does this pytest.raises test fail?
Given this test code, why does pytest report a failure?
PyTest
import pytest

def test_error():
    with pytest.raises(ValueError):
        x = int('abc')
    with pytest.raises(TypeError):
        x = int('abc')
AThe first with block does not raise any error
BThe second with block expects TypeError but int('abc') raises ValueError
Cpytest.raises cannot be used twice in one test
Dint('abc') raises SyntaxError, not ValueError or TypeError
Attempts:
2 left
💡 Hint
Check the actual error type raised by int('abc').
🧠 Conceptual
advanced
2:00remaining
Behavior of pytest.raises when no exception is raised
What happens if the code inside a pytest.raises context manager does NOT raise the expected exception?
AThe test fails with Failed: DID NOT RAISE <ExceptionType>
BThe test passes silently
Cpytest.raises raises a SyntaxError
DThe test is skipped automatically
Attempts:
2 left
💡 Hint
pytest.raises expects an exception to be raised inside the block.
❓ framework
expert
3:00remaining
Using pytest.raises to test multiple exception types
Which option correctly tests that a function raises either ValueError or TypeError using pytest.raises?
A
with pytest.raises((ValueError, TypeError)):
    func()
B
with pytest.raises(ValueError | TypeError):
    func()
C
with pytest.raises(ValueError) and pytest.raises(TypeError):
    func()
D
with pytest.raises(ValueError) or pytest.raises(TypeError):
    func()
Attempts:
2 left
💡 Hint
pytest.raises accepts a tuple of exception types to check multiple exceptions.

Practice

(1/5)
1. What is the main purpose of using pytest.raises in a test?
easy
A. To skip a test when an error occurs
B. To check if a specific error is raised by the code inside the block
C. To automatically fix errors in the tested code
D. To print error messages during test execution

Solution

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

    pytest.raises is used to verify that a certain error is raised when running code inside its context.
  2. Step 2: Compare options with this purpose

    Only To check if a specific error is raised by the code inside the block correctly states that pytest.raises checks for expected errors. Other options describe unrelated behaviors.
  3. Final Answer:

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

    pytest.raises checks errors = A [OK]
Hint: Remember: pytest.raises expects an error inside its with block [OK]
Common Mistakes:
  • Thinking pytest.raises fixes errors automatically
  • Confusing pytest.raises with test skipping
  • Using pytest.raises to print errors
2. Which of the following is the correct syntax to use pytest.raises to check for a ValueError?
easy
A. with pytest.raises(ValueError):\n function_call()
B. pytest.raises(ValueError):\nfunction_call()
C. with pytest.raises('ValueError'):\n function_call()
D. pytest.raises(ValueError)\n function_call()

Solution

  1. Step 1: Recall correct context manager syntax

    pytest.raises must be used with the with keyword and the exception class without quotes.
  2. Step 2: Evaluate each option

    with pytest.raises(ValueError):\n function_call() correctly uses with pytest.raises(ValueError):. Options A and B miss the with keyword. with pytest.raises('ValueError'):\n function_call() incorrectly uses quotes around the exception.
  3. Final Answer:

    with pytest.raises(ValueError):\n function_call() -> Option A
  4. Quick Check:

    Use with + exception class (no quotes) = D [OK]
Hint: Always use 'with' and exception class without quotes [OK]
Common Mistakes:
  • Omitting the 'with' keyword
  • Putting exception name in quotes
  • Not indenting code inside the block
3. What will be the result of this test code?
import pytest

def test_divide():
    with pytest.raises(ZeroDivisionError):
        x = 1 / 0
medium
A. Test fails because no error is raised
B. Test passes but warns about division
C. Test fails due to syntax error
D. Test passes because ZeroDivisionError is raised

Solution

  1. Step 1: Analyze the code inside pytest.raises

    The code divides 1 by 0, which raises a ZeroDivisionError as expected.
  2. Step 2: Understand pytest.raises behavior

    Since the expected error occurs, pytest.raises catches it and the test passes.
  3. Final Answer:

    Test passes because ZeroDivisionError is raised -> Option D
  4. Quick Check:

    Expected error raised = test passes = B [OK]
Hint: If expected error occurs inside with block, test passes [OK]
Common Mistakes:
  • Thinking test fails when error is raised
  • Confusing ZeroDivisionError with other exceptions
  • Assuming syntax error without checking code
4. Identify the error in this test code using pytest.raises:
import pytest

def test_key_error():
    with pytest.raises(KeyError):
    d = {'a': 1}
    x = d['b']
medium
A. Indentation error inside the with block
B. Wrong exception type used
C. Missing import of pytest
D. No error; code is correct

Solution

  1. Step 1: Check indentation inside the with block

    The lines inside the with block must be indented. Here, d = {'a': 1} and x = d['b'] are not indented properly.
  2. Step 2: Verify other aspects

    pytest is imported, and KeyError is the correct exception for missing key access. So no other errors.
  3. Final Answer:

    Indentation error inside the with block -> Option A
  4. Quick Check:

    Indent code inside with block = C [OK]
Hint: Indent all code inside the with block properly [OK]
Common Mistakes:
  • Not indenting code inside the with block
  • Using wrong exception type
  • Forgetting to import pytest
5. You want to test a function parse_int(s) that should raise ValueError when given a non-integer string. Which of these test snippets correctly uses pytest.raises to check this behavior and also verifies the error message contains 'invalid'?
hard
A. with pytest.raises('ValueError') as e: parse_int('abc') assert 'invalid' in e
B. with pytest.raises(ValueError): parse_int('abc') assert 'invalid' in str(ValueError)
C. with pytest.raises(ValueError) as excinfo: parse_int('abc') assert 'invalid' in str(excinfo.value)
D. pytest.raises(ValueError): parse_int('abc') assert 'invalid' in str(excinfo.value)

Solution

  1. Step 1: Use pytest.raises as context manager with 'as' to capture exception info

    with pytest.raises(ValueError) as excinfo: parse_int('abc') assert 'invalid' in str(excinfo.value) correctly uses as excinfo to capture the exception object for later inspection.
  2. Step 2: Check the error message from excinfo.value

    with pytest.raises(ValueError) as excinfo: parse_int('abc') assert 'invalid' in str(excinfo.value) asserts that 'invalid' is in the string form of the exception value, which is the correct way to check the error message.
  3. Final Answer:

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

    Use 'as excinfo' and check excinfo.value message = A [OK]
Hint: Use 'as excinfo' to check error message inside pytest.raises [OK]
Common Mistakes:
  • Putting exception name in quotes
  • Not capturing exception info with 'as'
  • Checking error message outside the context incorrectly
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