0
0
PyTesttesting~10 mins

pytest.raises context manager - 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 if a ZeroDivisionError is raised.

PyTest
import pytest

def test_divide_by_zero():
    with pytest.[1](ZeroDivisionError):
        x = 1 / 0
Drag options to blanks, or click blank then click option'
Aassert
Braises
Cexpect
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'assert' instead of 'raises' for exception checking.
Trying to catch exceptions manually instead of using pytest.raises.
2fill in blank
medium

Complete the code to check if a ValueError is raised when converting a string to int.

PyTest
import pytest

def test_invalid_int():
    with pytest.[1](ValueError):
        int('abc')
Drag options to blanks, or click blank then click option'
Acatch
Bassert
Craises
Dexpect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'assert' instead of 'raises'.
Not using a context manager.
3fill in blank
hard

Fix the error in the code to properly check for a KeyError.

PyTest
import pytest

def test_key_error():
    with pytest.[1](KeyError):
        d = {'a': 1}
        value = d['b']
Drag options to blanks, or click blank then click option'
Araises
Bassert
Cexpect
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'assert' or 'expect' instead of 'raises'.
Not using a context manager.
4fill in blank
hard

Fill both blanks to check if a TypeError is raised and capture the exception as 'exc'.

PyTest
import pytest

def test_type_error():
    with pytest.[1](TypeError) as [2]:
        int(None)
Drag options to blanks, or click blank then click option'
Araises
Bexc
Cerror
Dcatch
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong context manager names.
Not capturing the exception object.
5fill in blank
hard

Fill all three blanks to check for an IndexError, capture it as 'e', and assert the error message contains 'list index out of range'.

PyTest
import pytest

def test_index_error():
    with pytest.[1](IndexError) as [2]:
        lst = []
        _ = lst[0]
    assert '[3]' in str(e.value)
Drag options to blanks, or click blank then click option'
Araises
Be
Clist index out of range
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Not capturing the exception object.
Checking the wrong error message.
Using wrong variable names.