What is the purpose of the pytest.raises context manager?
It is used to check that a specific exception is raised during the execution of a block of code in a test.
Click to reveal answer
beginner
How do you use pytest.raises to test if a function raises a ValueError?
Use it as a context manager like this:
with pytest.raises(ValueError):
function_that_raises()
Click to reveal answer
beginner
What happens if the expected exception is not raised inside the pytest.raises block?
The test will fail because pytest.raises expects the specified exception to occur.
Click to reveal answer
intermediate
Can pytest.raises capture the exception object for further checks?
Yes, by using the as keyword, you can capture the exception and inspect its message or attributes. Example:
with pytest.raises(ValueError) as exc_info:
function_that_raises()
assert 'error message' in str(exc_info.value)
Click to reveal answer
intermediate
Why is using pytest.raises better than a try-except block in tests?
Because it makes tests cleaner and more readable by clearly showing the expected exception, and it automatically fails the test if the exception is not raised.
Click to reveal answer
What does pytest.raises(ValueError) check for?
AThat the test passes without errors
BThat no exceptions are raised
CThat the function returns a ValueError
DThat a ValueError exception is raised inside the block
✗ Incorrect
pytest.raises(ValueError) expects a ValueError exception to be raised inside its block.
How do you capture the exception object with pytest.raises?
Apytest.raises(Exception).catch()
Bwith pytest.raises(Exception).capture():
Cwith pytest.raises(Exception) as exc_info:
Dwith pytest.capture(Exception) as exc_info:
✗ Incorrect
Use as exc_info to capture the exception object for inspection.
What happens if the expected exception is not raised inside pytest.raises?
AThe test is skipped
BThe test fails
CThe test passes
DThe test raises a warning
✗ Incorrect
If the expected exception is not raised, pytest.raises causes the test to fail.
Which of these is a correct way to test that my_func() raises a KeyError?
Awith pytest.raises(KeyError): my_func()
Bpytest.raises(KeyError, my_func())
Ctry: my_func() except KeyError: pass
Dassert my_func() raises KeyError
✗ Incorrect
The correct syntax uses with pytest.raises(KeyError): as a context manager.
Why is pytest.raises preferred over manual try-except in tests?
AIt makes tests clearer and automatically fails if exception is missing
BIt runs tests faster
CIt catches all exceptions silently
DIt disables exceptions
✗ Incorrect
pytest.raises improves readability and test reliability by clearly expecting exceptions.
Explain how to use pytest.raises to test that a function raises a specific exception and how to check the exception message.
Think about capturing the exception and then asserting on its message.
You got /4 concepts.
Describe what happens when the expected exception is not raised inside a pytest.raises block during test execution.
Consider the purpose of expecting exceptions in tests.
You got /3 concepts.
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
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 B
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
Step 1: Recall correct context manager syntax
pytest.raises must be used with the with keyword and the exception class without quotes.
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.
Final Answer:
with pytest.raises(ValueError):\n function_call() -> Option A
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
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 D
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
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.
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 A
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
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.
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 C
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 unknownstrongwhile earning +1 Grip toward your certificate.