2
# Copyright 2013 Canonical Ltd.
4
# This program is free software: you can redistribute it and/or modify it
5
# under the terms of the GNU Affero General Public License version 3, as
6
# published by the Free Software Foundation.
8
# This program is distributed in the hope that it will be useful, but
9
# WITHOUT ANY WARRANTY; without even the implied warranties of
10
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11
# PURPOSE. See the GNU Affero General Public License for more details.
13
# You should have received a copy of the GNU Affero General Public License
14
# along with this program. If not, see <http://www.gnu.org/licenses/>.
18
from django.contrib.auth.models import User
19
from django.test import TestCase
21
from tastypie.models import ApiKey
22
from tastypie.test import TestApiClient
25
class TastypieTestCase(TestCase):
26
'''A base class for RESTFul services.'''
28
def setUp(self, resource_base):
29
'''Set up an admin user that can make POST/PATCH calls.'''
30
self.resource_base = resource_base
31
if resource_base[-1] == '/':
32
self.resource_base = resource_base[:-1]
34
# create an api key for "post" operations
35
u = User.objects.create(username='admin', is_superuser=True)
36
k = ApiKey.objects.create(user=u, key='key')
37
self.auth = 'ApiKey %s:%s' % (u.username, k.key)
38
self.client = TestApiClient()
40
def _resource(self, resource):
41
if resource[0] == '/' or resource.startswith('http://'):
42
# assume the caller is passing the full path
44
return self.resource_base + '/' + resource
46
def get(self, resource, params={}):
47
'''Get the resource and return resource as dict.'''
48
resource = self._resource(resource)
49
return json.loads(self.client.get(resource, data=params).content)
51
def post(self, resource, params):
52
'''Create the resource and return location of the new object.'''
53
resource = self._resource(resource)
54
resp = self.client.post(
55
resource, data=params, authentication=self.auth)
56
self.assertEqual(201, resp.status_code)
57
return resp['location']
59
def patch(self, resource, params):
60
'''Update an existing resource.'''
61
resource = self._resource(resource)
62
resp = self.client.patch(
63
resource, data=params, authentication=self.auth)
64
self.assertEqual(202, resp.status_code)
66
def getResource(self, resource, params={}):
67
'''Grab a single resource and return it as a dict.'''
68
obj = self.get(resource, params)
70
self.assertEqual(1, len(obj['objects']))
71
obj = obj['objects'][0]
74
def createResource(self, resource, params):
75
'''Create a resource, get it, and return the dict.'''
76
loc = self.post(resource, params)
77
return self.getResource(loc)