def test_bad_list_field(self): class ASchema(Schema): id = fields.Int() with pytest.raises(ValueError): fields.List("string") with pytest.raises(ValueError) as excinfo: fields.List(ASchema) expected_msg = ("The list elements must be a subclass or instance of " "marshmallow_muffin.base.FieldABC") assert expected_msg in str(excinfo)
class UserSchema(Schema): name = fields.String() age = fields.Float() created = fields.DateTime() created_formatted = fields.DateTime(format="%Y-%m-%d", attribute="created", dump_only=True) created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) updated = fields.DateTime() updated_local = fields.LocalDateTime(attribute="updated", dump_only=True) species = fields.String(attribute="SPECIES") id = fields.String(default="no-id") uppername = Uppercased(attribute="name", dump_only=True) homepage = fields.Url() email = fields.Email() balance = fields.Decimal() is_old = fields.Method("get_is_old") lowername = fields.Function(get_lowername) registered = fields.Boolean() hair_colors = fields.List(fields.Raw) sex_choices = fields.List(fields.Raw) finger_count = fields.Integer() uid = fields.UUID() time_registered = fields.Time() birthdate = fields.Date() activation_date = fields.Date() since_created = fields.TimeDelta() sex = fields.Str(validate=validate.OneOf(["male", "female"])) various_data = fields.Dict() class Meta: render_module = simplejson def get_is_old(self, obj): if obj is None: return missing if isinstance(obj, dict): age = obj.get("age") else: age = obj.age try: return age > 80 except TypeError as te: raise ValidationError(str(te)) @post_load def make_user(self, data): return User(**data)
def test_list_field_work_with_generator_single_value(self): def custom_generator(): yield dt.datetime.utcnow() obj = DateTimeList(custom_generator()) field = fields.List(fields.DateTime) result = field.serialize("dtimes", obj) assert len(result) == 1
def test_unbound_field_root_returns_none(self): field = fields.Str() assert field.root is None inner_field = fields.Nested(self.MySchema()) outer_field = fields.List(inner_field) assert outer_field.root is None assert inner_field.root is None
def test_list_field_work_with_set(self): custom_set = {1, 2, 3} obj = IntegerList(custom_set) field = fields.List(fields.Int) result = field.serialize("ints", obj) assert len(result) == 3 assert 1 in result assert 2 in result assert 3 in result
def test_list_field_work_with_generators_error(self): def custom_generator(): for dtime in [dt.datetime.utcnow(), "m", dt.datetime.now()]: yield dtime obj = DateTimeList(custom_generator()) field = fields.List(fields.DateTime) with pytest.raises(ValidationError): field.serialize("dtimes", obj)
def test_list_field_work_with_generators_multiple_values(self): def custom_generator(): for dtime in [dt.datetime.utcnow(), dt.datetime.now()]: yield dtime obj = DateTimeList(custom_generator()) field = fields.List(fields.DateTime) result = field.serialize("dtimes", obj) assert len(result) == 2
def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( self): # noqa def custom_generator(): yield yield obj = DateTimeList(custom_generator()) field = fields.List(fields.DateTime, allow_none=True) result = field.serialize("dtimes", obj) assert len(result) == 2 assert result[0] is None assert result[1] is None
class BlobSchema(Schema): polarity = fields.Float() subjectivity = fields.Float() chunks = fields.List(fields.String, attribute="noun_phrases") tags = fields.Raw() discrete_sentiment = fields.Method("get_discrete_sentiment") word_count = fields.Function(lambda obj: len(obj.words)) def get_discrete_sentiment(self, obj): if obj.polarity > 0.1: return "positive" elif obj.polarity < -0.1: return "negative" else: return "neutral"
def test_list_field_work_with_custom_class_with_iterator_protocol(self): class IteratorSupportingClass: def __init__(self, iterable): self.iterable = iterable def __iter__(self): return iter(self.iterable) ints = IteratorSupportingClass([1, 2, 3]) obj = IntegerList(ints) field = fields.List(fields.Int) result = field.serialize("ints", obj) assert len(result) == 3 assert result[0] == 1 assert result[1] == 2 assert result[2] == 3
class MySchema(Schema): foo = fields.Field() bar = fields.List(fields.Str()) baz = fields.Tuple([fields.Str(), fields.Int()])
def test_list_field_serialize_none_returns_none(self): obj = DateTimeList(None) field = fields.List(fields.DateTime) assert field.serialize("dtimes", obj) is None
def test_datetime_list_serialize_single_value(self): obj = DateTimeList(dt.datetime.utcnow()) field = fields.List(fields.DateTime) result = field.serialize("dtimes", obj) assert len(result) == 1 assert type(result[0]) == str
def test_list_field_with_error(self): obj = DateTimeList(["invaliddate"]) field = fields.List(fields.DateTime) with pytest.raises(ValidationError): field.serialize("dtimes", obj)
def test_datetime_list_field(self): obj = DateTimeList([dt.datetime.utcnow(), dt.datetime.now()]) field = fields.List(fields.DateTime) result = field.serialize("dtimes", obj) assert all([type(each) == str for each in result])
class BlogSchema(Schema): title = fields.String() user = fields.Nested(UserSchema) collaborators = fields.Nested(UserSchema, many=True) categories = fields.List(fields.String) id = fields.String()