示例#1
0
    def test_handle_not_authenticated(self):
        # Special-cased above for testing.
        self.res.request = FakeHttpRequest('DELETE')

        # First with DEBUG on
        resp = self.res.handle('list')
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 401)
        resp_json = json.loads(resp.content.decode('utf-8'))
        self.assertEqual(resp_json['error'], 'Unauthorized.')
        self.assertTrue('traceback' in resp_json)

        # Now with DEBUG off.
        settings.DEBUG = False
        self.addCleanup(setattr, settings, 'DEBUG', True)
        resp = self.res.handle('list')
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 401)
        resp_json = json.loads(resp.content.decode('utf-8'))
        self.assertEqual(resp_json, {
            'error': 'Unauthorized.',
        })
        self.assertFalse('traceback' in resp_json)

        # Last, with bubble_exceptions.
        class Bubbly(DjTestResource):
            def bubble_exceptions(self):
                return True

        with self.assertRaises(Unauthorized):
            bubb = Bubbly()
            bubb.request = FakeHttpRequest('DELETE')
            bubb.handle('list')
示例#2
0
    def test_build_error(self):
        err = HttpError("Whoopsie")
        resp = self.res.build_error(err)
        resp_body = json.loads(resp.body)
        self.assertEqual(resp_body, {'error': 'Whoopsie'})
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status_code, 500)

        nf_err = NotFound()
        resp = self.res.build_error(nf_err)
        resp_body = json.loads(resp.body)
        # Default error message.
        self.assertEqual(resp_body, {'error': 'Resource not found.'})
        self.assertEqual(resp.content_type, 'application/json')
        # Custom status code.
        self.assertEqual(resp.status_code, 404)

        # Non-restless exception.
        unknown_err = AttributeError("'something' not found on the object.")
        resp = self.res.build_error(unknown_err)
        resp_body = json.loads(resp.body)
        # Still gets the JSON treatment & an appropriate status code.
        self.assertEqual(resp_body,
                         {'error': "'something' not found on the object."})
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status_code, 500)
示例#3
0
    def test_build_error(self):
        err = HttpError("Whoopsie")
        resp = self.res.build_error(err)
        resp_body = json.loads(resp.body)
        self.assertEqual(resp_body, {'error': 'Whoopsie'})
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status_code, 500)

        nf_err = NotFound()
        resp = self.res.build_error(nf_err)
        resp_body = json.loads(resp.body)
        # Default error message.
        self.assertEqual(resp_body, {'error': 'Resource not found.'})
        self.assertEqual(resp.content_type, 'application/json')
        # Custom status code.
        self.assertEqual(resp.status_code, 404)

        # Non-restless exception.
        unknown_err = AttributeError("'something' not found on the object.")
        resp = self.res.build_error(unknown_err)
        resp_body = json.loads(resp.body)
        # Still gets the JSON treatment & an appropriate status code.
        self.assertEqual(resp_body, {'error': "'something' not found on the object."})
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status_code, 500)
示例#4
0
    def test_handle_not_authenticated(self):
        # Special-cased above for testing.
        self.res.request = FakeHttpRequest('DELETE')

        # First with DEBUG on
        resp = self.res.handle('list')
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 401)
        self.assertEqual(resp.reason_phrase.title(), responses[401])

        resp_json = json.loads(resp.content.decode('utf-8'))
        self.assertEqual(resp_json['error'], 'Unauthorized.')
        self.assertTrue('traceback' in resp_json)

        # Now with DEBUG off.
        settings.DEBUG = False
        self.addCleanup(setattr, settings, 'DEBUG', True)
        resp = self.res.handle('list')
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 401)
        resp_json = json.loads(resp.content.decode('utf-8'))
        self.assertEqual(resp_json, {
            'error': 'Unauthorized.',
        })
        self.assertFalse('traceback' in resp_json)

        # Last, with bubble_exceptions.
        class Bubbly(DjTestResource):
            def bubble_exceptions(self):
                return True

        with self.assertRaises(Unauthorized):
            bubb = Bubbly()
            bubb.request = FakeHttpRequest('DELETE')
            bubb.handle('list')
