Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Definiing custom exceptions in Python with a meaningful message
class InvalidParameterError(ValueError):
pass
from custom_errors import InvalidParameterError
def validate(p):
for k, v in p.items():
if v < 0:
emsg = "Parameter '%s' cannot be negative" %(k,)
raise InvalidParameterError(emsg)
import pytest
from custom_error import InvalidParameterError
from parse_parameters import validate
def test_negative_parameters_raise_error():
sample_params = {
'a': 1.43,
'b': 57,
'c': -10
}
with pytest.raises(InvalidParameterError) as excinfo:
validate(sample_params)
# The object returned by this pytest context manager
# has a 'value' field assigned to the exception object itself.
# In addition, all built-in exceptions derived from Exception
# have an 'args' tuple field assigned to the passed arguments.
# Hence, when we create a custom error with a string as the first argument,
# this string is assigned to the first element of the tuple 'args'
exception_msg = excinfo.value.args[0]
expected_message = "Parameter 'c' cannot be negative".
assert exception_msg == expected_message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment