Ejemplo n.º 1
0
    def test_function_field_does_not_swallow_attribute_error(self, user):
        def raise_error(obj):
            raise AttributeError()

        field = fields.Function(serialize=raise_error)
        with pytest.raises(AttributeError):
            field.serialize("key", user)
Ejemplo n.º 2
0
 def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(
         self):
     field = fields.Function(
         serialize=lambda val: val.lower(),
         deserialize=lambda val: val.upper(),
     )
     assert field.dump_only is False
Ejemplo n.º 3
0
    def test_function_field_passed_serialize_with_context(
            self, user, monkeypatch):
        class Parent(Schema):
            pass

        field = fields.Function(
            serialize=lambda obj, context: obj.name.upper() + context["key"])
        field.parent = Parent(context={"key": "BAR"})
        assert "FOOBAR" == field.serialize("key", user)
Ejemplo n.º 4
0
class UserMetaSchema(Schema):
    """The equivalent of the UserSchema, using the ``fields`` option."""

    uppername = Uppercased(attribute="name", dump_only=True)
    balance = fields.Decimal()
    is_old = fields.Method("get_is_old")
    lowername = fields.Function(get_lowername)
    updated_local = fields.LocalDateTime(attribute="updated", dump_only=True)
    species = fields.String(attribute="SPECIES")
    homepage = fields.Url()
    email = fields.Email()
    various_data = fields.Dict()

    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))

    class Meta:
        fields = (
            "name",
            "age",
            "created",
            "updated",
            "id",
            "homepage",
            "uppername",
            "email",
            "balance",
            "is_old",
            "lowername",
            "updated_local",
            "species",
            "registered",
            "hair_colors",
            "sex_choices",
            "finger_count",
            "uid",
            "time_registered",
            "birthdate",
            "since_created",
            "various_data",
        )
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
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"
Ejemplo n.º 7
0
 def test_function_field_passed_uncallable_object(self):
     with pytest.raises(ValueError):
         fields.Function("uncallable")
Ejemplo n.º 8
0
 def test_function_field_load_only(self):
     field = fields.Function(deserialize=lambda obj: None)
     assert field.load_only
Ejemplo n.º 9
0
 def test_function_field_passed_serialize(self, user):
     field = fields.Function(serialize=lambda obj: obj.name.upper())
     assert "FOO" == field.serialize("key", user)
Ejemplo n.º 10
0
 def test_function_field_passed_serialize_only_is_dump_only(self, user):
     field = fields.Function(serialize=lambda obj: obj.name.upper())
     assert field.dump_only is True
Ejemplo n.º 11
0
 def test_function_with_uncallable_param(self):
     with pytest.raises(ValueError):
         fields.Function("uncallable")
Ejemplo n.º 12
0
 class MySchema(Schema):
     friends = fields.Function(deserialize=get_split_words)
Ejemplo n.º 13
0
class UserAdditionalSchema(Schema):
    lowername = fields.Function(lambda obj: obj.name.lower())

    class Meta:
        additional = ("name", "age", "created", "email")