Bird
Raised Fist0
PyTesttesting~10 mins

pytest.raises context manager - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check if a ZeroDivisionError is raised.

PyTest
import pytest

def test_divide_by_zero():
    with pytest.[1](ZeroDivisionError):
        x = 1 / 0
Drag options to blanks, or click blank then click option'
Aassert
Braises
Cexpect
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'assert' instead of 'raises' for exception checking.
Trying to catch exceptions manually instead of using pytest.raises.
2fill in blank
medium

Complete the code to check if a ValueError is raised when converting a string to int.

PyTest
import pytest

def test_invalid_int():
    with pytest.[1](ValueError):
        int('abc')
Drag options to blanks, or click blank then click option'
Acatch
Bassert
Craises
Dexpect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'assert' instead of 'raises'.
Not using a context manager.
3fill in blank
hard

Fix the error in the code to properly check for a KeyError.

PyTest
import pytest

def test_key_error():
    with pytest.[1](KeyError):
        d = {'a': 1}
        value = d['b']
Drag options to blanks, or click blank then click option'
Araises
Bassert
Cexpect
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'assert' or 'expect' instead of 'raises'.
Not using a context manager.
4fill in blank
hard

Fill both blanks to check if a TypeError is raised and capture the exception as 'exc'.

PyTest
import pytest

def test_type_error():
    with pytest.[1](TypeError) as [2]:
        int(None)
Drag options to blanks, or click blank then click option'
Araises
Bexc
Cerror
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong context manager names.
Not capturing the exception object.
5fill in blank
hard

Fill all three blanks to check for an IndexError, capture it as 'e', and assert the error message contains 'list index out of range'.

PyTest
import pytest

def test_index_error():
    with pytest.[1](IndexError) as [2]:
        lst = []
        _ = lst[0]
    assert '[3]' in str(e.value)
Drag options to blanks, or click blank then click option'
Araises
Be
Clist index out of range
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Not capturing the exception object.
Checking the wrong error message.
Using wrong variable names.

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