0
0
PyTesttesting~5 mins

Asserting exceptions (pytest.raises) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of pytest.raises in testing?

pytest.raises is used to check if a specific exception is raised during a test. It helps verify that your code correctly handles error cases.

Click to reveal answer
beginner
How do you use pytest.raises as a context manager?

You wrap the code that should raise an exception inside a with pytest.raises(ExceptionType): block. If the exception occurs, the test passes; if not, it fails.

Click to reveal answer
beginner
Example: Write a test that checks if ValueError is raised when converting 'abc' to int.
<pre>import pytest

def test_value_error():
    with pytest.raises(ValueError):
        int('abc')</pre>
Click to reveal answer
beginner
What happens if the expected exception is not raised inside pytest.raises block?

The test will fail because pytest.raises expects the specified exception to occur. Not raising it means the code did not behave as expected.

Click to reveal answer
intermediate
Can you capture the exception object using pytest.raises? How?
<p>Yes. Use <code>as exc_info</code> to capture the exception object for further checks, like message content.</p><pre>import pytest

with pytest.raises(ValueError) as exc_info:
    int('abc')
assert 'invalid literal' in str(exc_info.value)</pre>
Click to reveal answer
What does pytest.raises(ValueError) check in a test?
AThat the test is skipped
BThat no exceptions are raised
CThat a ValueError exception is raised
DThat the code runs without errors
How do you write a test to check if a function raises an exception using pytest.raises?
ACall the function normally and catch exceptions manually
BUse <code>with pytest.raises(ExceptionType):</code> around the code
CUse <code>assertRaises</code> from unittest
DUse <code>try-except</code> without pytest
What happens if the expected exception is not raised inside the pytest.raises block?
AThe test fails
BThe test passes
CThe test is skipped
DThe test is marked as xfail
How can you check the message of an exception raised inside pytest.raises?
AUse <code>assertRaisesMessage</code>
BUse <code>print</code> inside the block
CYou cannot check the message
DCapture the exception with <code>as exc_info</code> and check <code>exc_info.value</code>
Which of these is a correct use of pytest.raises?
Awith pytest.raises(ValueError): int('abc')
Bwith pytest.raises(IndexError): [1,2,3][1]
Cwith pytest.raises(TypeError): int('123')
Dwith pytest.raises(KeyError): {'a':1}['a']
Explain how to use pytest.raises to test that a function raises an exception.
Think about wrapping the code that should fail inside a special block.
You got /3 concepts.
    Describe how to capture and check the exception message using pytest.raises.
    You can save the exception to a variable for more checks.
    You got /3 concepts.