class SpecialComponent(components.Component): foo = fields.IntField(required=False) bar = fields.IntField(required=False) def validate(self, data): super().validate(data) if ('foo' in data) == ('bar' in data): raise exceptions.ValidationError("Only one of 'foo' or 'bar' can be set.") def validate_bar(self, data): if 'bar' in data and data['bar'] % 2 != 0: raise exceptions.ValidationError("'bar' must be even.")
def test_bad_type(self): field = fields.IntField(required=True) field.name = 'widgets' with self.assertRaises(exceptions.ValidationError) as e: field.validate({'widgets': 'a'}) self.assertEqual(str(e.exception), "'widgets' must be an integer.")
def test_explicit_required(self): field = fields.IntField(required=True) field.name = 'widgets' with self.assertRaises(exceptions.ValidationError) as e: field.validate({}) self.assertEqual(str(e.exception), "'widgets' is required.")
def test_over_max(self): field = fields.IntField(min=0, max=100, required=True) field.name = 'widgets' with self.assertRaises(exceptions.ValidationError) as e: field.validate({'widgets': 200}) self.assertEqual(str(e.exception), "'widgets' must be less than or equal to 100.")
def test_in_range(self): field = fields.IntField(min=0, max=100, required=True) field.name = 'widgets' self.assertIsNone(field.validate({'widgets': 42}))
def test_not_required(self): field = fields.IntField(required=False) field.name = 'widgets' self.assertIsNone(field.validate({}))