test_customization.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # -*- coding: utf-8 -*-
  2. import cerberus
  3. from cerberus.tests import assert_fail, assert_success
  4. from cerberus.tests.conftest import sample_schema
  5. def test_contextual_data_preservation():
  6. class InheritedValidator(cerberus.Validator):
  7. def __init__(self, *args, **kwargs):
  8. if 'working_dir' in kwargs:
  9. self.working_dir = kwargs['working_dir']
  10. super(InheritedValidator, self).__init__(*args, **kwargs)
  11. def _validate_type_test(self, value):
  12. if self.working_dir:
  13. return True
  14. assert 'test' in InheritedValidator.types
  15. v = InheritedValidator({'test': {'type': 'list',
  16. 'schema': {'type': 'test'}}},
  17. working_dir='/tmp')
  18. assert_success({'test': ['foo']}, validator=v)
  19. def test_docstring_parsing():
  20. class CustomValidator(cerberus.Validator):
  21. def _validate_foo(self, argument, field, value):
  22. """ {'type': 'zap'} """
  23. pass
  24. def _validate_bar(self, value):
  25. """ Test the barreness of a value.
  26. The rule's arguments are validated against this schema:
  27. {'type': 'boolean'}
  28. """
  29. pass
  30. assert 'foo' in CustomValidator.validation_rules
  31. assert 'bar' in CustomValidator.validation_rules
  32. def test_issue_265():
  33. class MyValidator(cerberus.Validator):
  34. def _validator_oddity(self, field, value):
  35. if not value & 1:
  36. self._error(field, "Must be an odd number")
  37. v = MyValidator(schema={'amount': {'validator': 'oddity'}})
  38. assert_success(document={'amount': 1}, validator=v)
  39. assert_fail(document={'amount': 2}, validator=v,
  40. error=('amount', (), cerberus.errors.CUSTOM, None,
  41. ('Must be an odd number',)))
  42. def test_schema_validation_can_be_disabled_in_schema_setter():
  43. class NonvalidatingValidator(cerberus.Validator):
  44. """
  45. Skips schema validation to speed up initialization
  46. """
  47. @cerberus.Validator.schema.setter
  48. def schema(self, schema):
  49. if schema is None:
  50. self._schema = None
  51. elif self.is_child:
  52. self._schema = schema
  53. elif isinstance(schema, cerberus.schema.DefinitionSchema):
  54. self._schema = schema
  55. else:
  56. self._schema = cerberus.schema.UnvalidatedSchema(schema)
  57. v = NonvalidatingValidator(schema=sample_schema)
  58. assert v.validate(document={'an_integer': 1})
  59. assert not v.validate(document={'an_integer': 'a'})