/
test_manager.py
378 lines (310 loc) · 15.1 KB
/
test_manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
"""
tests.test_manager
~~~~~~~~~~~~~~~~~~
Provides unit tests for the :mod:`flask_restless.manager` module.
:copyright: 2012 Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com>
:license: GNU AGPLv3+ or BSD
"""
import datetime
from unittest2 import skipUnless
from unittest2 import TestCase
from unittest2 import TestSuite
from flask import Flask
from flask import json
try:
from flask.ext.sqlalchemy import SQLAlchemy
except:
has_flask_sqlalchemy = False
else:
has_flask_sqlalchemy = True
from flask.ext.restless import APIManager
from flask.ext.restless.views import _get_columns
from .helpers import FlaskTestBase
from .helpers import setUpModule
from .helpers import tearDownModule
from .helpers import TestSupport
__all__ = ['APIManagerTest']
dumps = json.dumps
loads = json.loads
class APIManagerTest(TestSupport):
"""Unit tests for the :class:`flask_restless.manager.APIManager` class.
"""
def test_init_app(self):
"""Tests for initializing the Flask application after instantiating the
:class:`flask.ext.restless.APIManager` object.
"""
# initialize the Flask application
self.manager.init_app(self.flaskapp, self.session)
# create an API
self.manager.create_api(self.Person)
# make a request on the API
#client = app.test_client()
response = self.app.get('/api/person')
self.assertEqual(response.status_code, 200)
def test_create_api(self):
"""Tests that the :meth:`flask_restless.manager.APIManager.create_api`
method creates endpoints which are accessible by the client, only allow
specified HTTP methods, and which provide a correct API to a database.
"""
# create three different APIs for the same model
self.manager.create_api(self.Person, methods=['GET', 'POST'])
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2')
self.manager.create_api(self.Person, methods=['GET'],
url_prefix='/readonly')
# test that specified endpoints exist
response = self.app.post('/api/person', data=dumps(dict(name='foo')))
self.assertEqual(response.status_code, 201)
self.assertEqual(loads(response.data)['id'], 1)
response = self.app.get('/api/person')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(loads(response.data)['objects']), 1)
self.assertEqual(loads(response.data)['objects'][0]['id'], 1)
# test that non-specified methods are not allowed
response = self.app.delete('/api/person/1')
self.assertEqual(response.status_code, 405)
response = self.app.patch('/api/person/1',
data=dumps(dict(name='bar')))
self.assertEqual(response.status_code, 405)
# test that specified endpoints exist
response = self.app.patch('/api2/person/1',
data=dumps(dict(name='bar')))
self.assertEqual(response.status_code, 200)
self.assertEqual(loads(response.data)['id'], 1)
self.assertEqual(loads(response.data)['name'], 'bar')
# test that non-specified methods are not allowed
response = self.app.get('/api2/person/1')
self.assertEqual(response.status_code, 405)
response = self.app.delete('/api2/person/1')
self.assertEqual(response.status_code, 405)
response = self.app.post('/api2/person',
data=dumps(dict(name='baz')))
self.assertEqual(response.status_code, 405)
# test that the model is the same as before
response = self.app.get('/readonly/person')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(loads(response.data)['objects']), 1)
self.assertEqual(loads(response.data)['objects'][0]['id'], 1)
self.assertEqual(loads(response.data)['objects'][0]['name'], 'bar')
def test_different_collection_name(self):
"""Tests that providing a different collection name exposes the API at
the corresponding URL.
"""
self.manager.create_api(self.Person, methods=['POST', 'GET'],
collection_name='people')
response = self.app.post('/api/people', data=dumps(dict(name='foo')))
self.assertEqual(response.status_code, 201)
self.assertEqual(loads(response.data)['id'], 1)
response = self.app.get('/api/people')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(loads(response.data)['objects']), 1)
self.assertEqual(loads(response.data)['objects'][0]['id'], 1)
response = self.app.get('/api/people/1')
self.assertEqual(response.status_code, 200)
self.assertEqual(loads(response.data)['id'], 1)
def test_allow_functions(self):
"""Tests that the ``allow_functions`` keyword argument makes a
:http:get:`/api/eval/...` endpoint available.
"""
self.manager.create_api(self.Person, allow_functions=True)
response = self.app.get('/api/eval/person', data=dumps(dict()))
self.assertNotEqual(response.status_code, 400)
self.assertEqual(response.status_code, 204)
def test_disallow_functions(self):
"""Tests that if the ``allow_functions`` keyword argument if ``False``,
no endpoint will be made available at :http:get:`/api/eval/...`.
"""
self.manager.create_api(self.Person, allow_functions=False)
response = self.app.get('/api/eval/person')
self.assertNotEqual(response.status_code, 200)
self.assertEqual(response.status_code, 404)
def test_include_columns(self):
"""Tests that the `include_columns` argument specifies which columns to
return in the JSON representation of instances of the model.
"""
all_columns = _get_columns(self.Person)
# allow all
self.manager.create_api(self.Person, include_columns=None,
url_prefix='/all')
self.manager.create_api(self.Person, include_columns=all_columns,
url_prefix='/all2')
# allow some
self.manager.create_api(self.Person, include_columns=('name', 'age'),
url_prefix='/some')
# allow none
self.manager.create_api(self.Person, include_columns=(),
url_prefix='/none')
# create a test person
self.manager.create_api(self.Person, methods=['POST'],
url_prefix='/add')
d = dict(name=u'Test', age=10, other=20,
birth_date=datetime.date(1999, 12, 31).isoformat())
response = self.app.post('/add/person', data=dumps(d))
self.assertEqual(response.status_code, 201)
personid = loads(response.data)['id']
# get all
response = self.app.get('/all/person/%s' % personid)
for column in 'name', 'age', 'other', 'birth_date', 'computers':
self.assertIn(column, loads(response.data))
response = self.app.get('/all2/person/%s' % personid)
for column in 'name', 'age', 'other', 'birth_date', 'computers':
self.assertIn(column, loads(response.data))
# get some
response = self.app.get('/some/person/%s' % personid)
for column in 'name', 'age':
self.assertIn(column, loads(response.data))
for column in 'other', 'birth_date', 'computers':
self.assertNotIn(column, loads(response.data))
# get none
response = self.app.get('/none/person/%s' % personid)
for column in 'name', 'age', 'other', 'birth_date', 'computers':
self.assertNotIn(column, loads(response.data))
def test_different_urls(self):
"""Tests that establishing different URL endpoints for the same model
affect the same database table.
"""
methods = frozenset(('get', 'patch', 'post', 'delete'))
# create a separate endpoint for each HTTP method
for method in methods:
url = '/%s' % method
self.manager.create_api(self.Person, methods=[method.upper()],
url_prefix=url)
# test for correct requests
response = self.app.get('/get/person')
self.assertEqual(response.status_code, 200)
response = self.app.post('/post/person', data=dumps(dict(name='Test')))
self.assertEqual(response.status_code, 201)
response = self.app.patch('/patch/person/1',
data=dumps(dict(name='foo')))
self.assertEqual(response.status_code, 200)
response = self.app.delete('/delete/person/1')
self.assertEqual(response.status_code, 204)
# test for incorrect requests
response = self.app.get('/post/person')
self.assertEqual(response.status_code, 405)
response = self.app.get('/patch/person/1')
self.assertEqual(response.status_code, 405)
response = self.app.get('/delete/person/1')
self.assertEqual(response.status_code, 405)
response = self.app.post('/get/person')
self.assertEqual(response.status_code, 405)
response = self.app.post('/patch/person/1')
self.assertEqual(response.status_code, 405)
response = self.app.post('/delete/person/1')
self.assertEqual(response.status_code, 405)
response = self.app.patch('/get/person')
self.assertEqual(response.status_code, 405)
response = self.app.patch('/post/person')
self.assertEqual(response.status_code, 405)
response = self.app.patch('/delete/person/1')
self.assertEqual(response.status_code, 405)
response = self.app.delete('/get/person')
self.assertEqual(response.status_code, 405)
response = self.app.delete('/post/person')
self.assertEqual(response.status_code, 405)
response = self.app.delete('/patch/person/1')
self.assertEqual(response.status_code, 405)
# test that the same model is updated on all URLs
response = self.app.post('/post/person', data=dumps(dict(name='Test')))
self.assertEqual(response.status_code, 201)
response = self.app.get('/get/person/1')
self.assertEqual(response.status_code, 200)
self.assertEqual(loads(response.data)['name'], 'Test')
response = self.app.patch('/patch/person/1',
data=dumps(dict(name='Foo')))
self.assertEqual(response.status_code, 200)
response = self.app.get('/get/person/1')
self.assertEqual(response.status_code, 200)
self.assertEqual(loads(response.data)['name'], 'Foo')
response = self.app.delete('/delete/person/1')
self.assertEqual(response.status_code, 204)
response = self.app.get('/get/person/1')
self.assertEqual(response.status_code, 404)
def test_session_class(self):
"""Test for providing a session class instead of a sesssion instance.
"""
manager = APIManager(self.flaskapp, session=self.Session)
manager.create_api(self.Person, methods=['GET', 'POST'])
response = self.app.get('/api/person')
self.assertEqual(response.status_code, 200)
response = self.app.post('/api/person', data=dumps(dict(name='foo')))
self.assertEqual(response.status_code, 201)
response = self.app.get('/api/person/1')
self.assertEqual(response.status_code, 200)
self.assertEqual(loads(response.data)['id'], 1)
class FSATest(FlaskTestBase):
"""Tests which use models defined using Flask-SQLAlchemy instead of pure
SQLAlchemy.
"""
def setUp(self):
"""Creates the Flask application, the APIManager, the database, and the
Flask-SQLAlchemy models.
"""
super(FSATest, self).setUp()
# initialize SQLAlchemy and Flask-Restless
self.db = SQLAlchemy(self.flaskapp)
self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
# for the sake of brevity...
db = self.db
# declare the models
class Computer(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
vendor = db.Column(db.Unicode)
buy_date = db.Column(db.DateTime)
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'))
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Unicode, unique=True)
age = db.Column(db.Float)
other = db.Column(db.Float)
birth_date = db.Column(db.Date)
computers = db.relationship('Computer',
backref=db.backref('owner',
lazy='dynamic'))
self.Person = Person
self.Computer = Computer
# create all the tables required for the models
self.db.create_all()
def tearDown(self):
"""Drops all tables from the temporary database."""
self.db.drop_all()
def test_flask_sqlalchemy(self):
"""Tests that :class:`flask.ext.restless.APIManager` correctly exposes
models defined using Flask-SQLAlchemy.
"""
# create three different APIs for the same model
self.manager.create_api(self.Person, methods=['GET', 'POST'])
self.manager.create_api(self.Person, methods=['PATCH'],
url_prefix='/api2')
self.manager.create_api(self.Person, methods=['GET'],
url_prefix='/readonly')
# test that specified endpoints exist
response = self.app.post('/api/person', data=dumps(dict(name='foo')))
self.assertEqual(response.status_code, 201)
self.assertEqual(loads(response.data)['id'], 1)
response = self.app.get('/api/person')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(loads(response.data)['objects']), 1)
self.assertEqual(loads(response.data)['objects'][0]['id'], 1)
response = self.app.patch('/api2/person/1',
data=dumps(dict(name='bar')))
self.assertEqual(response.status_code, 200)
self.assertEqual(loads(response.data)['id'], 1)
self.assertEqual(loads(response.data)['name'], 'bar')
# test that the model is the same as before
response = self.app.get('/readonly/person')
self.assertEqual(response.status_code, 200)
self.assertEqual(len(loads(response.data)['objects']), 1)
self.assertEqual(loads(response.data)['objects'][0]['id'], 1)
self.assertEqual(loads(response.data)['objects'][0]['name'], 'bar')
# skipUnless should be used as a decorator, but Python 2.5 doesn't have
# decorators.
FSATest = skipUnless(has_flask_sqlalchemy,
'Flask-SQLAlchemy not found.')(FSATest)
def load_tests(loader, standard_tests, pattern):
"""Returns the test suite for this module."""
suite = TestSuite()
suite.addTest(loader.loadTestsFromTestCase(APIManagerTest))
suite.addTest(loader.loadTestsFromTestCase(FSATest))
return suite