0
0
PyTesttesting~10 mins

Matching exception messages 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'
AValueError
BKeyError
CTypeError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception type like TypeError instead of ValueError.
2fill in blank
medium

Complete the code to check that the exception message contains 'invalid literal'.

PyTest
import pytest

def test_value_error_message():
    with pytest.raises(ValueError, match=[1]):
        int('abc')
Drag options to blanks, or click blank then click option'
A'KeyError'
B'TypeError'
C'invalid literal'
D'IndexError'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the exception type name instead of a message substring for match.
3fill in blank
hard

Fix the error in the code to correctly match the exception message.

PyTest
import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError, match=[1]):
        1 / 0
Drag options to blanks, or click blank then click option'
A'float division by zero'
B'division zero'
C'ZeroDivisionError'
D'division by zero'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the exception class name as the match string instead of the message.
4fill in blank
hard

Fill both blanks to check for a KeyError with message 'missing'.

PyTest
import pytest

def test_key_error():
    with pytest.raises([1], match=[2]):
        d = {}
        d['missing']
Drag options to blanks, or click blank then click option'
AKeyError
B'missing key'
C'missing'
DValueError
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception type or incorrect message string.
5fill in blank
hard

Fill all three blanks to check for an IndexError with message 'list index out of range'.

PyTest
import pytest

def test_index_error():
    with pytest.raises([1], match=[2]):
        lst = [1, 2, 3]
        _ = lst[[3]]
Drag options to blanks, or click blank then click option'
AIndexError
B'list index out of range'
C5
DKeyError
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception type or wrong index number.