Created
October 23, 2019 13:19
-
-
Save fabiofortkamp/5c557664f87953be390b4c54131c19f6 to your computer and use it in GitHub Desktop.
Definiing custom exceptions in Python with a meaningful message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class InvalidParameterError(ValueError): | |
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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