示例#5
0
    def test_as_list_paginated_second_page(self):
        list_endpoint = DjTestResourcePaginatedOnePerPage(page_size=1).as_list()

        req = FakeHttpRequest('GET', get_request={'p': 2})

        resp = list_endpoint(req)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)

        self.assertEqual(
            json.loads(resp.content.decode('utf-8')),
            {
                'objects': [
                    {
                        'author': 'daniel',
                        'body': 'Stuff here.',
                        'id': 'de-faced',
                        'title': 'Another',
                    },
                ],
                'pagination': {
                    'num_pages': 3,
                    'count': 3,
                    'page': 2,
                    'start_index': 2,
                    'end_index': 2,
                    'next_page': 3,
                    'previous_page': 1,
                    'per_page': 1,
                    },
                 },
                 )
示例#6
0
    def test_as_list_paginated_second_page(self):
        list_endpoint = DjTestResourcePaginatedOnePerPage(
            page_size=1).as_list()

        req = FakeHttpRequest('GET', get_request={'p': 2})

        resp = list_endpoint(req)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)

        self.assertEqual(
            json.loads(resp.content.decode('utf-8')),
            {
                'objects': [
                    {
                        'author': 'daniel',
                        'body': 'Stuff here.',
                        'id': 'de-faced',
                        'title': 'Another',
                    },
                ],
                'pagination': {
                    'num_pages': 3,
                    'count': 3,
                    'page': 2,
                    'start_index': 2,
                    'end_index': 2,
                    'next_page': 3,
                    'previous_page': 1,
                    'per_page': 1,
                },
            },
        )
示例#7
0
    def test_serialize_detail(self):
        # This isn't very unit-y, but we're also testing that we're using the
        # right JSON encoder & that it can handle other data types.
        data = {
            'title':
            'Cosmos',
            'author':
            'Carl Sagan',
            'short_desc':
            'A journey through the stars by an emminent astrophysist.',
        }

        self.res.preparer = FieldsPreparer(fields={
            'title': 'title',
            'author': 'author',
            'synopsis': 'short_desc',
        })
        res = self.res.serialize_detail(data)
        self.assertEqual(
            json.loads(res), {
                'author': 'Carl Sagan',
                'synopsis':
                'A journey through the stars by an emminent astrophysist.',
                'title': 'Cosmos'
            })

        # Make sure we don't try to serialize a ``None``, which would fail.
        self.assertEqual(self.res.serialize_detail(None), '')
示例#8
0
    def test_list(self):
        res = self.client.get('/mydata/')

        self.assertEqual(res.content_type, 'application/json')
        self.assertEqual(res.status_code, 200)
        self.assertEqual(json.loads(res.body.decode('utf-8')), {
            'objects': [
                {
                    'author': 'viniciuscainelli',
                    'body': 'Hello world!',
                    'id': 2,
                    'title': 'First post'
                },
                {
                    'author': 'viniciuscainelli',
                    'body': 'Stuff here.',
                    'id': 4,
                    'title': 'Another'
                },
                {
                    'author': 'viniciuscainelli',
                    'body': "G'bye!",
                    'id': 5,
                    'title': 'Last'
                }
            ]
        })
示例#9
0
    def test_as_list(self):
        list_endpoint = DjTestResource.as_list()
        req = FakeHttpRequest('GET')

        resp = list_endpoint(req)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
            json.loads(resp.content.decode('utf-8')), {
                'objects': [{
                    'author': 'daniel',
                    'body': 'Hello world!',
                    'id': 'dead-beef',
                    'title': 'First post'
                }, {
                    'author': 'daniel',
                    'body': 'Stuff here.',
                    'id': 'de-faced',
                    'title': 'Another'
                }, {
                    'author': 'daniel',
                    'body': "G'bye!",
                    'id': 'bad-f00d',
                    'title': 'Last'
                }]
            })
