Rowin
Rowin

Reputation: 465

How to test for an error message with Pytest

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.

Upvotes: 0

Views: 833

Answers (1)

cylon86
cylon86

Reputation: 634

I believe you should change you code structure to achieve what you wish.

class Species:

    def myMethod(tag):
        try:
            species = self.species[tag]
        except KeyError:
            raise YourCustomError(f"Error: the species {tag} is not defined")

Then you can write your pytest function to check that YourCustomError is raised when using myMethod with a bad tag. Note that instead of YourCustomError, you can do : raise KeyError("custom message")

Upvotes: 1

Related Questions