I want to find a way to test that my code return the correct error message for a given error with pytest
My code works on a dictionary and in some cases, some keys could be undefined. In the example below, the tag
variable is provided by the user, and in some cases, that key can be undefined. I then added a try/except statement to catch this exception and return an error message to the user, explaining the issue.
try:
species = self.species[tag]
except KeyError:
print(f"Error: the species {tag} is not defined")
My issue arise when trying to write a unit test for this code. How could I check that my code return the appropriate error message ? I could write a test who provide willingly a wrong tag
and then check for stdout, but then I would have to rewrite this test if I decided to change the error message. And it seems not very appropriate in the "Don't Repeat Yourself" approach.
This : How to properly assert that an exception gets raised in pytest? does not answer my question, as I don't raise an exception.
Maybe I'm not even handling correctly the error in the first place and there is a better way to do it with Python.