0
0
PyTesttesting~5 mins

pytest.raises context manager - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
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:<br>
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.<br>Example:<br>
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
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:
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
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
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
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.