Bird
Raised Fist0
PyTesttesting~5 mins

pytest.raises context manager

Choose your learning style10 modes available
Introduction

We use pytest.raises to check if a piece of code correctly causes an error. This helps us make sure our program handles mistakes well.

When you want to test if a function raises an error for bad input.
When you want to confirm that your code stops running and shows the right error message.
When you want to catch specific exceptions during testing to avoid crashes.
When you want to verify that your error handling works as expected.
When you want to write tests that expect failures to happen safely.
Syntax
PyTest
with pytest.raises(ExpectedException):
    code_that_should_raise()

Replace ExpectedException with the error type you expect, like ValueError.

Put the code that should cause the error inside the with block.

Examples
This test passes if dividing by zero raises a ZeroDivisionError.
PyTest
with pytest.raises(ZeroDivisionError):
    x = 1 / 0
This test checks that converting a non-number string to int raises a ValueError.
PyTest
with pytest.raises(ValueError):
    int('abc')
This test expects a KeyError when accessing a missing dictionary key.
PyTest
with pytest.raises(KeyError):
    d = {}
    value = d['missing']
Sample Program

This test checks that dividing by zero in the divide function raises a ZeroDivisionError. The test will pass if the error happens as expected.

PyTest
import pytest

def divide(a, b):
    return a / b

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

if __name__ == '__main__':
    pytest.main([__file__])
OutputSuccess
Important Notes

Always specify the exact exception you expect to catch for clear tests.

If the code inside with pytest.raises() does not raise the error, the test fails.

You can also check the error message by using as exc_info after raises().

Summary

pytest.raises helps test if code raises expected errors.

Use it as a with block around code that should fail.

This makes your tests safer and your code more reliable.

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