Beispiel #1
0
def test_invalid_type_on_polymorphic_relation(single_company,
                                              research_project_factory,
                                              client):
    response = client.get(
        reverse("company-detail", kwargs={'pk': single_company.pk}))
    content = load_json(response.content)
    assert content["data"]["relationships"]["currentProject"]["data"][
        "type"] == "artProjects"

    research_project = research_project_factory()
    content["data"]["relationships"]["currentProject"]["data"] = {
        "type": "invalidProjects",
        "id": research_project.pk
    }
    response = client.put(reverse("company-detail",
                                  kwargs={'pk': single_company.pk}),
                          data=json.dumps(content),
                          content_type='application/vnd.api+json')
    assert response.status_code == 409
    content = load_json(response.content)
    assert len(content["errors"]) is 1
    assert content["errors"][0]["status"] == "409"
    try:
        assert content["errors"][0]["detail"] == \
            "Incorrect relation type. Expected one of [researchProjects, artProjects], " \
            "received invalidProjects."
    except AssertionError:
        # Available type list order isn't enforced
        assert content["errors"][0]["detail"] == \
            "Incorrect relation type. Expected one of [artProjects, researchProjects], " \
            "received invalidProjects."
    def test_resource_name_precendence(self, client):
        # default
        response = client.get(reverse("comment-list"))
        data = load_json(response.content)['data'][0]
        assert (data.get('type') == 'comments'), (
            'resource_name from model incorrect on list')

        # model > default
        models.Comment.__bases__ += (_PatchedModel,)
        response = client.get(reverse("comment-list"))
        data = load_json(response.content)['data'][0]
        assert (data.get('type') == 'resource_name_from_JSONAPIMeta'), (
            'resource_name from model incorrect on list')

        # serializer > model
        serializers.CommentSerializer.Meta.resource_name = "resource_name_from_serializer"
        response = client.get(reverse("comment-list"))
        data = load_json(response.content)['data'][0]
        assert (data.get('type') == 'resource_name_from_serializer'), (
            'resource_name from serializer incorrect on list')

        # view > serializer > model
        views.CommentViewSet.resource_name = 'resource_name_from_view'
        response = client.get(reverse("comment-list"))
        data = load_json(response.content)['data'][0]
        assert (data.get('type') == 'resource_name_from_view'), (
            'resource_name from view incorrect on list')
    def test_resource_name_precendence(self, client, monkeypatch):
        # default
        response = client.get(reverse("comment-list"))
        data = load_json(response.content)['data'][0]
        assert (data.get('type') == 'comments'), (
            'resource_name from model incorrect on list')

        # model > default
        models.Comment.__bases__ += (_PatchedModel, )
        response = client.get(reverse("comment-list"))
        data = load_json(response.content)['data'][0]
        assert (data.get('type') == 'resource_name_from_JSONAPIMeta'), (
            'resource_name from model incorrect on list')

        # serializer > model
        monkeypatch.setattr(serializers.CommentSerializer.Meta,
                            'resource_name', 'resource_name_from_serializer',
                            False)
        response = client.get(reverse("comment-list"))
        data = load_json(response.content)['data'][0]
        assert (data.get('type') == 'resource_name_from_serializer'), (
            'resource_name from serializer incorrect on list')

        # view > serializer > model
        monkeypatch.setattr(views.CommentViewSet, 'resource_name',
                            'resource_name_from_view', False)
        response = client.get(reverse("comment-list"))
        data = load_json(response.content)['data'][0]
        assert (data.get('type') == 'resource_name_from_view'), (
            'resource_name from view incorrect on list')
Beispiel #4
0
def _check_relationship_and_included_comment_type_are_the_same(django_client, url):
    response = django_client.get(url + "?include=comments")
    data = load_json(response.content).get('data')[0]
    comment = load_json(response.content).get('included')[0]

    comment_relationship_type = data.get('relationships').get('comments').get('data')[0].get('type')
    comment_included_type = comment.get('type')

    assert comment_relationship_type == comment_included_type, "The resource type seen in the relationships and included do not match"
Beispiel #5
0
def _check_resource_and_relationship_comment_type_match(django_client):
    entry_response = django_client.get(reverse("entry-list"))
    comment_response = django_client.get(reverse("comment-list"))

    comment_resource_type = load_json(comment_response.content).get('data')[0].get('type')
    comment_relationship_type = load_json(entry_response.content).get(
        'data')[0].get('relationships').get('comments').get('data')[0].get('type')

    assert comment_resource_type == comment_relationship_type, "The resource type seen in the relationships and head resource do not match"
