codekingpro/portable-devtools
114k
1"""2Tests for the parts of jsonschema related to the :kw:`format` keyword.3"""4 5from unittest import TestCase6 7from jsonschema import FormatChecker, ValidationError8from jsonschema.exceptions import FormatError9from jsonschema.validators import Draft4Validator10 11BOOM = ValueError("Boom!")12BANG = ZeroDivisionError("Bang!")13 14 15def boom(thing):16 if thing == "bang":17 raise BANG18 raise BOOM19 20 21class TestFormatChecker(TestCase):22 def test_it_can_validate_no_formats(self):23 checker = FormatChecker(formats=())24 self.assertFalse(checker.checkers)25 26 def test_it_raises_a_key_error_for_unknown_formats(self):27 with self.assertRaises(KeyError):28 FormatChecker(formats=["o noes"])29 30 def test_it_can_register_cls_checkers(self):31 original = dict(FormatChecker.checkers)32 self.addCleanup(FormatChecker.checkers.pop, "boom")33 with self.assertWarns(DeprecationWarning):34 FormatChecker.cls_checks("boom")(boom)35 self.assertEqual(36 FormatChecker.checkers,37 dict(original, boom=(boom, ())),38 )39 40 def test_it_can_register_checkers(self):41 checker = FormatChecker()42 checker.checks("boom")(boom)43 self.assertEqual(44 checker.checkers,45 dict(FormatChecker.checkers, boom=(boom, ())),46 )47 48 def test_it_catches_registered_errors(self):49 checker = FormatChecker()50 checker.checks("boom", raises=type(BOOM))(boom)51 52 with self.assertRaises(FormatError) as cm:53 checker.check(instance=12, format="boom")54 55 self.assertIs(cm.exception.cause, BOOM)56 self.assertIs(cm.exception.__cause__, BOOM)57 self.assertEqual(str(cm.exception), "12 is not a 'boom'")58 59 # Unregistered errors should not be caught60 with self.assertRaises(type(BANG)):61 checker.check(instance="bang", format="boom")62 63 def test_format_error_causes_become_validation_error_causes(self):64 checker = FormatChecker()65 checker.checks("boom", raises=ValueError)(boom)66 validator = Draft4Validator({"format": "boom"}, format_checker=checker)67 68 with self.assertRaises(ValidationError) as cm:69 validator.validate("BOOM")70 71 self.assertIs(cm.exception.cause, BOOM)72 self.assertIs(cm.exception.__cause__, BOOM)73 74 def test_format_checkers_come_with_defaults(self):75 # This is bad :/ but relied upon.76 # The docs for quite awhile recommended people do things like77 # validate(..., format_checker=FormatChecker())78 # We should change that, but we can't without deprecation...79 checker = FormatChecker()80 with self.assertRaises(FormatError):81 checker.check(instance="not-an-ipv4", format="ipv4")82 83 def test_repr(self):84 checker = FormatChecker(formats=())85 checker.checks("foo")(lambda thing: True) # pragma: no cover86 checker.checks("bar")(lambda thing: True) # pragma: no cover87 checker.checks("baz")(lambda thing: True) # pragma: no cover88 self.assertEqual(89 repr(checker),90 "<FormatChecker checkers=['bar', 'baz', 'foo']>",91 )92 