-
Notifications
You must be signed in to change notification settings - Fork 170
/
Copy pathtest_sandman.py
511 lines (430 loc) · 20.9 KB
/
test_sandman.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
"""Main test class for sandman"""
import os
import shutil
import json
import datetime
from sandman import app
class TestSandmanBase(object):
"""Base class for all sandman test classes."""
DB_LOCATION = os.path.join(os.getcwd(), 'tests', 'chinook.sqlite3')
def setup_method(self, _):
"""Grab the database file from the *data* directory and configure the
app."""
shutil.copy(
os.path.join(
os.getcwd(),
'tests',
'data',
'chinook.sqlite3'),
self.DB_LOCATION)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + self.DB_LOCATION
app.config['SANDMAN_SHOW_PKS'] = False
app.config['SANDMAN_GENERATE_PKS'] = False
app.config['TESTING'] = True
self.app = app.test_client()
#pylint: disable=unused-variable
from . import models
def teardown_method(self, _):
"""Remove the database file copied during setup."""
os.unlink(self.DB_LOCATION)
#pylint: disable=attribute-defined-outside-init
self.app = None
#pylint: disable=too-many-arguments
def get_response(self, uri, status_code, params=None, has_data=True,
headers=None):
"""Return the response generated from a generic GET request. Do basic
validation on the response."""
if headers is None:
headers = {}
response = self.app.get(uri, query_string=params, headers=headers)
assert response.status_code == status_code
if has_data:
assert response.get_data(as_text=True)
return response
def post_response(self):
"""Return the response generated from a generic POST request. Do basic
validation on the response."""
response = self.app.post('/artists',
content_type='application/json',
data=json.dumps({u'Name': u'Jeff Knupp'}))
assert response.status_code == 201
assert json.loads(response.get_data(as_text=True))[u'Name'] == u'Jeff Knupp'
return response
@staticmethod
def is_html_response(response):
"""Return True if *response* is an HTML response"""
assert 'text/html' in str(response.headers['Content-type'])
return '<!DOCTYPE html>' in response.get_data(as_text=True)
class TestSandmanBasicVerbs(TestSandmanBase):
"""Test the basic HTTP verbs (e.g. "PUT", "GET", etc.)"""
def test_get(self):
"""Test simple HTTP GET"""
response = self.get_response('/artists', 200)
assert len(json.loads(response.get_data(as_text=True))[u'resources']) == 275
def test_get_with_limit(self):
"""Test simple HTTP GET"""
response = self.get_response('/artists', 200, params={'limit': 10})
assert len(json.loads(response.get_data(as_text=True))[u'resources']) == 10
def test_get_with_filter(self):
"""Test simple HTTP GET"""
response = self.get_response('/artists', 200, params={'Name': 'AC/DC'})
assert len(json.loads(response.get_data(as_text=True))[u'resources']) == 1
def test_get_with_like_filter(self):
"""Test simple HTTP GET"""
response = self.get_response('/artists', 200, params={'Name': '%AC%DC%'})
assert len(json.loads(response.get_data(as_text=True))[u'resources']) == 1
def test_get_with_sort(self):
"""Test simple HTTP GET"""
response = self.get_response('/artists', 200, params={'sort': 'Name'})
assert json.loads(response.get_data(as_text=True))[u'resources'][0]['Name'] == 'A Cor Do Som'
def test_get_attribute(self):
"""Test simple HTTP GET"""
response = self.get_response('/artists/1/Name', 200)
assert json.loads(response.get_data(as_text=True))[u'Name'] == 'AC/DC'
def test_get_meta(self):
"""Test simple HTTP GET"""
response = self.get_response('/', 200)
assert 'meta' in json.loads(response.get_data(as_text=True))['artists']
def test_get_root(self):
"""Test simple HTTP GET"""
response = self.get_response('/artists/meta', 200)
assert 'Name' in json.loads(response.get_data(as_text=True))['Artist']
def test_get_object_attribute(self):
"""Test simple HTTP GET"""
response = self.get_response('/tracks/347', 200)
response = self.get_response('/tracks/347/Genre', 200)
assert json.loads(response.get_data(as_text=True))[u'Name'] == 'Rock'
def test_get_link_header_for_resource(self):
"""Does GETing a resource return the 'Link' header field?"""
response = self.get_response('/tracks/1', 200)
assert 'Link' in response.headers
assert '</MediaType/1>; rel="related"' in response.headers['Link']
assert self.get_response('/Album/1', 200).data is not None
def test_get_expanded_resource(self):
"""Does GETing a resource return the 'Link' header field?"""
response = self.get_response('/tracks/1', 200, params={'expand': 1})
assert 'album' in json.loads(response.get_data(as_text=True))
def test_get_etag_header(self):
"""Does GETing a resource with the ETag header return a 304?"""
response = self.get_response('/tracks/1', 200)
assert 'ETag' in response.headers
etag_value = response.headers['ETag']
cached_response = self.get_response('/tracks/1', 304, headers={'If-None-Match': etag_value}, has_data=False)
def test_get_etag_no_match(self):
"""Does GETing a resource return the 'Link' header field?"""
response = self.get_response('/tracks/1', 200)
assert 'ETag' in response.headers
cached_response = self.get_response('/tracks/1', 412, headers={'If-Match': 'foo'}, has_data=False)
def test_post(self):
"""Test simple HTTP POST"""
response = self.post_response()
assert json.loads(response.get_data(as_text=True)) == {
'ArtistId': 276,
'Name': 'Jeff Knupp',
'self': '/artists/276',
'links': [{'rel': 'self', 'uri': '/artists/276'}]}
def test_posted_location(self):
"""Make sure 'Location' header returned in response actually points to
new resource created during POST."""
post_response = self.post_response()
location = post_response.headers['Location']
self.get_response(location, 200)
def test_posted_uri(self):
"""Make sure 'uri' in the links returned in response actually points to
new resource created during POST."""
post_response = self.post_response()
as_json = json.loads(post_response.get_data(as_text=True))
assert as_json == {
'ArtistId': 276,
'Name': 'Jeff Knupp',
'self': '/artists/276',
'links': [{'rel': 'self', 'uri': '/artists/276'}]
}
uri = as_json['self']
self.app.get(uri)
assert as_json[u'Name'] == u'Jeff Knupp'
def test_patch_new_resource(self):
"""Send HTTP PATCH for a resource which doesn't exist (should be
created)."""
response = self.app.patch('/artists/276',
content_type='application/json',
data=json.dumps({u'Name': u'Jeff Knupp'}))
assert response.status_code == 201
assert json.loads(response.get_data(as_text=True))['Name'] == u'Jeff Knupp'
assert json.loads(response.get_data(as_text=True))['self'] == '/artists/276'
def test_patch_existing_resource(self):
"""Send HTTP PATCH for an existing resource (should be updated)."""
response = self.app.patch('/artists/275',
content_type='application/json',
data=json.dumps({u'Name': u'Jeff Knupp'}))
assert response.status_code == 204
response = self.get_response('/artists/275', 200)
assert json.loads(
response.get_data(as_text=True))[u'Name'] == u'Jeff Knupp'
assert json.loads(
response.get_data(as_text=True))[u'ArtistId'] == 275
def test_delete_resource(self):
"""Test DELETEing a resource."""
response = self.app.delete('/artists/239')
assert response.status_code == 204
response = self.get_response('/artists/239', 404, False)
def test_delete_resource_violating_constraint(self):
"""Test DELETEing a resource which violates a foreign key
constraint (i.e. the record is still referred to in another table)."""
response = self.app.delete('/artists/275')
assert response.status_code == 422
def test_delete_non_existant_resource(self):
"""Test DELETEing a resource that doesn't exist."""
response = self.app.delete('/artists/404')
assert response.status_code == 404
def test_put_resource(self):
"""Test HTTP PUTing a resource that already exists (should be
updated)."""
response = self.app.put('/tracks/1',
content_type='application/json',
data=json.dumps(
{'Name': 'Some New Album',
'AlbumId': 1,
'GenreId': 1,
'MediaTypeId': 1,
'Milliseconds': 343719,
'TrackId': 1,
'UnitPrice': 0.99,}))
assert response.status_code == 204
response = self.get_response('/tracks/1', 200)
assert json.loads(
response.get_data(as_text=True))[u'Name'] == u'Some New Album'
assert json.loads(
response.get_data(as_text=True))[u'Composer'] is None
def test_put_unknown_resource(self):
"""Test HTTP PUTing a resource that doesn't exist. Should give 404."""
response = self.app.put('/tracks/99999',
content_type='application/json',
data=json.dumps(
{'Name': 'Some New Album',
'AlbumId': 1,
'GenreId': 1,
'MediaTypeId': 1,
'Milliseconds': 343719,
'TrackId': 99999,
'UnitPrice': 0.99,}))
assert response.status_code == 404
def test_put_invalid_foreign_key(self):
"""Test HTTP PUTing a resource with a field that refers to a
non-existent resource (i.e. violate a foreign key constraint)."""
response = self.app.put('/tracks/998',
content_type='application/json',
data=json.dumps(
{'Name': 'Some New Album',
'Milliseconds': 343719,
'TrackId': 998,
'UnitPrice': 0.99,}))
assert response.status_code == 422
class TestSandmanUserDefinitions(TestSandmanBase):
"""Sandman tests related to user-defined functionality"""
def test_user_defined_endpoint(self):
"""Make sure user-defined endpoint exists."""
response = self.get_response('/styles', 200)
assert len(json.loads(response.get_data(as_text=True))[u'resources']) == 25
def test_user_validation_reject(self):
"""Test user-defined validation which on request which should be
rejected."""
self.get_response('/styles/1', 403, False)
def test_user_validation_accept(self):
"""Test user-defined validation which on request which should be
accepted."""
self.get_response('/styles/2', 200)
def test_put_fail_validation(self):
"""Test HTTP PUTing a resource that fails user-defined validation."""
response = self.app.put('/tracks/999',
content_type='application/json',
data=json.dumps(
{'Name': 'Some New Album',
'GenreId': 1,
'AlbumId': 1,
'MediaTypeId': 1,
'Milliseconds': 343719,
'TrackId': 999,
'UnitPrice': 0.99,}))
assert response.status_code == 403
def test_responds_with_top_level_json_name_if_present(self):
"""Test top level json element is the one defined on the Model
rather than the string 'resources'"""
response = self.get_response('/albums', 200)
assert len(json.loads(response.get_data(as_text=True))[u'Albums']) == 347
class TestSandmanValidation(TestSandmanBase):
"""Sandman tests related to request validation"""
def test_delete_not_supported(self):
"""Test DELETEing a resource for an endpoint that doesn't support it."""
response = self.app.delete('/playlists/1')
assert response.status_code == 403
def test_unsupported_patch_resource(self):
"""Test PATCHing a resource for an endpoint that doesn't support it."""
response = self.app.patch('/styles/26',
content_type='application/json',
data=json.dumps({u'Name': u'Hip-Hop'}))
assert response.status_code == 403
def test_unsupported_get_resource(self):
"""Test GETing a resource for an endpoint that doesn't support it."""
self.get_response('/playlists', 403, False)
def test_unsupported_collection_method(self):
"""Test POSTing a collection for an endpoint that doesn't support it."""
response = self.app.post('/styles',
content_type='application/json',
data=json.dumps({u'Name': u'Jeff Knupp'}))
assert response.status_code == 403
def test_pagination(self):
"""Can we get paginated results?"""
response = self.get_response('/artists', 200, params={'page': 2})
assert len(json.loads(response.get_data(as_text=True))['resources']) == 20
class TestSandmanContentTypes(TestSandmanBase):
"""Sandman tests related to content types"""
def test_get_html(self):
"""Test getting HTML version of a resource rather than JSON."""
response = self.get_response('/artists/1',
200,
headers={'Accept': 'text/html'})
assert self.is_html_response(response)
def test_get_html_attribute(self):
"""Test getting HTML version of a resource rather than JSON."""
response = self.get_response('/artists/1/Name',
200,
headers={'Accept': 'text/html'})
assert self.is_html_response(response)
def test_get_html_non_existant_resource(self):
"""Test getting HTML version of a resource rather than JSON."""
response = self.get_response('/artists/99999',
404,
headers={'Accept': 'text/html'})
assert self.is_html_response(response)
def test_get_meta_html(self):
"""Test simple HTTP GET"""
response = self.get_response('/', 200, headers={'Accept': 'text/html'})
assert 'meta' in response.get_data(as_text=True)
def test_get_html_collection(self):
"""Test getting HTML version of a collection rather than JSON."""
response = self.get_response('/artists',
200,
headers={'Accept': 'text/html'})
assert self.is_html_response(response)
assert 'Aerosmith' in response.get_data(as_text=True)
def test_get_json(self):
"""Test explicitly getting the JSON version of a resource."""
response = self.get_response('/artists',
200,
headers={'Accept': 'application/json'})
assert len(json.loads(response.get_data(as_text=True))[u'resources']) == 275
def test_get_unknown_url(self):
"""Test sending a GET request to a URL that would match the
URL patterns of the API but is not a valid endpoint (e.g. 'foo/bar')."""
self.get_response('/foo/bar', 404)
def test_delete_resource_html(self):
"""Test DELETEing a resource via HTML."""
response = self.app.delete('/artists/239',
headers={'Accept': 'text/html'})
assert response.status_code == 204
assert response.headers['Content-type'].startswith('text/html')
response = self.get_response('/artists/239',
404,
False,
headers={'Accept': 'text/html'})
assert response.headers['Content-type'].startswith('text/html')
def test_patch_new_resource_html(self):
"""Send HTTP PATCH for a resource which doesn't exist (should be
created)."""
response = self.app.patch('/artists/276',
data={'Name': 'Jeff Knupp'},
headers={'Accept': 'text/html'})
assert response.status_code == 201
assert self.is_html_response(response)
def test_post_html_response(self):
"""Test POSTing a resource via form parameters and requesting the
response be HTML formatted."""
response = self.app.post('/artists',
headers={'Accept': 'text/html'},
data={u'Name': u'Jeff Knupp'})
assert response.status_code == 201
assert 'Jeff Knupp' in str(response.get_data(as_text=True))
def test_post_html_with_charset(self):
"""Test POSTing a resource with a Content-Type that specifies a
character set."""
response = self.app.post('/artists',
content_type='application/x-www-form-urlencoded',
charset='UTF-8;',
headers={'Accept': 'text/html'},
data={u'Name': u'Jeff Knupp'})
assert response.status_code == 201
assert 'Jeff Knupp' in str(response.get_data(as_text=True))
def test_post_no_json_data(self):
"""Test POSTing a resource with no JSON data."""
response = self.app.post('/artists',
content_type='application/json',
data=dict())
assert response.status_code == 400
def test_post_no_html_form_data(self):
"""Test POSTing a resource with no form data."""
response = self.app.post('/artists',
data=dict())
assert response.status_code == 400
def test_post_unsupported_content_type(self):
"""Test POSTing with an unsupported Content-type."""
response = self.app.post('/artists',
content_type='foobar',
data={'Foo': 'bar'})
assert response.status_code == 415
def test_post_unsupported_accept_type(self):
"""Test POSTing with an unsupported Accept content-type."""
response = self.app.post('/artists',
headers={'Accept': 'foo'},
data={'Foo': 'bar'})
assert response.status_code == 415
def test_put_unknown_resource_form_data(self):
"""Test HTTP PUTing a resource that doesn't exist. Should give 404."""
response = self.app.put('/tracks/99999',
data={'Name': 'Some New Album',
'AlbumId': 1,
'GenreId': 1,
'MediaTypeId': 1,
'Milliseconds': 343719,
'TrackId': 99999,
'UnitPrice': 0.99,})
assert response.status_code == 404
class TestSandmanAdmin(TestSandmanBase):
"""Test the admin GUI functionality."""
def test_admin_index(self):
"""Ensure the main admin page is served correctly."""
self.get_response('/admin/', 200)
def test_admin_collection_view(self):
"""Ensure user-defined ``__str__`` implementations are being picked up
by the admin."""
response = self.get_response('/admin/trackview/', 200)
# If related tables are being loaded correctly, Tracks will have a
# Mediatype column, at least one of which has the value 'MPEG audio
# file'.
assert 'MPEG audio file' in str(response.get_data(as_text=True))
def test_admin_default_str_repr(self):
"""Ensure default ``__str__`` implementations works in the admin."""
response = self.get_response('/admin/trackview/?page=3/', 200)
# If related tables are being loaded correctly, Tracks will have a
# Genre column, but should display the GenreId and not the name ('Jazz'
# is the genre for many results on the third page
assert 'Jazz' not in str(response.get_data(as_text=True))
#pylint: disable=invalid-name
def test_admin_default_str_repr_different_table_class_name(self):
"""Ensure default ``__str__`` representation for classes where the
classname differs from the table name show up with the classname (not the
table name)."""
response = self.get_response('/admin/styleview/', 200)
assert 'Genre' not in str(response.get_data(as_text=True))
class TestExistingModel(TestSandmanBase):
"""Test the functionality allowing exisitng DB Models to be registered as
resources."""
def setup_method(self, args):
super(TestExistingModel, self).setup_method(args)
app.config['SANDMAN_SHOW_PKS'] = True
def test_get_resource_for_existing_model(self):
"""Can we get a resource for an existing model?"""
self.get_response('/somemodels/1', 200)
def test_get_meta_for_existing_class(self):
"""Can we get the meta information for an existing model."""
self.get_response('/somemodels/meta', 200)