0
0
PyTesttesting~10 mins

Why error path testing ensures robustness in PyTest - Test Your Understanding

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

Complete the code to check if the function raises a ValueError for invalid input.

PyTest
import pytest

def test_invalid_input():
    with pytest.raises([1]):
        process_data('bad_input')
Drag options to blanks, or click blank then click option'
ATypeError
BValueError
CKeyError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception type in pytest.raises.
Not using pytest.raises at all.
2fill in blank
medium

Complete the assertion to verify the error message contains the word 'invalid'.

PyTest
import pytest

def test_error_message():
    with pytest.raises(ValueError) as excinfo:
        process_data('bad_input')
    assert '[1]' in str(excinfo.value)
Drag options to blanks, or click blank then click option'
A'invalid'
B'error'
C'fail'
D'exception'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for a wrong or unrelated word in the error message.
Not converting the exception to string before checking.
3fill in blank
hard

Fix the error in the test that tries to catch a KeyError but the function raises ValueError.

PyTest
import pytest

def test_wrong_exception():
    with pytest.raises([1]):
        process_data('bad_input')
Drag options to blanks, or click blank then click option'
AValueError
BTypeError
CKeyError
DRuntimeError
Attempts:
3 left
💡 Hint
Common Mistakes
Expecting the wrong exception type.
Not updating the test after function changes.
4fill in blank
hard

Fill both blanks to test that the function raises a TypeError when input is not a string and the error message contains 'type'.

PyTest
import pytest

def test_type_error():
    with pytest.raises([1]) as excinfo:
        process_data(123)
    assert '[2]' in str(excinfo.value)
Drag options to blanks, or click blank then click option'
ATypeError
BValueError
Ctype
Dinvalid
Attempts:
3 left
💡 Hint
Common Mistakes
Using ValueError instead of TypeError.
Checking for 'invalid' instead of 'type' in the message.
5fill in blank
hard

Fill all three blanks to create a test that asserts a KeyError is raised when a missing key is accessed, and the error message contains the missing key name.

PyTest
import pytest

def test_missing_key():
    with pytest.raises([1]) as excinfo:
        data = {'a': 1}
        value = data[[2]]
    assert [3] in str(excinfo.value)
Drag options to blanks, or click blank then click option'
AKeyError
B'b'
DValueError
Attempts:
3 left
💡 Hint
Common Mistakes
Using ValueError instead of KeyError.
Not using quotes around the missing key in the assertion.