示例#10
0
    def test_as_list(self):
        list_endpoint = DjTestResource.as_list()
        req = FakeHttpRequest('GET')

        resp = list_endpoint(req)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.content.decode('utf-8')), {
            'objects': [
                {
                    'author': 'daniel',
                    'body': 'Hello world!',
                    'id': 2,
                    'title': 'First post'
                },
                {
                    'author': 'daniel',
                    'body': 'Stuff here.',
                    'id': 4,
                    'title': 'Another'
                },
                {
                    'author': 'daniel',
                    'body': "G'bye!",
                    'id': 5,
                    'title': 'Last'
                }
            ]
        })
示例#11
0
 def test_as_list(self):
     resp = self.fetch("/fake", method="GET", follow_redirects=False)
     self.assertEqual(resp.headers["Content-Type"], "application/json; charset=UTF-8")
     self.assertEqual(resp.code, 200)
     self.assertEqual(
         json.loads(resp.body.decode("utf-8")),
         {"objects": [{"id": 2, "title": "First post"}, {"id": 4, "title": "Another"}, {"id": 5, "title": "Last"}]},
     )
示例#12
0
    def test_handle_not_implemented(self):
        self.res.request = FakeHttpRequest('TRACE')

        resp = self.res.handle('list')
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 501)
        resp_json = json.loads(resp.content.decode('utf-8'))
        self.assertEqual(resp_json['error'], "Unsupported method 'TRACE' for list endpoint.")
        self.assertTrue('traceback' in resp_json)
示例#13
0
 def test_as_detail(self):
     resp = self.fetch('/fake/4', method='GET', follow_redirects=False)
     self.assertEqual(resp.headers['Content-Type'],
                      'application/json; charset=UTF-8')
     self.assertEqual(resp.code, 200)
     self.assertEqual(json.loads(resp.body.decode('utf-8')), {
         'id': 4,
         'title': 'Another'
     })
示例#14
0
    def test_handle_build_err(self):
        # Special-cased above for testing.
        self.res.request = FakeHttpRequest("POST")
        settings.DEBUG = False
        self.addCleanup(setattr, settings, "DEBUG", True)

        resp = self.res.handle("detail")
        self.assertEqual(resp["Content-Type"], "application/json")
        self.assertEqual(resp.status_code, 500)
        self.assertEqual(json.loads(resp.content.decode("utf-8")), {"error": "This is a random & crazy exception."})
示例#15
0
    def test_handle_not_implemented(self):
        self.res.request = FakeHttpRequest('TRACE')

        resp = self.res.handle('list')
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 501)
        resp_json = json.loads(resp.content.decode('utf-8'))
        self.assertEqual(resp_json['error'],
                         "Unsupported method 'TRACE' for list endpoint.")
        self.assertTrue('traceback' in resp_json)
示例#16
0
    def test_detail(self):
        res = self.client.get('/mydata/4/')

        self.assertEqual(res.content_type, 'application/json')
        self.assertEqual(res.status_code, 200)
        self.assertEqual(json.loads(res.body.decode('utf-8')), {
            'author': 'viniciuscainelli',
            'body': 'Stuff here.',
            'id': 4,
            'title': 'Another'
        })
示例#17
0
    def test_object_does_not_exist(self):
        # Make sure we get a proper Not Found exception rather than a
        # generic 500.
        self.res.request = FakeHttpRequest("GET")
        settings.DEBUG = False
        self.addCleanup(setattr, settings, "DEBUG", True)

        resp = self.res.handle("detail", 1001)
        self.assertEqual(resp["Content-Type"], "application/json")
        self.assertEqual(resp.status_code, 404)
        self.assertEqual(json.loads(resp.content.decode("utf-8")), {"error": "Model with pk 1001 not found."})
示例#18
0
    def test_as_detail(self):
        detail_endpoint = DjTestResource.as_detail()
        req = FakeHttpRequest("GET")

        resp = detail_endpoint(req, 4)
        self.assertEqual(resp["Content-Type"], "application/json")
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
            json.loads(resp.content.decode("utf-8")),
            {"author": "daniel", "body": "Stuff here.", "id": 4, "title": "Another"},
        )
