Exemple #1
0
    def test_include_data_load_without_schema_loads_only_ids(self, post):
        class PostInnerSchemalessSchema(Schema):
            id = fields.Str()
            comments = fields.Relationship(
                "http://test.test/posts/{id}/comments/",
                related_url_kwargs={"id": "<id>"},
                data_key="post-comments",
                load_from="post-comments",
                many=True,
                type_="comments",
            )

            class Meta:
                type_ = "posts"
                strict = True

        serialized = unpack(
            PostSchema(include_data=("author", "post_comments")).dump(post))

        if _MARSHMALLOW_VERSION_INFO[0] >= 3:
            from marshmallow import INCLUDE

            load_kwargs = {"unknown": INCLUDE}
        else:
            load_kwargs = {}

        loaded = unpack(
            PostInnerSchemalessSchema(**load_kwargs).load(serialized))

        assert "comments" in loaded
        assert len(loaded["comments"]) == len(post.comments)
        for comment_id in loaded["comments"]:
            assert int(comment_id) in [c.id for c in post.comments]
    def test_include_data_load_without_schema_loads_only_ids(
            self, post):
        class PostInnerSchemalessSchema(Schema):
            id = fields.Str()
            comments = fields.Relationship(
                'http://test.test/posts/{id}/comments/',
                related_url_kwargs={'id': '<id>'},
                data_key='post-comments',
                load_from='post-comments',
                many=True, type_='comments'
            )

            class Meta:
                type_ = 'posts'
                strict = True

        serialized = unpack(PostSchema(
            include_data=('author', 'post_comments')
        ).dump(post))

        if _MARSHMALLOW_VERSION_INFO[0] >= 3:
            from marshmallow import INCLUDE
            load_kwargs = {'unknown': INCLUDE}
        else:
            load_kwargs = {}

        loaded = unpack(PostInnerSchemalessSchema(**load_kwargs).load(serialized))

        assert 'comments' in loaded
        assert len(loaded['comments']) == len(post.comments)
        for comment_id in loaded['comments']:
            assert int(comment_id) in [c.id for c in post.comments]
Exemple #3
0
    def test_include_data_load_without_schema_loads_only_ids(
            self, post):
        class PostInnerSchemalessSchema(Schema):
            id = fields.Str()
            comments = fields.Relationship(
                'http://test.test/posts/{id}/comments/',
                related_url_kwargs={'id': '<id>'},
                data_key='post-comments',
                load_from='post-comments',
                many=True, type_='comments'
            )

            class Meta:
                type_ = 'posts'
                strict = True

        serialized = unpack(PostSchema(
            include_data=('author', 'post_comments')
        ).dump(post))

        loaded = unpack(PostInnerSchemalessSchema().load(serialized))

        assert 'comments' in loaded
        assert len(loaded['comments']) == len(post.comments)
        for comment_id in loaded['comments']:
            assert int(comment_id) in [c.id for c in post.comments]
Exemple #4
0
    def test_deserializing_missing_required_relationship(self):
        class ArticleSchemaRequiredRelationships(Schema):
            id = fields.Integer()
            body = fields.String()
            author = fields.Relationship(
                dump_only=False,
                include_resource_linkage=True,
                many=False,
                type_="people",
                required=True,
            )
            comments = fields.Relationship(
                dump_only=False,
                include_resource_linkage=True,
                many=True,
                type_="comments",
                required=True,
            )

            class Meta:
                type_ = "articles"
                strict = True

        article = self.article.copy()
        article["data"]["relationships"] = {}

        with pytest.raises(ValidationError) as excinfo:
            unpack(ArticleSchemaRequiredRelationships().load(article))
        errors = excinfo.value.messages

        assert assert_relationship_error("author", errors["errors"])
        assert assert_relationship_error("comments", errors["errors"])
Exemple #5
0
    def test_load_single(self):
        serialized = unpack(PolygonSchema().dump(self.shape))
        loaded = unpack(PolygonSchema().load(serialized))

        assert loaded["meta"] == self.shape["meta"]
        assert loaded["resource_meta"] == self.shape["resource_meta"]
        assert loaded["document_meta"] == self.shape["document_meta"]
Exemple #6
0
    def test_load_many(self):
        serialized = unpack(PolygonSchema(many=True).dump(self.shapes))
        loaded = unpack(PolygonSchema(many=True).load(serialized))

        first = loaded[0]
        assert first["meta"] == self.shapes[0]["meta"]
        assert first["resource_meta"] == self.shapes[0]["resource_meta"]
        assert first["document_meta"] == self.shapes[0]["document_meta"]

        second = loaded[1]
        assert second["meta"] == self.shapes[1]["meta"]
        assert second["resource_meta"] == self.shapes[1]["resource_meta"]
        assert second["document_meta"] == self.shapes[1]["document_meta"]
