I have some test code that does this at one point:
from contextlib import suppress from datetime import datetime import unittest class BirthdayParser(object): @staticmethod def parse(birthday): with suppress(TypeError, ValueError): return datetime.strptime(birthday, '%Y-%m-%d') class TestBirthdayParser(unittest.TestCase) def test(self): self.assertEqual(BirthdayParser.parse('1970-01-01'), datetime(year=1970, month=1, day=1)) self.assertIsNone(BirthdayParser.parse('x'))
Now, the coverage report for that with statement in BirthdayParser.parse() will be the same, no matter if the exceptions are raised or not, since they are suppressed by the context.
I'd really like to have a more accurate coverage report, so I could replace the with statement with a try statement:
try: return datetime.strptime(data['birthday'], '%Y-%m-%d') except (TypeError, ValueError): pass
This accomplishes my intention, but I'm starting to think, is this a bit paranoid? Does it actually matter? I feel I should test that call to datetime.strptime, but I'm having a slight feeling I'm caring about testing at an overly fine level of granularity.