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.
pytest.raises context manager
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.
ZeroDivisionError.with pytest.raises(ZeroDivisionError): x = 1 / 0
ValueError.with pytest.raises(ValueError): int('abc')
KeyError when accessing a missing dictionary key.with pytest.raises(KeyError): d = {} value = d['missing']
This test checks that dividing by zero in the divide function raises a ZeroDivisionError. The test will pass if the error happens as expected.
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__])
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().
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
pytest.raises in a test?Solution
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.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.Final Answer:
To check if a specific error is raised by the code inside the block -> Option BQuick Check:
pytest.raises checks errors = A [OK]
- Thinking pytest.raises fixes errors automatically
- Confusing pytest.raises with test skipping
- Using pytest.raises to print errors
pytest.raises to check for a ValueError?Solution
Step 1: Recall correct context manager syntax
pytest.raises must be used with thewithkeyword and the exception class without quotes.Step 2: Evaluate each option
with pytest.raises(ValueError):\n function_call() correctly useswith pytest.raises(ValueError):. Options A and B miss thewithkeyword. with pytest.raises('ValueError'):\n function_call() incorrectly uses quotes around the exception.Final Answer:
with pytest.raises(ValueError):\n function_call() -> Option AQuick Check:
Use with + exception class (no quotes) = D [OK]
- Omitting the 'with' keyword
- Putting exception name in quotes
- Not indenting code inside the block
import pytest
def test_divide():
with pytest.raises(ZeroDivisionError):
x = 1 / 0
Solution
Step 1: Analyze the code inside pytest.raises
The code divides 1 by 0, which raises a ZeroDivisionError as expected.Step 2: Understand pytest.raises behavior
Since the expected error occurs, pytest.raises catches it and the test passes.Final Answer:
Test passes because ZeroDivisionError is raised -> Option DQuick Check:
Expected error raised = test passes = B [OK]
- Thinking test fails when error is raised
- Confusing ZeroDivisionError with other exceptions
- Assuming syntax error without checking code
pytest.raises:import pytest
def test_key_error():
with pytest.raises(KeyError):
d = {'a': 1}
x = d['b']
Solution
Step 1: Check indentation inside the with block
The lines inside the with block must be indented. Here,d = {'a': 1}andx = d['b']are not indented properly.Step 2: Verify other aspects
pytest is imported, and KeyError is the correct exception for missing key access. So no other errors.Final Answer:
Indentation error inside the with block -> Option AQuick Check:
Indent code inside with block = C [OK]
- Not indenting code inside the with block
- Using wrong exception type
- Forgetting to import pytest
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'?Solution
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 usesas excinfoto capture the exception object for later inspection.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.Final Answer:
with pytest.raises(ValueError) as excinfo: parse_int('abc') assert 'invalid' in str(excinfo.value) -> Option CQuick Check:
Use 'as excinfo' and check excinfo.value message = A [OK]
- Putting exception name in quotes
- Not capturing exception info with 'as'
- Checking error message outside the context incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