def test_deep_included_data_on_list(multiple_entries, client):
    response = client.get(
        reverse("entry-list") + '?include=comments,comments.author,'
        'comments.author.bio&page_size=5')
    included = load_json(response.content).get('included')

    assert len(load_json(response.content)['data']) == len(
        multiple_entries), 'Incorrect entry count'
    assert [x.get('type') for x in included] == [
        'authorBios', 'authorBios', 'authors', 'authors', 'comments',
        'comments'
    ], 'List included types are incorrect'

    comment_count = len(
        [resource for resource in included if resource["type"] == "comments"])
    expected_comment_count = sum(
        [entry.comment_set.count() for entry in multiple_entries])
    assert comment_count == expected_comment_count, 'List comment count is incorrect'

    author_count = len(
        [resource for resource in included if resource["type"] == "authors"])
    expected_author_count = sum([
        entry.comment_set.filter(author__isnull=False).count()
        for entry in multiple_entries
    ])
    assert author_count == expected_author_count, 'List author count is incorrect'

    author_bio_count = len([
        resource for resource in included if resource["type"] == "authorBios"
    ])
    expected_author_bio_count = sum([
        entry.comment_set.filter(author__bio__isnull=False).count()
        for entry in multiple_entries
    ])
    assert author_bio_count == expected_author_bio_count, 'List author bio count is incorrect'

    # Also include entry authors
    response = client.get(
        reverse("entry-list") + '?include=authors,comments,comments.author,'
        'comments.author.bio&page_size=5')
    included = load_json(response.content).get('included')

    assert len(load_json(response.content)['data']) == len(
        multiple_entries), 'Incorrect entry count'
    assert [x.get('type') for x in included] == [
        'authorBios', 'authorBios', 'authors', 'authors', 'authors', 'authors',
        'comments', 'comments'
    ], 'List included types are incorrect'

    author_count = len(
        [resource for resource in included if resource["type"] == "authors"])
    expected_author_count = sum(
        [entry.authors.count() for entry in multiple_entries] + [
            entry.comment_set.filter(author__isnull=False).count()
            for entry in multiple_entries
        ])
    assert author_count == expected_author_count, 'List author count is incorrect'
def _check_resource_and_relationship_comment_type_match(django_client):
    entry_response = django_client.get(reverse("entry-list"))
    comment_response = django_client.get(reverse("comment-list"))

    comment_resource_type = load_json(comment_response.content).get('data')[0].get('type')
    comment_relationship_type = load_json(entry_response.content).get(
        'data')[0].get('relationships').get('comments').get('data')[0].get('type')

    assert comment_resource_type == comment_relationship_type, "The resource type seen in the relationships and head resource do not match"
def _check_relationship_and_included_comment_type_are_the_same(django_client, url):
    response = django_client.get(url + "?include=comments")
    data = load_json(response.content).get('data')[0]
    comment = load_json(response.content).get('included')[0]

    comment_relationship_type = data.get('relationships').get('comments').get('data')[0].get('type')
    comment_included_type = comment.get('type')

    assert comment_relationship_type == comment_included_type, "The resource type seen in the relationships and included do not match"
Beispiel #9
0
def test_included_data_on_list(multiple_entries, client, query='?include=comments&page_size=5'):
    response = client.get(reverse("entry-list") + query)
    included = load_json(response.content).get('included')

    assert len(load_json(response.content)['data']) == len(multiple_entries), 'Incorrect entry count'
    assert [x.get('type') for x in included] == ['comments', 'comments'], 'List included types are incorrect'

    comment_count = len([resource for resource in included if resource["type"] == "comments"])
    expected_comment_count = sum([entry.comment_set.count() for entry in multiple_entries])
    assert comment_count == expected_comment_count, 'List comment count is incorrect'