示例#19
0
    def test_as_detail(self):
        detail_endpoint = ItTestResource.as_detail()
        request = FakeHttpRequest('GET')

        resp = detail_endpoint(request, 'de-faced')
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status, 200)
        self.assertEqual(json.loads(resp.output), {
            'id': 'de-faced',
            'title': 'Another'
        })
示例#20
0
    def test_as_detail(self):
        detail_endpoint = ItTestResource.as_detail()
        request = FakeHttpRequest('GET')

        resp = detail_endpoint(request, 4)
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status, 200)
        self.assertEqual(json.loads(resp.output), {
            'id': 4,
            'title': 'Another'
        })
示例#21
0
    def test_handle_build_err(self):
        # Special-cased above for testing.
        self.res.request = FakeHttpRequest('POST')
        settings.DEBUG = False
        self.addCleanup(setattr, settings, 'DEBUG', True)

        resp = self.res.handle('detail')
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 500)
        self.assertEqual(json.loads(resp.content.decode('utf-8')),
                         {'error': 'This is a random & crazy exception.'})
示例#22
0
    def test_as_view(self):
        # This would be hooked up via the URLconf...
        schema_endpoint = DjTestResource.as_view("schema", prepare_data=False)
        req = FakeHttpRequest("GET")

        resp = schema_endpoint(req)
        self.assertEqual(resp["Content-Type"], "application/json")
        self.assertEqual(resp.status_code, 200)
        schema = json.loads(resp.content.decode("utf-8"))
        self.assertEqual(sorted(list(schema["fields"].keys())), ["author", "body", "id", "title"])
        self.assertEqual(schema["fields"]["id"]["type"], "integer")
        self.assertEqual(schema["format"], "application/json")
示例#23
0
    def test_as_detail(self):
        detail_endpoint = FlTestResource.as_detail()
        flask.request = FakeHttpRequest('GET')

        with self.app.test_request_context('/whatever/', method='GET'):
            resp = detail_endpoint('de-faced')
            self.assertEqual(resp.headers['Content-Type'], 'application/json')
            self.assertEqual(resp.status_code, 200)
            self.assertEqual(json.loads(resp.data.decode('utf-8')), {
                'id': 'de-faced',
                'title': 'Another'
            })
示例#24
0
 def test_as_detail(self):
     resp = self.fetch(
         '/fake_async/de-faced',
         method='GET',
         follow_redirects=False
     )
     self.assertEqual(resp.headers['Content-Type'], 'application/json; charset=UTF-8')
     self.assertEqual(resp.code, 200)
     self.assertEqual(json.loads(resp.body.decode('utf-8')), {
         'id': 'de-faced',
         'title': 'Another'
     })
示例#25
0
    def test_as_detail(self):
        detail_endpoint = FlTestResource.as_detail()
        flask.request = FakeHttpRequest('GET')

        with self.app.test_request_context('/whatever/', method='GET'):
            resp = detail_endpoint('de-faced')
            self.assertEqual(resp.headers['Content-Type'], 'application/json')
            self.assertEqual(resp.status_code, 200)
            self.assertEqual(json.loads(resp.data.decode('utf-8')), {
                'id': 'de-faced',
                'title': 'Another'
            })
示例#26
0
    def test_handle_build_err(self):
        # Special-cased above for testing.
        self.res.request = FakeHttpRequest('POST')
        settings.DEBUG = False
        self.addCleanup(setattr, settings, 'DEBUG', True)

        resp = self.res.handle('detail')
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 500)
        self.assertEqual(json.loads(resp.content.decode('utf-8')), {
            'error': 'This is a random & crazy exception.'
        })
