0
0
PyTesttesting~10 mins

Testing custom exceptions 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 if the function raises ValueError.

PyTest
import pytest

def test_raise_custom_exception():
    with pytest.raises([1]):
        raise ValueError('Error!')
Drag options to blanks, or click blank then click option'
AKeyError
BValueError
CTypeError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different exception type than the one raised.
Not using pytest.raises() to catch exceptions.
2fill in blank
medium

Complete the code to define a custom exception class.

PyTest
class [1](Exception):
    pass
Drag options to blanks, or click blank then click option'
ACustomError
Berror
Cexception
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase names for exception classes.
Not inheriting from Exception.
3fill in blank
hard

Fix the error in the test to correctly check for the custom exception.

PyTest
import pytest

class MyError(Exception):
    pass

def test_my_error():
    with pytest.raises([1]):
        raise MyError('Oops!')
Drag options to blanks, or click blank then click option'
AMyError
BMyerror
CException
DError
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong capitalization for the exception class name.
Using a base exception class instead of the custom one.
4fill in blank
hard

Fill both blanks to raise and test a custom exception with a message.

PyTest
import pytest

class CustomError(Exception):
    pass

def test_custom_error_message():
    with pytest.raises([1]) as exc_info:
        raise CustomError([2])
    assert str(exc_info.value) == 'Error occurred'
Drag options to blanks, or click blank then click option'
ACustomError
B'Error occurred'
C'An error happened'
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different exception class in pytest.raises().
Passing a different message string than the one asserted.
5fill in blank
hard

Fill all three blanks to define, raise, and test a custom exception with a message.

PyTest
import pytest

class [1](Exception):
    pass

def test_[2]():
    with pytest.raises([3]) as exc:
        raise CustomException('Failed')
    assert str(exc.value) == 'Failed'
Drag options to blanks, or click blank then click option'
ACustomException
Bcustom_exception
DCustomError
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatch between class name and exception caught.
Incorrect test function naming style.
Using a different exception class in the test.