Skip to content

Commit 822c75f

Browse files
author
Itamar Turner-Trauring
committed
Better error message for additionalProperties: false when there are patternProperties.
1 parent ee2de6d commit 822c75f

2 files changed

Lines changed: 32 additions & 2 deletions

File tree

jsonschema/_validators.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,18 @@ def additionalProperties(validator, aP, instance, schema):
2929
for error in validator.descend(instance[extra], aP, path=extra):
3030
yield error
3131
elif not aP and extras:
32-
error = "Additional properties are not allowed (%s %s unexpected)"
33-
yield ValidationError(error % _utils.extras_msg(extras))
32+
if "patternProperties" in schema:
33+
patterns = sorted(schema["patternProperties"].keys())
34+
if len(extras) == 1:
35+
verb = "does"
36+
else:
37+
verb = "do"
38+
error = "%s %s not match any of the regexs: %s" % (
39+
", ".join(map(repr, sorted(extras))), verb, ", ".join(patterns))
40+
yield ValidationError(error)
41+
else:
42+
error = "Additional properties are not allowed (%s %s unexpected)"
43+
yield ValidationError(error % _utils.extras_msg(extras))
3444

3545

3646
def items(validator, items, instance, schema):

jsonschema/tests/test_validators.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,26 @@ def test_invalid_format_default_message(self):
191191
self.assertIn(repr("thing"), message)
192192
self.assertIn("is not a", message)
193193

194+
def test_additionalProperties_false_patternProperties(self):
195+
schema = {u"type": u"object",
196+
u"additionalProperties": False,
197+
u"patternProperties": {
198+
u"$abc^": {u"type": u"string"},
199+
u"$def^": {u"type": u"string"}
200+
}}
201+
message = self.message_for({u"zebra": 123}, schema,
202+
cls=Draft4Validator)
203+
self.assertEqual(
204+
message,
205+
"{} does not match any of the regexs: $abc^, $def^".format(
206+
repr(u"zebra")))
207+
message = self.message_for({u"zebra": 123, u"fish": 456}, schema,
208+
cls=Draft4Validator)
209+
self.assertEqual(
210+
message,
211+
"{}, {} do not match any of the regexs: $abc^, $def^".format(
212+
repr(u"fish"), repr(u"zebra")))
213+
194214

195215
class TestValidationErrorDetails(unittest.TestCase):
196216
# TODO: These really need unit tests for each individual validator, rather

0 commit comments

Comments
 (0)