示例#27
0
    def test_object_does_not_exist(self):
        # Make sure we get a proper Not Found exception rather than a
        # generic 500, when code raises a ObjectDoesNotExist exception.
        self.res.request = FakeHttpRequest('GET')
        settings.DEBUG = False
        self.addCleanup(setattr, settings, 'DEBUG', True)

        resp = self.res.handle('detail', 1001)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 404)
        self.assertEqual(json.loads(resp.content.decode('utf-8')),
                         {'error': 'Model with pk 1001 not found.'})
示例#28
0
    def test_http404_exception_handling(self):
        # Make sure we get a proper Not Found exception rather than a
        # generic 500, when code raises a Http404 exception.
        res = DjTestResourceHttp404Handling()
        res.request = FakeHttpRequest('GET')
        settings.DEBUG = False
        self.addCleanup(setattr, settings, 'DEBUG', True)

        resp = res.handle('detail', 1001)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 404)
        self.assertEqual(json.loads(resp.content.decode('utf-8')),
                         {'error': 'Model with pk 1001 not found.'})
示例#29
0
    def test_as_detail(self):
        detail_endpoint = DjTestResource.as_detail()
        req = FakeHttpRequest('GET')

        resp = detail_endpoint(req, 4)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.content.decode('utf-8')), {
            'author': 'daniel',
            'body': 'Stuff here.',
            'id': 4,
            'title': 'Another'
        })
示例#30
0
    def test_object_does_not_exist(self):
        # Make sure we get a proper Not Found exception rather than a
        # generic 500, when code raises a ObjectDoesNotExist exception.
        self.res.request = FakeHttpRequest('GET')
        settings.DEBUG = False
        self.addCleanup(setattr, settings, 'DEBUG', True)

        resp = self.res.handle('detail', 1001)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 404)
        self.assertEqual(json.loads(resp.content.decode('utf-8')), {
            'error': 'Model with pk 1001 not found.'
        })
示例#31
0
    def test_as_detail(self):
        detail_endpoint = DjTestResource.as_detail()
        req = FakeHttpRequest('GET')

        resp = detail_endpoint(req, 4)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.content.decode('utf-8')), {
            'author': 'daniel',
            'body': 'Stuff here.',
            'id': 4,
            'title': 'Another'
        })
示例#32
0
    def test_as_detail(self):
        detail_endpoint = PyrTestResource.as_detail()
        req = testing.DummyRequest()

        req = FakeHttpRequest('GET')
        req.matchdict = {'name': 'de-faced'}

        resp = detail_endpoint(req)
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.body.decode('utf-8')), {
            'id': 'de-faced',
            'title': 'Another'
        })
示例#33
0
    def test_http404_exception_handling(self):
        # Make sure we get a proper Not Found exception rather than a
        # generic 500, when code raises a Http404 exception.
        res = DjTestResourceHttp404Handling()
        res.request = FakeHttpRequest('GET')
        settings.DEBUG = False
        self.addCleanup(setattr, settings, 'DEBUG', True)

        resp = res.handle('detail', 1001)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 404)
        self.assertEqual(json.loads(resp.content.decode('utf-8')), {
            'error': 'Model with pk 1001 not found.'
        })
示例#34
0
    def test_as_detail(self):
        detail_endpoint = PyrTestResource.as_detail()
        req = testing.DummyRequest()

        req = FakeHttpRequest('GET')
        req.matchdict = {'name': 4}

        resp = detail_endpoint(req)
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(json.loads(resp.body.decode('utf-8')), {
            'id': 4,
            'title': 'Another'
        })
示例#35
0
    def test_handle_not_authenticated(self):
        # Special-cased above for testing.
        self.res.request = FakeHttpRequest("DELETE")

        with self.assertRaises(Unauthorized):
            self.res.handle("list")

        # Now with DEBUG off.
        settings.DEBUG = False
        self.addCleanup(setattr, settings, "DEBUG", True)
        resp = self.res.handle("list")
        self.assertEqual(resp["Content-Type"], "application/json")
        self.assertEqual(resp.status_code, 401)
        self.assertEqual(json.loads(resp.content.decode("utf-8")), {"error": "Unauthorized."})