Exemple #7
0
    def test_include_data_load(self, post):
        serialized = unpack(
            PostSchema(include_data=("author", "post_comments",
                                     "post_comments.author")).dump(post))
        loaded = unpack(PostSchema().load(serialized))

        assert "author" in loaded
        assert loaded["author"]["id"] == str(post.author.id)
        assert loaded["author"]["first_name"] == post.author.first_name

        assert "comments" in loaded
        assert len(loaded["comments"]) == len(post.comments)
        for comment in loaded["comments"]:
            assert "body" in comment
            assert comment["id"] in [str(c.id) for c in post.comments]
Exemple #8
0
    def test_include_data_load(self, post):
        serialized = unpack(PostSchema(
            include_data=('author', 'post_comments', 'post_comments.author')
        ).dump(post))
        loaded = unpack(PostSchema().load(serialized))

        assert 'author' in loaded
        assert loaded['author']['id'] == str(post.author.id)
        assert loaded['author']['first_name'] == post.author.first_name

        assert 'comments' in loaded
        assert len(loaded['comments']) == len(post.comments)
        for comment in loaded['comments']:
            assert 'body' in comment
            assert comment['id'] in [str(c.id) for c in post.comments]
Exemple #9
0
    def test_include_self_referential_relationship_many(self):
        class RefSchema(Schema):
            id = fields.Str()
            data = fields.Str()
            children = fields.Relationship(schema="self", many=True)

            class Meta:
                type_ = "refs"

        obj = {
            "id":
            "1",
            "data":
            "data1",
            "children": [{
                "id": "2",
                "data": "data2"
            }, {
                "id": "3",
                "data": "data3"
            }],
        }
        data = unpack(RefSchema(include_data=("children", )).dump(obj))
        assert "included" in data
        assert len(data["included"]) == 2
        for child in data["included"]:
            assert child["attributes"]["data"] == "data%s" % child["id"]
Exemple #10
0
 def test_include_data_with_single(self, post):
     data = unpack(PostSchema(include_data=("author", )).dump(post))
     assert "included" in data
     assert len(data["included"]) == 1
     author = data["included"][0]
     assert "attributes" in author
     assert "first_name" in author["attributes"]
Exemple #11
0
 def test_dump_to(self, post):
     data = unpack(PostSchema().dump(post))
     assert 'data' in data
     assert 'attributes' in data['data']
     assert 'title' in data['data']['attributes']
     assert 'relationships' in data['data']
     assert 'post-comments' in data['data']['relationships']
Exemple #12
0
    def test_include_data_with_schema_context(self, post):
        class ContextTestSchema(Schema):
            id = fields.Str()
            from_context = fields.Method('get_from_context')

            def get_from_context(self, obj):
                return self.context['some_value']

            class Meta:
                type_ = 'people'

        class PostContextTestSchema(PostSchema):
            author = fields.Relationship(
                'http://test.test/posts/{id}/author/',
                related_url_kwargs={'id': '<id>'},
                schema=ContextTestSchema, many=False
            )

            class Meta(PostSchema.Meta):
                pass

        serialized = unpack(PostContextTestSchema(
            include_data=('author',),
            context={'some_value': 'Hello World'}
        ).dump(post))

        for included in serialized['included']:
            if included['type'] == 'people':
                assert 'from_context' in included['attributes']
                assert included['attributes']['from_context'] == 'Hello World'
Exemple #13
0
    def test_include_self_referential_relationship_many(self):
        class RefSchema(Schema):
            id = fields.Str()
            data = fields.Str()
            children = fields.Relationship(schema='self', many=True)

            class Meta:
                type_ = 'refs'

        obj = {
            'id': '1',
            'data': 'data1',
            'children': [
                {
                    'id': '2',
                    'data': 'data2'
                },
                {
                    'id': '3',
                    'data': 'data3'
                }
            ]
        }
        data = unpack(RefSchema(include_data=('children', )).dump(obj))
        assert 'included' in data
        assert len(data['included']) == 2
        for child in data['included']:
            assert child['attributes']['data'] == 'data%s' % child['id']
Exemple #14
0
    def test_include_data_with_schema_context(self, post):
        class ContextTestSchema(Schema):
            id = fields.Str()
            from_context = fields.Method("get_from_context")

            def get_from_context(self, obj):
                return self.context["some_value"]

            class Meta:
                type_ = "people"

        class PostContextTestSchema(PostSchema):
            author = fields.Relationship(
                "http://test.test/posts/{id}/author/",
                related_url_kwargs={"id": "<id>"},
                schema=ContextTestSchema,
                many=False,
            )

            class Meta(PostSchema.Meta):
                pass

        serialized = unpack(
            PostContextTestSchema(include_data=("author", ),
                                  context={
                                      "some_value": "Hello World"
                                  }).dump(post))

        for included in serialized["included"]:
            if included["type"] == "people":
                assert "from_context" in included["attributes"]
                assert included["attributes"]["from_context"] == "Hello World"
Exemple #15
0
 def test_include_data_with_many(self, post):
     data = unpack(PostSchema(include_data=('post_comments', 'post_comments.author')).dump(post))
     assert 'included' in data
     assert len(data['included']) == 4
     first_comment = [i for i in data['included'] if i['type'] == 'comments'][0]
     assert 'attributes' in first_comment
     assert 'body' in first_comment['attributes']
