From 8dc3296bd59729c711aac5a0e117281db179428d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Fri, 13 Jul 2018 15:03:35 +0200 Subject: [PATCH] Schema change for IP range, use validator instead of type Custom types became rather useless in Cerberus 1.0 since the type checker is cripled (doesn't know field name, cannot return useful/detailed error messages). Instead we use a validator now. --- pillar/api/custom_field_validation.py | 2 +- pillar/api/eve_settings.py | 2 +- tests/test_api/test_cerberus.py | 10 +++++++++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/pillar/api/custom_field_validation.py b/pillar/api/custom_field_validation.py index e4d0f9db..1decfb85 100644 --- a/pillar/api/custom_field_validation.py +++ b/pillar/api/custom_field_validation.py @@ -143,7 +143,7 @@ class ValidateCustomFields(Validator): if not value: self._error(field, "Value is required once the document was created") - def _validate_type_iprange(self, field_name: str, value: str): + def _validator_iprange(self, field_name: str, value: str): """Ensure the field contains a valid IP address. Supports both IPv6 and IPv4 ranges. Requires the IPy module. diff --git a/pillar/api/eve_settings.py b/pillar/api/eve_settings.py index 40b259db..6c93c5c6 100644 --- a/pillar/api/eve_settings.py +++ b/pillar/api/eve_settings.py @@ -227,7 +227,7 @@ organizations_schema = { 'start': {'type': 'binary', 'required': True}, 'end': {'type': 'binary', 'required': True}, 'prefix': {'type': 'integer', 'required': True}, - 'human': {'type': 'iprange', 'required': True}, + 'human': {'type': 'string', 'required': True, 'validator': 'iprange'}, } }, }, diff --git a/tests/test_api/test_cerberus.py b/tests/test_api/test_cerberus.py index 54dee688..d0079229 100644 --- a/tests/test_api/test_cerberus.py +++ b/tests/test_api/test_cerberus.py @@ -173,7 +173,7 @@ class NodeValidationTest(ValidationTest): class IPRangeValidatorTest(ValidationTest): - schema = {'iprange': {'type': 'iprange', 'required': True}} + schema = {'iprange': {'type': 'string', 'required': True, 'validator': 'iprange'}} def assertValid(self, document, schema=None): return super().assertValid(document, schema or self.schema) @@ -199,3 +199,11 @@ class IPRangeValidatorTest(ValidationTest): self.assertValid({'iprange': '127.0.0.0/8'}) self.assertInvalid({'iprange': '127.0.0.0/0'}) self.assertInvalid({'iprange': 'garbled'}) + + def test_descriptive_error_message(self): + is_valid = self.validator.validate({'iprange': '::/0'}, self.schema) + self.assertFalse(is_valid) + self.assertEquals(1, len(self.validator._errors)) + err = self.validator._errors[0] + self.assertEquals(('iprange', ), err.document_path) + self.assertEquals(('Zero-length prefix is not allowed',), err.info)