def test_format_checkers_come_with_defaults(self): # This is bad :/ but relied upon. # The docs for quite awhile recommended people do things like # validate(..., format_checker=FormatChecker()) # We should change that, but we can't without deprecation... checker = FormatChecker() with self.assertRaises(FormatError): checker.check(instance="not-an-ipv4", format="ipv4")
class FormatValidator: def __init__(self, format): self._format = format self._checker = FormatChecker() def __call__(self, text): try: self._checker.check(text, self._format) except FormatError: raise ValidationError("Value {!r} does not confirm to format {!r}".format(text, self._format)) return True
def test_it_catches_registered_errors(self): checker = FormatChecker() checker.checks("boom", raises=type(BOOM))(boom) with self.assertRaises(FormatError) as cm: checker.check(instance=12, format="boom") self.assertIs(cm.exception.cause, BOOM) self.assertIs(cm.exception.__cause__, BOOM) # Unregistered errors should not be caught with self.assertRaises(type(BANG)): checker.check(instance="bang", format="boom")
def test_it_catches_registered_errors(self): checker = FormatChecker() checker.checks("foo", raises=ValueError)(self.fn) # Registered errors should be caught and turned into FormatErrors cause = ValueError() self.fn.side_effect = cause with self.assertRaises(FormatError) as cm: checker.check("bar", "foo") # Original exception should be attached to cause attribute self.assertIs(cm.exception.cause, cause) # Unregistered errors should not be caught self.fn.side_effect = AttributeError with self.assertRaises(AttributeError): checker.check("bar", "foo")
def test_it_catches_registered_errors(self): checker = FormatChecker() cause = self.fn.side_effect = ValueError() checker.checks("foo", raises=ValueError)(self.fn) with self.assertRaises(FormatError) as cm: checker.check("bar", "foo") self.assertIs(cm.exception.cause, cause) self.assertIs(cm.exception.__cause__, cause) # Unregistered errors should not be caught self.fn.side_effect = AttributeError with self.assertRaises(AttributeError): checker.check("bar", "foo")