Exemple #16
0
 def test_self_link_quoted(self, author):
     data = unpack(AuthorAutoSelfLinkFirstLastSchema().dump(author))
     assert 'links' in data
     assert data['links']['self'] == quote('/authors/{} {}'.format(
         author.first_name,
         author.last_name,
     ))
Exemple #17
0
    def test_self_link_many(self, app, posts):
        data = unpack(self.PostFlaskSchema(many=True).dump(posts))
        assert 'links' in data
        assert data['links']['self'] == '/posts/'

        assert 'links' in data['data'][0]
        assert data['data'][0]['links']['self'] == '/posts/{}/'.format(posts[0].id)
Exemple #18
0
 def test_dump_to(self, post):
     data = unpack(PostSchema().dump(post))
     assert "data" in data
     assert "attributes" in data["data"]
     assert "title" in data["data"]["attributes"]
     assert "relationships" in data["data"]
     assert "post-comments" in data["data"]["relationships"]
Exemple #19
0
 def test_include_data_with_single(self, post):
     data = unpack(PostSchema(include_data=('author',)).dump(post))
     assert 'included' in data
     assert len(data['included']) == 1
     author = data['included'][0]
     assert 'attributes' in author
     assert 'first_name' in author['attributes']
Exemple #20
0
    def test_self_link_many(self, authors):
        data = unpack(AuthorAutoSelfLinkSchema(many=True).dump(authors))
        assert 'links' in data
        assert data['links']['self'] == '/authors/'

        assert 'links' in data['data'][0]
        assert data['data'][0]['links']['self'] == '/authors/{}'.format(
            authors[0].id)
Exemple #21
0
    def test_load_bulk_id_fields(self):
        request = {'data': [{'id': '1', 'type': 'people'}]}

        result = unpack(AuthorSchema(only=('id', ), many=True).load(request))
        assert type(result) is list

        response = result[0]
        assert response['id'] == request['data'][0]['id']
    def test_self_link_many(self, app, posts):
        data = unpack(self.PostFlaskSchema(many=True).dump(posts))
        assert "links" in data
        assert data["links"]["self"] == "/posts/"

        assert "links" in data["data"][0]
        assert data["data"][0]["links"]["self"] == "/posts/{}/".format(
            posts[0].id)
    def test_load_bulk_id_fields(self):
        request = {"data": [{"id": "1", "type": "people"}]}

        result = unpack(AuthorSchema(only=("id", ), many=True).load(request))
        assert type(result) is list

        response = result[0]
        assert response["id"] == request["data"][0]["id"]
    def test_self_link_many(self, authors):
        data = unpack(AuthorAutoSelfLinkSchema(many=True).dump(authors))
        assert "links" in data
        assert data["links"]["self"] == "/authors/"

        assert "links" in data["data"][0]
        assert data["data"][0]["links"]["self"] == "/authors/{}".format(
            authors[0].id)
Exemple #25
0
    def test_dump_empty_list(self):
        data = unpack(AuthorSchema(many=True).dump([]))

        assert "data" in data
        assert type(data["data"]) is list
        assert len(data["data"]) == 0
        assert "links" in data
        assert data["links"]["self"] == "/authors/"
Exemple #26
0
    def test_dump_empty_list(self):
        data = unpack(AuthorSchema(many=True).dump([]))

        assert 'data' in data
        assert type(data['data']) is list
        assert len(data['data']) == 0
        assert 'links' in data
        assert data['links']['self'] == '/authors/'
Exemple #27
0
    def test_include_data_load_null(self, post_with_null_author):
        serialized = unpack(PostSchema(
            include_data=('author', 'post_comments')
        ).dump(post_with_null_author))

        with pytest.raises(ValidationError) as excinfo:
            PostSchema().load(serialized)
        err = excinfo.value
        assert 'author' in err.field_names
Exemple #28
0
 def test_load_with_inflection_and_load_from_override(self):
     schema = AuthorSchemaWithOverrideInflection()
     data = unpack(
         schema.load(
             make_serialized_author({
                 'firstName': 'Steve',
                 'last-name': 'Loria',
             })))
     assert data['first_name'] == 'Steve'
     assert data['last_name'] == 'Loria'
 def test_load_with_inflection_and_load_from_override(self):
     schema = AuthorSchemaWithOverrideInflection()
     data = unpack(
         schema.load(
             make_serialized_author({
                 "firstName": "Steve",
                 "last-name": "Loria"
             })))
     assert data["first_name"] == "Steve"
     assert data["last_name"] == "Loria"
Exemple #30
0
    def test_include_data_load_null(self, post_with_null_author):
        serialized = unpack(
            PostSchema(
                include_data=("author",
                              "post_comments")).dump(post_with_null_author))

        with pytest.raises(ValidationError) as excinfo:
            PostSchema().load(serialized)
        err = excinfo.value
        assert "author" in err.args[0]