0
0
PyTesttesting~10 mins

Asserting exceptions (pytest.raises) - Interactive Code Practice

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

Complete the code to assert that a ValueError is raised.

PyTest
import pytest

def test_value_error():
    with pytest.[1](ValueError):
        int('abc')
Drag options to blanks, or click blank then click option'
Araises
Braises_error
Cassert
Dexpect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'assert' instead of 'raises' causes syntax errors.
Using a wrong function name like 'raises_error' will fail.
2fill in blank
medium

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

PyTest
import pytest

def test_error_message():
    with pytest.raises(ValueError) as [1]:
        int('abc')
    assert 'invalid literal' in [1].value.args[0]
Drag options to blanks, or click blank then click option'
Aexception
Berror
Cexcinfo
Derr
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name not matching the assertion line causes NameError.
Forgetting to use 'as' to capture exception info.
3fill in blank
hard

Fix the error in the code to properly assert a ZeroDivisionError is raised.

PyTest
import pytest

def test_division():
    with pytest.raises([1]):
        result = 1 / 0
Drag options to blanks, or click blank then click option'
AValueError
BZeroDivisionError
CTypeError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using ValueError or other exceptions causes the test to fail.
Misspelling the exception name.
4fill in blank
hard

Fill both blanks to assert a KeyError is raised and check its message.

PyTest
import pytest

def test_key_error():
    with pytest.[1](KeyError) as [2]:
        d = {}
        d['missing']
Drag options to blanks, or click blank then click option'
Araises
Berror
Cexcinfo
Dexpect
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong context manager name causes syntax errors.
Using a variable name not matching the assertion line.
5fill in blank
hard

Fill all three blanks to assert a TypeError is raised and check the exception message contains 'unsupported operand'.

PyTest
import pytest

def test_type_error():
    with pytest.[1](TypeError) as [2]:
        result = 'a' + 1
    assert '[3]' in [2].value.args[0]
Drag options to blanks, or click blank then click option'
Araises
Bexcinfo
Cunsupported operand
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong exception type or variable name.
Checking for wrong message text.