示例#36
0
    def test_as_view(self):
        # This would be hooked up via the URLconf...
        schema_endpoint = DjTestResource.as_view('schema')
        req = FakeHttpRequest('GET')

        resp = schema_endpoint(req)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)
        schema = json.loads(resp.content.decode('utf-8'))
        self.assertEqual(sorted(list(schema['fields'].keys())), [
            'author',
            'body',
            'id',
            'title',
        ])
        self.assertEqual(schema['fields']['id']['type'], 'integer')
        self.assertEqual(schema['format'], 'application/json')
示例#37
0
    def test_as_list(self):
        list_endpoint = DjTestResource.as_list()
        req = FakeHttpRequest("GET")

        resp = list_endpoint(req)
        self.assertEqual(resp["Content-Type"], "application/json")
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
            json.loads(resp.content.decode("utf-8")),
            {
                "objects": [
                    {"author": "daniel", "body": "Hello world!", "id": 2, "title": "First post"},
                    {"author": "daniel", "body": "Stuff here.", "id": 4, "title": "Another"},
                    {"author": "daniel", "body": "G'bye!", "id": 5, "title": "Last"},
                ]
            },
        )
示例#38
0
 def test_as_list(self):
     resp = self.fetch('/fake_async', method='GET', follow_redirects=False)
     self.assertEqual(resp.headers['Content-Type'],
                      'application/json; charset=UTF-8')
     self.assertEqual(resp.code, 200)
     self.assertEqual(
         json.loads(resp.body.decode('utf-8')), {
             'objects': [{
                 'id': 'dead-beef',
                 'title': 'First post'
             }, {
                 'id': 'de-faced',
                 'title': 'Another'
             }, {
                 'id': 'bad-f00d',
                 'title': 'Last'
             }]
         })
示例#39
0
 def test_raw_serialize(self):
     # This isn't very unit-y, but we're also testing that we're using the
     # right JSON encoder & that it can handle other data types.
     data = {
         'title': 'Cosmos',
         'author': 'Carl Sagan',
         'short_desc': 'A journey through the stars by an emminent astrophysist.',
         'pub_date': datetime.date(1980, 10, 5),
         'price': decimal.Decimal('17.99'),
     }
     res = self.res.raw_serialize(data)
     # Note the keys **don't** get remapped here.
     self.assertEqual(json.loads(res), {
         'author': 'Carl Sagan',
         'price': '17.99',
         'pub_date': '1980-10-05',
         'short_desc': 'A journey through the stars by an emminent astrophysist.',
         'title': 'Cosmos'
     })
示例#40
0
 def test_as_list(self):
     list_endpoint = PyrTestResource.as_list()
     req = FakeHttpRequest('GET')
     resp = list_endpoint(req)
     self.assertEqual(resp.content_type, 'application/json')
     self.assertEqual(resp.status_code, 200)
     self.assertEqual(
         json.loads(resp.body.decode('utf-8')), {
             'objects': [{
                 'id': 'dead-beef',
                 'title': 'First post'
             }, {
                 'id': 'de-faced',
                 'title': 'Another'
             }, {
                 'id': 'bad-f00d',
                 'title': 'Last'
             }]
         })
示例#41
0
    def test_as_list_paginated(self):
        list_endpoint = DjTestResourcePaginated().as_list()
        req = FakeHttpRequest('GET')

        resp = list_endpoint(req)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
            json.loads(resp.content.decode('utf-8')),
            {
                'objects': [
                    {
                        'author': 'daniel',
                        'body': 'Hello world!',
                        'id': 'dead-beef',
                        'title': 'First post',
                    },
                    {
                        'author': 'daniel',
                        'body': 'Stuff here.',
                        'id': 'de-faced',
                        'title': 'Another',
                    },
                    {
                        'author': 'daniel',
                        'body': "G'bye!",
                        'id': 'bad-f00d',
                        'title': 'Last',
                    },
                ],
                'pagination': {
                    'num_pages': 1,
                    'count': 3,
                    'page': 1,
                    'start_index': 1,
                    'end_index': 3,
                    'next_page': None,
                    'previous_page': None,
                    'per_page': 10,
                    },
                 },
                 )
