Skip to content

Instantly share code, notes, and snippets.

@fabiofortkamp
Created October 23, 2019 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabiofortkamp/5c557664f87953be390b4c54131c19f6 to your computer and use it in GitHub Desktop.
Save fabiofortkamp/5c557664f87953be390b4c54131c19f6 to your computer and use it in GitHub Desktop.
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