Beispiel #10
0
def test_missing_field_not_included(author_bio_factory, author_factory, client):
    # First author does not have a bio
    author = author_factory(bio=None)
    response = client.get(reverse('author-detail', args=[author.pk])+'?include=bio')
    data = load_json(response.content)
    assert 'included' not in data
    # Second author does
    author = author_factory()
    response = client.get(reverse('author-detail', args=[author.pk])+'?include=bio')
    data = load_json(response.content)
    assert 'included' in data
    assert len(data['included']) == 1
    assert data['included'][0]['attributes']['body'] == author.bio.body
    def test_model_serializer_with_implicit_fields(self, comment, client):
        expected = {
            "data": {
                "type": "comments",
                "id": str(comment.pk),
                "attributes": {
                    "body": comment.body
                },
                "relationships": {
                    "entry": {
                        "data": {
                            "type": "entries",
                            "id": str(comment.entry.pk)
                        }
                    },
                    "author": {
                        "data": {
                            "type": "authors",
                            "id": str(comment.author.pk)
                        }
                    },
                }
            }
        }

        response = client.get(reverse("comment-detail", kwargs={'pk': comment.pk}))

        assert response.status_code == 200

        parsed_content = load_json(response.content)

        assert expected == parsed_content
    def test_default_validation_exceptions(self):
        """
        Default validation exceptions should conform to json api spec
        """
        expected = {
            'errors': [
                {
                    'status': '400',
                    'source': {
                        'pointer': '/data/attributes/email',
                    },
                    'detail': 'Enter a valid email address.',
                },
                {
                    'status': '400',
                    'source': {
                        'pointer': '/data/attributes/first-name',
                    },
                    'detail': 'There\'s a problem with first name',
                }
            ]
        }
        response = self.client.post('/identities', {
            'email': 'bar', 'first_name': 'alajflajaljalajlfjafljalj'})

        parsed_content = load_json(response.content)

        assert expected == parsed_content
    def test_ember_expected_renderer(self):
        """
        The :class:`UserEmber` ViewSet has the ``resource_name`` of 'data'
        so that should be the key in the JSON response.
        """
        url = reverse('user-manual-resource-name', kwargs={'pk': self.miles.pk})

        response = self.client.get(url)
        self.assertEqual(200, response.status_code)

        expected = {
            'data': {
                'type': 'data',
                'id': '2',
                'attributes': {
                    'first-name': 'Miles',
                    'last-name': 'Davis',
                    'email': '*****@*****.**'
                }
            }
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
 def test_model_resource_name_on_list(self, client):
     models.Comment.__bases__ += (_PatchedModel,)
     response = client.get(reverse("comment-list"))
     data = load_json(response.content)['data'][0]
     # name should be super-author instead of model name RenamedAuthor
     assert (data.get('type') == 'resource_name_from_JSONAPIMeta'), (
         'resource_name from model incorrect on list')
    def test_custom_validation_exceptions(self):
        """
        Exceptions should be able to be formatted manually
        """
        expected = {
            'errors': [
                {
                    'id': 'armageddon101',
                    'detail': 'Hey! You need a last name!',
                    'meta': 'something',
                },
                {
                    'status': '400',
                    'source': {
                        'pointer': '/data/attributes/email',
                    },
                    'detail': 'Enter a valid email address.',
                },
            ]
        }
        response = self.client.post('/identities', {
            'email': 'bar',
            'last_name': 'alajflajaljalajlfjafljalj'
        })

        parsed_content = load_json(response.content)

        assert expected == parsed_content
    def test_default_validation_exceptions(self):
        """
        Default validation exceptions should conform to json api spec
        """
        expected = {
            'errors': [{
                'status': '400',
                'source': {
                    'pointer': '/data/attributes/email',
                },
                'detail': 'Enter a valid email address.',
            }, {
                'status': '400',
                'source': {
                    'pointer': '/data/attributes/first-name',
                },
                'detail': 'There\'s a problem with first name',
            }]
        }
        response = self.client.post('/identities', {
            'email': 'bar',
            'first_name': 'alajflajaljalajlfjafljalj'
        })

        parsed_content = load_json(response.content)

        assert expected == parsed_content
    def test_ember_expected_renderer(self):
        """
        The :class:`UserEmber` ViewSet has the ``resource_name`` of 'data'
        so that should be the key in the JSON response.
        """
        url = reverse('user-manual-resource-name',
                      kwargs={'pk': self.miles.pk})

        response = self.client.get(url)
        self.assertEqual(200, response.status_code)

        expected = {
            'data': {
                'type': 'data',
                'id': '2',
                'attributes': {
                    'first-name': 'Miles',
                    'last-name': 'Davis',
                    'email': '*****@*****.**'
                }
            }
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
Beispiel #18
0
def test_top_level_meta_for_detail_view(blog, client):

    expected = {
        "data": {
            "type": "blogs",
            "id": "1",
            "attributes": {
                "name": blog.name
            },
            "relationships": {
                "tags": {
                    "data": []
                }
            },
            "links": {
                "self": "http://testserver/blogs/1"
            },
            "meta": {
                "copyright": datetime.now().year
            },
        },
        "meta": {
            "apiDocs": "/docs/api/blogs"
        },
    }

    response = client.get(reverse("blog-detail", kwargs={'pk': blog.pk}))
    parsed_content = load_json(response.content)

    assert expected == parsed_content
    def test_key_in_post(self):
        """
        Ensure a key is in the post.
        """
        self.client.login(username='******', password='******')
        data = {
            'data': {
                'type': 'users',
                'id': encoding.force_text(self.miles.pk),
                'attributes': {
                    'first-name': self.miles.first_name,
                    'last-name': self.miles.last_name,
                    'email': '*****@*****.**'
                },
            }
        }

        response = self.client.put(self.detail_url,
                                   content_type='application/vnd.api+json',
                                   data=dump_json(data))

        parsed_content = load_json(response.content)

        assert data == parsed_content

        # is it updated?
        self.assertEqual(
            get_user_model().objects.get(pk=self.miles.pk).email,
            '*****@*****.**')
    def test_custom_validation_exceptions(self):
        """
        Exceptions should be able to be formatted manually
        """
        expected = {
            'errors': [
                {
                    'id': 'armageddon101',
                    'detail': 'Hey! You need a last name!',
                    'meta': 'something',
                },
                {
                    'status': '400',
                    'source': {
                        'pointer': '/data/attributes/email',
                    },
                    'detail': 'Enter a valid email address.',
                },
            ]
        }
        response = self.client.post('/identities', {
            'email': 'bar', 'last_name': 'alajflajaljalajlfjafljalj'})

        parsed_content = load_json(response.content)

        assert expected == parsed_content
 def test_model_resource_name_on_list(self, client):
     models.Comment.__bases__ += (_PatchedModel, )
     response = client.get(reverse("comment-list"))
     data = load_json(response.content)['data'][0]
     # name should be super-author instead of model name RenamedAuthor
     assert (data.get('type') == 'resource_name_from_JSONAPIMeta'), (
         'resource_name from model incorrect on list')
Beispiel #22
0
    def test_model_serializer_with_implicit_fields(self, comment, client):
        expected = {
            "data": {
                "type": "comments",
                "id": str(comment.pk),
                "attributes": {
                    "body": comment.body
                },
                "relationships": {
                    "entry": {
                        "data": {
                            "type": "entries",
                            "id": str(comment.entry.pk)
                        }
                    },
                    "author": {
                        "data": {
                            "type": "authors",
                            "id": str(comment.author.pk)
                        }
                    },
                }
            }
        }

        response = client.get(
            reverse("comment-detail", kwargs={'pk': comment.pk}))

        assert response.status_code == 200

        parsed_content = load_json(response.content)

        assert expected == parsed_content
Beispiel #23
0
def test_polymorphism_on_polymorphic_model_detail_patch(
        single_art_project, client):
    url = reverse("project-detail", kwargs={'pk': single_art_project.pk})
    response = client.get(url)
    content = load_json(response.content)
    test_topic = 'test-{}'.format(random.randint(0, 999999))
    test_artist = 'test-{}'.format(random.randint(0, 999999))
    content['data']['attributes']['topic'] = test_topic
    content['data']['attributes']['artist'] = test_artist
    response = client.patch(url,
                            data=json.dumps(content),
                            content_type='application/vnd.api+json')
    new_content = load_json(response.content)
    assert new_content['data']['type'] == "artProjects"
    assert new_content['data']['attributes']['topic'] == test_topic
    assert new_content['data']['attributes']['artist'] == test_artist
Beispiel #24
0
def test_invalid_type_on_polymorphic_model(client):
    test_topic = 'New test topic {}'.format(random.randint(0, 999999))
    test_artist = 'test-{}'.format(random.randint(0, 999999))
    url = reverse('project-list')
    data = {
        'data': {
            'type': 'invalidProjects',
            'attributes': {
                'topic': test_topic,
                'artist': test_artist
            }
        }
    }
    response = client.post(url,
                           data=json.dumps(data),
                           content_type='application/vnd.api+json')
    assert response.status_code == 409
    content = load_json(response.content)
    assert len(content["errors"]) is 1
    assert content["errors"][0]["status"] == "409"
    try:
        assert content["errors"][0]["detail"] == \
            "The resource object's type (invalidProjects) is not the type that constitute the " \
            "collection represented by the endpoint (one of [researchProjects, artProjects])."
    except AssertionError:
        # Available type list order isn't enforced
        assert content["errors"][0]["detail"] == \
            "The resource object's type (invalidProjects) is not the type that constitute the " \
            "collection represented by the endpoint (one of [artProjects, researchProjects])."
Beispiel #25
0
def test_dynamic_related_data_is_included(single_entry, entry_factory, client):
    entry_factory()
    response = client.get(reverse("entry-detail", kwargs={'pk': single_entry.pk}) + '?include=featured')
    included = load_json(response.content).get('included')

    assert [x.get('type') for x in included] == ['entries'], 'Dynamic included types are incorrect'
    assert len(included) == 1, 'The dynamically included blog entries are of an incorrect count'
Beispiel #26
0
def test_dynamic_many_related_data_is_included(single_entry, entry_factory, client):
    entry_factory()
    response = client.get(reverse("entry-detail", kwargs={'pk': single_entry.pk}) + '?include=suggested')
    included = load_json(response.content).get('included')

    assert included
    assert [x.get('type') for x in included] == ['entries'], 'Dynamic included types are incorrect'
Beispiel #27
0
    def test_key_in_post(self):
        """
        Ensure a key is in the post.
        """
        self.client.login(username='******', password='******')
        data = {
            'data': {
                'type': 'users',
                'id': encoding.force_text(self.miles.pk),
                'attributes': {
                    'first-name': self.miles.first_name,
                    'last-name': self.miles.last_name,
                    'email': '*****@*****.**'
                },
            }
        }

        response = self.client.put(self.detail_url,
                                   content_type='application/vnd.api+json',
                                   data=dump_json(data))

        parsed_content = load_json(response.content)

        assert data == parsed_content

        # is it updated?
        self.assertEqual(get_user_model().objects.get(pk=self.miles.pk).email,
                         '*****@*****.**')
Beispiel #28
0
def test_included_data_on_detail(single_entry, client, query='?include=comments'):
    response = client.get(reverse("entry-detail", kwargs={'pk': single_entry.pk}) + query)
    included = load_json(response.content).get('included')

    assert [x.get('type') for x in included] == ['comments'], 'Detail included types are incorrect'

    comment_count = len([resource for resource in included if resource["type"] == "comments"])
    expected_comment_count = single_entry.comment_set.count()
    assert comment_count == expected_comment_count, 'Detail comment count is incorrect'
Beispiel #29
0
def test_polymorphism_on_detail_relations(single_company, client):
    response = client.get(
        reverse("company-detail", kwargs={'pk': single_company.pk}))
    content = load_json(response.content)
    assert content["data"]["relationships"]["currentProject"]["data"][
        "type"] == "artProjects"
    assert (set([
        rel["type"]
        for rel in content["data"]["relationships"]["futureProjects"]["data"]
    ]) == set(["researchProjects", "artProjects"]))
def test_deep_included_data_on_list(multiple_entries, client):
    response = client.get(reverse("entry-list") + '?include=comments,comments.author,'
                          'comments.author.bio&page_size=5')
    included = load_json(response.content).get('included')

    assert len(load_json(response.content)['data']) == len(multiple_entries), 'Incorrect entry count'
    assert [x.get('type') for x in included] == [
        'authorBios', 'authorBios', 'authors', 'authors', 'comments', 'comments'
    ], 'List included types are incorrect'

    comment_count = len([resource for resource in included if resource["type"] == "comments"])
    expected_comment_count = sum([entry.comment_set.count() for entry in multiple_entries])
    assert comment_count == expected_comment_count, 'List comment count is incorrect'

    author_count = len([resource for resource in included if resource["type"] == "authors"])
    expected_author_count = sum(
        [entry.comment_set.filter(author__isnull=False).count() for entry in multiple_entries])
    assert author_count == expected_author_count, 'List author count is incorrect'

    author_bio_count = len([resource for resource in included if resource["type"] == "authorBios"])
    expected_author_bio_count = sum([entry.comment_set.filter(
        author__bio__isnull=False).count() for entry in multiple_entries])
    assert author_bio_count == expected_author_bio_count, 'List author bio count is incorrect'

    # Also include entry authors
    response = client.get(reverse("entry-list") + '?include=authors,comments,comments.author,'
                          'comments.author.bio&page_size=5')
    included = load_json(response.content).get('included')

    assert len(load_json(response.content)['data']) == len(multiple_entries), 'Incorrect entry count'
    assert [x.get('type') for x in included] == [
        'authorBios', 'authorBios', 'authors', 'authors', 'authors', 'authors',
        'comments', 'comments'], 'List included types are incorrect'

    author_count = len([resource for resource in included if resource["type"] == "authors"])
    expected_author_count = sum(
        [entry.authors.count() for entry in multiple_entries] +
        [entry.comment_set.filter(author__isnull=False).count() for entry in multiple_entries])
    assert author_count == expected_author_count, 'List author count is incorrect'
Beispiel #31
0
def test_polymorphism_relations_update(single_company,
                                       research_project_factory, client):
    response = client.get(
        reverse("company-detail", kwargs={'pk': single_company.pk}))
    content = load_json(response.content)
    assert content["data"]["relationships"]["currentProject"]["data"][
        "type"] == "artProjects"

    research_project = research_project_factory()
    content["data"]["relationships"]["currentProject"]["data"] = {
        "type": "researchProjects",
        "id": research_project.pk
    }
    response = client.put(reverse("company-detail",
                                  kwargs={'pk': single_company.pk}),
                          data=json.dumps(content),
                          content_type='application/vnd.api+json')
    assert response.status_code == 200
    content = load_json(response.content)
    assert content["data"]["relationships"]["currentProject"]["data"][
        "type"] == "researchProjects"
    assert int(content["data"]["relationships"]["currentProject"]["data"]["id"]) == \
        research_project.pk
    def test_page_range_in_list_result(self):
        """
        Ensure that the range of a page can be changed from the client,
        tests pluralization as two objects means it converts ``user`` to
        ``users``.
        """
        response = self.client.get(self.list_url, {'page_size': 2})
        self.assertEqual(response.status_code, 200)

        users = get_user_model().objects.all()
        expected = {
            'data': [
                {
                    'type': 'users',
                    'id': encoding.force_text(users[0].pk),
                    'attributes': {
                        'first-name': users[0].first_name,
                        'last-name': users[0].last_name,
                        'email': users[0].email
                    },
                },
                {
                    'type': 'users',
                    'id': encoding.force_text(users[1].pk),
                    'attributes': {
                        'first-name': users[1].first_name,
                        'last-name': users[1].last_name,
                        'email': users[1].email
                    },
                }
            ],
            'links': {
                'first': 'http://testserver/identities?page=1&page_size=2',
                'last': 'http://testserver/identities?page=1&page_size=2',
                'next': None,
                'prev': None
            },
            'meta': {
                'pagination': {
                    'page': 1,
                    'pages': 1,
                    'count': 2
                }
            }
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
Beispiel #33
0
def test_deep_included_data_on_detail(single_entry, client):
    # Same test as in list but also ensures that intermediate resources (here comments' authors)
    # are returned along with the leaf nodes
    response = client.get(reverse("entry-detail", kwargs={'pk': single_entry.pk}) +
                          '?include=comments,comments.author.bio')
    included = load_json(response.content).get('included')

    assert [x.get('type') for x in included] == ['authorBios', 'authors', 'comments'], \
        'Detail included types are incorrect'

    comment_count = len([resource for resource in included if resource["type"] == "comments"])
    expected_comment_count = single_entry.comment_set.count()
    assert comment_count == expected_comment_count, 'Detail comment count is incorrect'

    author_bio_count = len([resource for resource in included if resource["type"] == "authorBios"])
    expected_author_bio_count = single_entry.comment_set.filter(author__bio__isnull=False).count()
    assert author_bio_count == expected_author_bio_count, 'Detail author bio count is incorrect'
    def test_default_rest_framework_behavior(self):
        """
        This is more of an example really, showing default behavior
        """
        url = reverse('user-default', kwargs={'pk': self.miles.pk})

        response = self.client.get(url)

        self.assertEqual(200, response.status_code)

        expected = {
            'id': 2,
            'first_name': 'Miles',
            'last_name': 'Davis',
            'email': '*****@*****.**'
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
    def test_generic_validation_error(self):
        """
        Check error formatting
        """
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 400)

        expected = {
            'errors': [{
                'status': '400',
                'source': {
                    'pointer': '/data'
                },
                'detail': 'Oh nohs!'
            }]
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
    def test_default_rest_framework_behavior(self):
        """
        This is more of an example really, showing default behavior
        """
        url = reverse('user-default', kwargs={'pk': self.miles.pk})

        response = self.client.get(url)

        self.assertEqual(200, response.status_code)

        expected = {
            'id': 2,
            'first_name': 'Miles',
            'last_name': 'Davis',
            'email': '*****@*****.**'
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
Beispiel #37
0
def test_top_level_meta_for_list_view(blog, client):

    expected = {
        "data": [{
            "type": "blogs",
            "id": "1",
            "attributes": {
                "name": blog.name
            },
            "links": {
                "self": 'http://testserver/blogs/1'
            },
            "relationships": {
                "tags": {
                    "data": []
                }
            },
            "meta": {
                "copyright": datetime.now().year
            },
        }],
        'links': {
            'first': 'http://testserver/blogs?page=1',
            'last': 'http://testserver/blogs?page=1',
            'next': None,
            'prev': None
        },
        'meta': {
            'pagination': {
                'count': 1,
                'page': 1,
                'pages': 1
            },
            'apiDocs': '/docs/api/blogs'
        }
    }

    response = client.get(reverse("blog-list"))
    parsed_content = load_json(response.content)

    assert expected == parsed_content
Beispiel #38
0
def test_polymorphism_on_polymorphic_model_list_post(client):
    test_topic = 'New test topic {}'.format(random.randint(0, 999999))
    test_artist = 'test-{}'.format(random.randint(0, 999999))
    url = reverse('project-list')
    data = {
        'data': {
            'type': 'artProjects',
            'attributes': {
                'topic': test_topic,
                'artist': test_artist
            }
        }
    }
    response = client.post(url,
                           data=json.dumps(data),
                           content_type='application/vnd.api+json')
    content = load_json(response.content)
    assert content['data']['id'] is not None
    assert content['data']['type'] == "artProjects"
    assert content['data']['attributes']['topic'] == test_topic
    assert content['data']['attributes']['artist'] == test_artist
Beispiel #39
0
def test_polymorphism_on_included_relations(single_company, client):
    response = client.get(
        reverse("company-detail", kwargs={'pk': single_company.pk}) +
        '?include=current_project,future_projects')
    content = load_json(response.content)
    assert content["data"]["relationships"]["currentProject"]["data"][
        "type"] == "artProjects"
    assert (set([
        rel["type"]
        for rel in content["data"]["relationships"]["futureProjects"]["data"]
    ]) == set(["researchProjects", "artProjects"]))
    assert set([x.get('type') for x in content.get('included')
                ]) == set(['artProjects', 'artProjects', 'researchProjects'
                           ]), 'Detail included types are incorrect'
    # Ensure that the child fields are present.
    assert content.get('included')[0].get('attributes').get(
        'artist') is not None
    assert content.get('included')[1].get('attributes').get(
        'artist') is not None
    assert content.get('included')[2].get('attributes').get(
        'supervisor') is not None
Beispiel #40
0
    def test_key_in_detail_result(self):
        """
        Ensure the result has a 'user' key.
        """
        response = self.client.get(self.detail_url)
        self.assertEqual(response.status_code, 200)

        expected = {
            'data': {
                'type': 'users',
                'id': encoding.force_text(self.miles.pk),
                'attributes': {
                    'first-name': self.miles.first_name,
                    'last-name': self.miles.last_name,
                    'email': self.miles.email
                },
            }
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
    def test_key_in_detail_result(self):
        """
        Ensure the result has a 'user' key.
        """
        response = self.client.get(self.detail_url)
        self.assertEqual(response.status_code, 200)

        expected = {
            'data': {
                'type': 'users',
                'id': encoding.force_text(self.miles.pk),
                'attributes': {
                    'first-name': self.miles.first_name,
                    'last-name': self.miles.last_name,
                    'email': self.miles.email
                },
            }
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
Beispiel #42
0
def test_polymorphic_model_without_any_instance(client):
    expected = {
        "links": {
            "first": "http://testserver/projects?page=1",
            "last": "http://testserver/projects?page=1",
            "next": None,
            "prev": None
        },
        "data": [],
        "meta": {
            "pagination": {
                "page": 1,
                "pages": 1,
                "count": 0
            }
        }
    }

    response = client.get(reverse('project-list'))
    assert response.status_code == 200
    content = load_json(response.content)
    assert expected == content
    def test_page_two_in_list_result(self):
        """
        Ensure that the second page is reachable and is the correct data.
        """
        response = self.client.get(self.list_url, {'page': 2})
        self.assertEqual(response.status_code, 200)

        user = get_user_model().objects.all()[1]
        expected = {
            'data': [
                {
                'type': 'users',
                'id': encoding.force_text(user.pk),
                'attributes': {
                    'first-name': user.first_name,
                    'last-name': user.last_name,
                    'email': user.email
                },
            }
            ],
            'links': {
                'first': 'http://testserver/identities?page=1',
                'last': 'http://testserver/identities?page=2',
                'next': None,
                'prev': 'http://testserver/identities?page=1',
            },
            'meta': {
                'pagination': {
                    'page': 2,
                    'pages': 2,
                    'count': 2
                }
            }
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
    def test_camelization(self):
        """
        Test that camelization works.
        """
        response = self.client.get(self.list_url)
        self.assertEqual(response.status_code, 200)

        user = get_user_model().objects.all()[0]
        expected = {
            'data': [
                {
                    'type': 'users',
                    'id': encoding.force_text(user.pk),
                    'attributes': {
                        'firstName': user.first_name,
                        'lastName': user.last_name,
                        'email': user.email
                    },
                }
            ],
            'links': {
                'first': 'http://testserver/identities?page=1',
                'last': 'http://testserver/identities?page=2',
                'next': 'http://testserver/identities?page=2',
                'prev': None
            },
            'meta': {
                'pagination': {
                    'page': 1,
                    'pages': 2,
                    'count': 2
                }
            }
        }

        parsed_content = load_json(response.content)

        assert expected == parsed_content
def test_model_resource_name_on_list(single_entry, client):
    response = client.get(reverse("renamed-authors-list"))
    data = load_json(response.content)['data']
    # name should be super-author instead of model name RenamedAuthor
    assert [x.get('type') for x in data] == ['super-author'], 'List included types are incorrect'
def test_multiple_entries_no_pagination(multiple_entries, rf):

    expected = {
        "data": [
            {
                "type": "posts",
                "id": "1",
                "attributes":
                {
                    "headline": multiple_entries[0].headline,
                    "bodyText": multiple_entries[0].body_text,
                    "pubDate": None,
                    "modDate": None
                },
                "meta": {
                    "bodyFormat": "text"
                },
                "relationships":
                {
                    "blog": {
                        "data": {"type": "blogs", "id": "1"}
                    },
                    "authors": {
                        "meta": {"count": 1},
                        "data": [{"type": "authors", "id": "1"}]
                    },
                    "comments": {
                        "meta": {"count": 1},
                        "data": [{"type": "comments", "id": "1"}]
                    },
                    "suggested": {
                        "data": [{"type": "entries", "id": "2"}],
                        "links": {
                            "related": "http://testserver/entries/1/suggested/",
                            "self": "http://testserver/entries/1/relationships/suggested"
                        }
                    },
                    "tags": {
                        "data": []
                    }
                }
            },
            {
                "type": "posts",
                "id": "2",
                "attributes":
                {
                    "headline": multiple_entries[1].headline,
                    "bodyText": multiple_entries[1].body_text,
                    "pubDate": None,
                    "modDate": None
                },
                "meta": {
                    "bodyFormat": "text"
                },
                "relationships":
                {
                    "blog": {
                        "data": {"type": "blogs", "id": "2"}
                    },
                    "authors": {
                        "meta": {"count": 1},
                        "data": [{"type": "authors", "id": "2"}]
                    },
                    "comments": {
                        "meta": {"count": 1},
                        "data": [{"type": "comments", "id": "2"}]
                    },
                    "suggested": {
                        "data": [{"type": "entries", "id": "1"}],
                        "links": {
                            "related": "http://testserver/entries/2/suggested/",
                            "self": "http://testserver/entries/2/relationships/suggested"
                        }
                    },
                    "tags": {
                        "data": []
                    }
                }
            },
        ]
    }

    class NoPagination(PageNumberPagination):
        page_size = None

    class NonPaginatedEntryViewSet(EntryViewSet):
        pagination_class = NoPagination

    request = rf.get(
        reverse("entry-list"))
    view = NonPaginatedEntryViewSet.as_view({'get': 'list'})
    response = view(request)
    response.render()

    parsed_content = load_json(response.content)

    assert expected == parsed_content