示例#42
0
    def test_as_list_paginated(self):
        list_endpoint = DjTestResourcePaginated().as_list()
        req = FakeHttpRequest('GET')

        resp = list_endpoint(req)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(
            json.loads(resp.content.decode('utf-8')),
            {
                'objects': [
                    {
                        'author': 'daniel',
                        'body': 'Hello world!',
                        'id': 'dead-beef',
                        'title': 'First post',
                    },
                    {
                        'author': 'daniel',
                        'body': 'Stuff here.',
                        'id': 'de-faced',
                        'title': 'Another',
                    },
                    {
                        'author': 'daniel',
                        'body': "G'bye!",
                        'id': 'bad-f00d',
                        'title': 'Last',
                    },
                ],
                'pagination': {
                    'num_pages': 1,
                    'count': 3,
                    'page': 1,
                    'start_index': 1,
                    'end_index': 3,
                    'next_page': None,
                    'previous_page': None,
                    'per_page': 10,
                },
            },
        )
示例#43
0
    def test_as_list(self):
        list_endpoint = ItTestResource.as_list()
        request = FakeHttpRequest('GET')

        resp = list_endpoint(request)
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status, 200)
        self.assertEqual(
            json.loads(resp.output), {
                'objects': [{
                    'id': 2,
                    'title': 'First post'
                }, {
                    'id': 4,
                    'title': 'Another'
                }, {
                    'id': 5,
                    'title': 'Last'
                }]
            })
示例#44
0
    def test_as_view(self):
        # This would be hooked up via the URLconf...
        schema_endpoint = DjTestResource.as_view('schema')
        req = FakeHttpRequest('GET')

        resp = schema_endpoint(req)
        self.assertEqual(resp['Content-Type'], 'application/json')
        self.assertEqual(resp.status_code, 200)
        schema = json.loads(resp.content.decode('utf-8'))
        self.assertEqual(
            sorted(list(schema['fields'].keys())),
            [
                'author',
                'body',
                'id',
                'title',
            ]
        )
        self.assertEqual(schema['fields']['id']['type'], 'integer')
        self.assertEqual(schema['format'], 'application/json')
示例#45
0
    def test_as_list(self):
        list_endpoint = FlTestResource.as_list()
        flask.request = FakeHttpRequest('GET')

        with self.app.test_request_context('/whatever/', method='GET'):
            resp = list_endpoint()
            self.assertEqual(resp.headers['Content-Type'], 'application/json')
            self.assertEqual(resp.status_code, 200)
            self.assertEqual(
                json.loads(resp.data.decode('utf-8')), {
                    'objects': [{
                        'id': 'dead-beef',
                        'title': 'First post'
                    }, {
                        'id': 'de-faced',
                        'title': 'Another'
                    }, {
                        'id': 'bad-f00d',
                        'title': 'Last'
                    }]
                })
示例#46
0
    def test_serialize_list(self):
        data = [{
            'title': 'Cosmos',
            'author': 'Carl Sagan',
            'short_desc':
            'A journey through the stars by an emminent astrophysist.',
            'pub_date': '1980',
        }, {
            'title': "Hitchhiker's Guide To The Galaxy",
            'author': 'Douglas Adams',
            'short_desc': "Don't forget your towel.",
            'pub_date': '1979',
        }]

        self.res.preparer = FieldsPreparer(fields={
            'title': 'title',
            'author': 'author',
            'synopsis': 'short_desc',
        })
        res = self.res.serialize_list(data)
        self.assertEqual(
            json.loads(res), {
                'objects': [
                    {
                        'author': 'Carl Sagan',
                        'synopsis':
                        'A journey through the stars by an emminent astrophysist.',
                        'title': 'Cosmos'
                    },
                    {
                        'title': "Hitchhiker's Guide To The Galaxy",
                        'author': 'Douglas Adams',
                        'synopsis': "Don't forget your towel.",
                    },
                ],
            })

        # Make sure we don't try to serialize a ``None``, which would fail.
        self.assertEqual(self.res.serialize_list(None), '')
