0
0
PyTesttesting~10 mins

Testing exception chains in PyTest - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to check that a ValueError is raised.

PyTest
import pytest

def test_value_error():
    with pytest.raises([1]):
        int('abc')
Drag options to blanks, or click blank then click option'
AKeyError
BValueError
CTypeError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception type like TypeError or KeyError.
Not using pytest.raises context manager.
2fill in blank
medium

Complete the code to check that a KeyError is raised with the correct message.

PyTest
import pytest

def test_key_error():
    with pytest.raises(KeyError) as exc_info:
        {}['missing']
    assert exc_info.value.args[0] == [1]
Drag options to blanks, or click blank then click option'
A"key"
B"missing"
C'key'
D'missing'
Attempts:
3 left
💡 Hint
Common Mistakes
Using double quotes instead of single quotes (both work but be consistent).
Checking the wrong attribute of exc_info.
3fill in blank
hard

Fix the error in the test to correctly check the exception chain.

PyTest
import pytest

def test_exception_chain():
    with pytest.raises(RuntimeError) as exc_info:
        try:
            int('abc')
        except ValueError as e:
            raise RuntimeError('Failed') from [1]
Drag options to blanks, or click blank then click option'
Ae
Bexc_info
CRuntimeError
DValueError
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable name in the 'from' clause.
Using the exception class instead of the instance.
4fill in blank
hard

Fill both blanks to assert the original exception type and message in the exception chain.

PyTest
import pytest

def test_exception_chain_details():
    with pytest.raises(RuntimeError) as exc_info:
        try:
            int('abc')
        except ValueError as e:
            raise RuntimeError('Failed') from e
    original = exc_info.value.__cause__
    assert isinstance(original, [1])
    assert str(original) == [2]
Drag options to blanks, or click blank then click option'
AValueError
BTypeError
C'invalid literal for int() with base 10: \'abc\''
D'Failed'
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing the RuntimeError message with the original exception message.
Using the wrong exception type in isinstance check.
5fill in blank
hard

Fill all three blanks to write a test that verifies the exception chain and message.

PyTest
import pytest

def test_full_exception_chain():
    with pytest.raises([1]) as exc_info:
        try:
            float('xyz')
        except [2] as e:
            raise [3]('Conversion failed') from e
Drag options to blanks, or click blank then click option'
ARuntimeError
BValueError
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up exception types in the raises or except clauses.
Not using the 'from' keyword to chain exceptions.