def test_optional_validation(self): """Fields are required by default but can be made optional""" fields = [ IntegerField(required=False), UnicodeField(required=False), ObjectField(required=False), ArrayField(required=False), IsoDateString(required=False), # subschema tested elsewhere... ] for field in fields: assert field.validate(None)
def test_array_validation(self): field = ArrayField(int) assert field.validate([1, 2, 3]) with self.assertRaises(Invalid): field.validate(["a", 1, 1.0]) with self.assertRaises(Invalid): field.validate(None) with self.assertRaises(Invalid): field.validate({1: "A", 2: "B"}) with self.assertRaises(Invalid): field.validate("hiya") field = ArrayField(int, required=False) assert field.validate([1, 2, 3]) assert field.validate(None) with self.assertRaises(Invalid): field.validate(1) class SomeSchema(Schema): good = IntegerField() field = ArrayField(SomeSchema, required=False) assert field.validate([SomeSchema(good=1)]) assert field.validate([{"good": 1}]) assert field.validate(None) with self.assertRaises(Invalid): field.validate([SomeSchema(good="bad")]) with self.assertRaises(Invalid): field.validate([{"good": "bad"}]) with self.assertRaises(Invalid): field.validate([{"wat": "whatever"}])
class My2(Schema): stuff = ArrayField(Sub, required=True)
class My(Schema): stuff = ArrayField(Sub, required=False)
class Outer(Schema): many = ArrayField(Inner)
class SomeSchema(Schema): great = ArrayField(int, required=False)
def test_array_serialization(self): field = ArrayField(int) flat = [1, 2, 3] self.assertEqual(flat, field.serialize(flat)) self.assertEqual(None, field.serialize(None)) self.assertEqual([], field.serialize([])) self.assertEqual("wow", field.serialize("wow")) class SomeSchema(Schema): wat = IntegerField() field = ArrayField(Subschema) source = [SomeSchema(wat=1), SomeSchema(wat=2)] self.assertEqual([{"wat": 1}, {"wat": 2}], field.serialize(source)) source = [SomeSchema(), SomeSchema()] self.assertEqual([], field.serialize(source)) self.assertEqual([{"wat": None}, {"wat": None}], field.serialize(source, implicit_nulls=False))
class SomeSchema(Schema): great = ArrayField(int)
class Myschema(Schema): maybe = ArrayField()
class Source(Schema): together = ArrayField(IntegerField()) sep_1 = IntegerField() sep_2 = IntegerField()
class SecondSchema(Schema): those = ArrayField(ManySchema)
class Conversation(Schema): numbers = ArrayField(IntegerField()) conversants = ArrayField(Subschema(Person))
class Some(Schema): wow = ArrayField()