I am working on unit tests for the first time, and I am a bit stuck figuring out what people tend to do when handling an exception and using tests. Specifically, I sometimes like to handle an exception simply when it allows me to provide a more useful error message (especially for myself if I am using my own code incorrectly later at some point). However, I figured out that because I handled the exception, assertRaises
doesn't work. An minimal example:
Main script
data_dict = {'Dog': 'puppies',
'Cat': 'kittens',
'Bear': 'cubs'}
def fetch_metadata(animal_name):
# Do some other stuff, then:
try:
return data_dict[animal_name]
except KeyError:
print("{} not a valid entry. Please check your entry or update the data dictionary.".format(animal_name))
Test Script
import unittest
from scripts.update_metadata import fetch_metadata
class TestFetchMetaData(unittest.TestCase):
def test_unknown_animal_raises_error(self):
with self.assertRaises(KeyError):
fetch_metadata('Giraffe')
if __name__ == "__main__":
unittest.main()
I have some (maybe dumb) ideas of how this could be fixed: (1) re-raising after printing the message (2) using a different assert, maybe something to do with stdout
since pytest printed the message or (3) not testing because I wrote the try/except myself so it theoretically it's taken care of, although if people always wrote things perfectly then we wouldn't bother testing.
I have done some searching and haven't been able to find examples or posts talking about this.
Aucun commentaire:
Enregistrer un commentaire