示例#47
0
    def test_serialize_list(self):
        data = [
            {
                'title': 'Cosmos',
                'author': 'Carl Sagan',
                'short_desc': 'A journey through the stars by an emminent astrophysist.',
                'pub_date': '1980',
            },
            {
                'title': "Hitchhiker's Guide To The Galaxy",
                'author': 'Douglas Adams',
                'short_desc': "Don't forget your towel.",
                'pub_date': '1979',
            }
        ]

        self.res.fields = {
            'title': 'title',
            'author': 'author',
            'synopsis': 'short_desc',
        }
        res = self.res.serialize_list(data)
        self.assertEqual(json.loads(res), {
            'objects': [
                {
                    'author': 'Carl Sagan',
                    'synopsis': 'A journey through the stars by an emminent astrophysist.',
                    'title': 'Cosmos'
                },
                {
                    'title': "Hitchhiker's Guide To The Galaxy",
                    'author': 'Douglas Adams',
                    'synopsis': "Don't forget your towel.",
                },
            ],
        })

        # Make sure we don't try to serialize a ``None``, which would fail.
        self.assertEqual(self.res.serialize_list(None), '')
示例#48
0
 def test_as_list(self):
     list_endpoint = PyrTestResource.as_list()
     req = FakeHttpRequest('GET')
     resp = list_endpoint(req)
     self.assertEqual(resp.content_type, 'application/json')
     self.assertEqual(resp.status_code, 200)
     self.assertEqual(json.loads(resp.body.decode('utf-8')), {
         'objects': [
             {
                 'id': 2,
                 'title': 'First post'
             },
             {
                 'id': 4,
                 'title': 'Another'
             },
             {
                 'id': 5,
                 'title': 'Last'
             }
         ]
     })
示例#49
0
    def test_serialize_detail(self):
        # This isn't very unit-y, but we're also testing that we're using the
        # right JSON encoder & that it can handle other data types.
        data = {
            'title': 'Cosmos',
            'author': 'Carl Sagan',
            'short_desc': 'A journey through the stars by an emminent astrophysist.',
        }

        self.res.fields = {
            'title': 'title',
            'author': 'author',
            'synopsis': 'short_desc',
        }
        res = self.res.serialize_detail(data)
        self.assertEqual(json.loads(res), {
            'author': 'Carl Sagan',
            'synopsis': 'A journey through the stars by an emminent astrophysist.',
            'title': 'Cosmos'
        })

        # Make sure we don't try to serialize a ``None``, which would fail.
        self.assertEqual(self.res.serialize_detail(None), '')
示例#50
0
    def test_as_list(self):
        list_endpoint = ItTestResource.as_list()
        request = FakeHttpRequest('GET')

        resp = list_endpoint(request)
        self.assertEqual(resp.content_type, 'application/json')
        self.assertEqual(resp.status, 200)
        self.assertEqual(json.loads(resp.output), {
            'objects': [
                {
                    'id': 'dead-beef',
                    'title': 'First post'
                },
                {
                    'id': 'de-faced',
                    'title': 'Another'
                },
                {
                    'id': 'bad-f00d',
                    'title': 'Last'
                }
            ]
        })
示例#51
0
 def test_as_list(self):
     resp = self.fetch(
         '/fake_async',
         method='GET',
         follow_redirects=False
     )
     self.assertEqual(resp.headers['Content-Type'], 'application/json; charset=UTF-8')
     self.assertEqual(resp.code, 200)
     self.assertEqual(json.loads(resp.body.decode('utf-8')), {
         'objects': [
             {
                 'id': 'dead-beef',
                 'title': 'First post'
             },
             {
                 'id': 'de-faced',
                 'title': 'Another'
             },
             {
                 'id': 'bad-f00d',
                 'title': 'Last'
             }
         ]
     })