We use pytest.raises to check if a piece of code correctly causes an error. This helps us make sure our program handles bad situations safely.
Asserting exceptions (pytest.raises)
with pytest.raises(ExpectedException):
code_that_should_raise()Use with to start a block where you expect an error.
Replace ExpectedException with the specific error type you expect, like ValueError.
ZeroDivisionError.with pytest.raises(ZeroDivisionError): x = 1 / 0
ValueError.with pytest.raises(ValueError): int('abc')
KeyError so you can check its message if needed.with pytest.raises(KeyError) as exc_info: d = {} d['missing']
This test script has two tests. One checks that dividing by zero raises the right error with the correct message. The other checks normal division works fine.
import pytest def divide(a, b): if b == 0: raise ZeroDivisionError('Cannot divide by zero') return a / b def test_divide_by_zero(): with pytest.raises(ZeroDivisionError) as exc_info: divide(10, 0) assert str(exc_info.value) == 'Cannot divide by zero' def test_divide_normal(): assert divide(10, 2) == 5
Always specify the exact exception type to avoid catching unexpected errors.
You can capture the exception info with as exc_info to check error messages.
Use pytest.raises inside test functions only.
pytest.raises helps check if code raises expected errors.
Use it with a with block around code that should fail.
You can also check the error message by capturing the exception info.
Practice
pytest.raises in a test?Solution
Step 1: Understand the role of
pytest.raisespytest.raisesis used to verify that a certain exception is raised by the code inside itswithblock.Step 2: Compare options with the purpose
Only To check if a specific exception is raised by the code inside thewithblock correctly states that it checks for a specific exception. Other options describe unrelated behaviors.Final Answer:
To check if a specific exception is raised by the code inside thewithblock -> Option DQuick Check:
pytest.raises checks exceptions = A [OK]
- Thinking pytest.raises skips tests
- Assuming it prints exceptions automatically
- Believing it ignores exceptions
ValueError is raised when calling func() using pytest.raises?Solution
Step 1: Recall correct
The correct way is to use apytest.raisessyntaxwithstatement withpytest.raises(ExceptionType):followed by the code that should raise the exception.Step 2: Evaluate each option
with pytest.raises(ValueError): func() uses the correctwithblock 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 thewithkeyword.Final Answer:
with pytest.raises(ValueError): func() -> Option BQuick Check:
Use with + pytest.raises(Exception): code [OK]
- Calling the function inside pytest.raises() arguments
- Using exception name as string instead of class
- Omitting the 'with' keyword
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError) as exc_info:
1 / 0
assert 'division by zero' in str(exc_info.value)Solution
Step 1: Analyze the code behavior
The code inside thewith pytest.raises(ZeroDivisionError) as exc_info:block raises a ZeroDivisionError by dividing 1 by 0.Step 2: Check the assertion
The assertion verifies that the exception message contains 'division by zero', which is true for this error.Final Answer:
Test passes because ZeroDivisionError is raised and message matches -> Option AQuick Check:
Exception raised and message checked = D [OK]
- Not using 'as exc_info' to capture exception details
- Checking wrong exception message text
- Expecting no exception raised
def test_key_error():
with pytest.raises(KeyError):
d = {'a': 1}
value = d['b']
assert value == 1Solution
Step 1: Understand variable scope and exception flow
The linevalue = d['b']raises a KeyError, sovalueis never assigned inside thewithblock.Step 2: Identify the error in assertion
After thewithblock, the code tries to assertvalue == 1, butvalueis undefined because the assignment never happened due to the exception.Final Answer:
The variable 'value' is used outside the with block where it may not be assigned -> Option AQuick Check:
Exception stops assignment, so variable undefined after [OK]
- Assuming variable is assigned despite exception
- Confusing exception types
- Thinking pytest.raises can't handle dict key errors
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?Solution
Step 1: Use correct syntax to capture exception info
Usewith pytest.raises(ValueError) as e:to catch the exception and store info ine.Step 2: Check error message properly
After the block, check if the string 'invalid literal' is instr(e.value). This converts the exception to string for message checking.Step 3: Eliminate incorrect options
with pytest.raises(ValueError): parse_int('abc') assert 'invalid literal' in e.value tries to useeoutside the block without capturing it. pytest.raises(ValueError, parse_int('abc')) assert 'invalid literal' in e.value calls the function insidepytest.raisesincorrectly and useseundefined. with pytest.raises('ValueError') as e: parse_int('abc') assert 'invalid literal' in str(e.value) uses exception name as string instead of class.Final Answer:
with pytest.raises(ValueError) as e: parse_int('abc') assert 'invalid literal' in str(e.value) -> Option CQuick Check:
Capture exception with 'as' and check message string [OK]
- Using exception name as string instead of class
- Calling function inside pytest.raises arguments
- Accessing exception info outside 'with' without 'as'
Ready to prove it?
Pass the test and this pattern moves unknown
