-
Notifications
You must be signed in to change notification settings - Fork 300
/
test_views.py
2314 lines (1959 loc) · 90.5 KB
/
test_views.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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- encoding: utf-8 -*-
"""
tests.test_views
~~~~~~~~~~~~~~~~
Provides unit tests for the :mod:`flask_restless.views` module.
:copyright: 2011 by Lincoln de Sousa <lincoln@comum.org>
:copyright: 2012, 2013, 2014, 2015 Jeffrey Finkelstein
<jeffrey.finkelstein@gmail.com> and contributors.
:license: GNU AGPLv3+ or BSD
"""
from datetime import date
from datetime import datetime
from datetime import timedelta
import math
# In Python 2, the function is `urllib.quote()`, in Python 3 it is
# `urllib.parse.quote()`.
try:
from urllib.parse import quote as urlquote
except:
from urllib import quote as urlquote
import dateutil
from flask import json
try:
from flask.ext.sqlalchemy import SQLAlchemy
except:
has_flask_sqlalchemy = False
else:
has_flask_sqlalchemy = True
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy import Unicode
from sqlalchemy.ext.associationproxy import association_proxy as prox
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from sqlalchemy.orm import relationship as rel
from sqlalchemy.orm.collections import column_mapped_collection as col_mapped
from flask.ext.restless.helpers import to_dict
from flask.ext.restless.manager import APIManager
from .helpers import FlaskTestBase
from .helpers import ManagerTestBase
from .helpers import skip_unless
from .helpers import TestSupport
from .helpers import TestSupportPrefilled
from .helpers import unregister_fsa_session_signals
dumps = json.dumps
loads = json.loads
#: The User-Agent string for Microsoft Internet Explorer 8.
#:
#: From <http://blogs.msdn.com/b/ie/archive/2008/02/21/the-internet-explorer-8-user-agent-string.aspx>.
MSIE8_UA = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'
#: The User-Agent string for Microsoft Internet Explorer 9.
#:
#: From <http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx>.
MSIE9_UA = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
@skip_unless(has_flask_sqlalchemy, 'Flask-SQLAlchemy not found.')
class TestFSAModel(FlaskTestBase):
"""Tests for functions which operate on Flask-SQLAlchemy models."""
def setUp(self):
"""Creates the Flask-SQLAlchemy database and models."""
super(TestFSAModel, self).setUp()
db = SQLAlchemy(self.flaskapp)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
class Pet(db.Model):
id = db.Column(db.Integer, primary_key=True)
ownerid = db.Column(db.Integer, db.ForeignKey(User.id))
owner = db.relationship(User, backref=db.backref('pets'))
class LazyUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
class LazyPet(db.Model):
id = db.Column(db.Integer, primary_key=True)
ownerid = db.Column(db.Integer, db.ForeignKey(LazyUser.id))
owner = db.relationship(LazyUser,
backref=db.backref('pets', lazy='dynamic'))
self.User = User
self.Pet = Pet
self.LazyUser = LazyUser
self.LazyPet = LazyPet
self.db = db
self.db.create_all()
self.manager = APIManager(self.flaskapp, flask_sqlalchemy_db=self.db)
def tearDown(self):
"""Drops all tables."""
self.db.drop_all()
unregister_fsa_session_signals()
def test_get(self):
"""Test for the :meth:`views.API.get` method with models defined using
Flask-SQLAlchemy with both dynamically loaded and static relationships.
"""
# create the API endpoint
self.manager.create_api(self.User)
self.manager.create_api(self.LazyUser)
self.manager.create_api(self.Pet)
self.manager.create_api(self.LazyPet)
response = self.app.get('/api/user')
assert 200 == response.status_code
response = self.app.get('/api/lazy_user')
assert 200 == response.status_code
response = self.app.get('/api/pet')
assert 200 == response.status_code
response = self.app.get('/api/lazy_pet')
assert 200 == response.status_code
# create a user with two pets
owner = self.User()
pet1 = self.Pet()
pet2 = self.Pet()
pet3 = self.Pet()
pet1.owner = owner
pet2.owner = owner
self.db.session.add_all([owner, pet1, pet2, pet3])
self.db.session.commit()
response = self.app.get('/api/user/{0:d}'.format(owner.id))
assert 200 == response.status_code
data = loads(response.data)
assert 2 == len(data['pets'])
for pet in data['pets']:
assert owner.id == pet['ownerid']
response = self.app.get('/api/pet/1')
assert 200 == response.status_code
data = loads(response.data)
assert not isinstance(data['owner'], list)
assert owner.id == data['ownerid']
# create a lazy user with two lazy pets
owner = self.LazyUser()
pet1 = self.LazyPet()
pet2 = self.LazyPet()
pet1.owner = owner
pet2.owner = owner
self.db.session.add_all([owner, pet1, pet2])
self.db.session.commit()
response = self.app.get('/api/lazy_user/{0:d}'.format(owner.id))
assert 200 == response.status_code
data = loads(response.data)
assert 2 == len(data['pets'])
for pet in data['pets']:
assert owner.id == pet['ownerid']
response = self.app.get('/api/lazy_pet/1')
assert 200 == response.status_code
data = loads(response.data)
assert not isinstance(data['owner'], list)
assert owner.id == data['ownerid']
# Check that it's possible to get owner if not null
response = self.app.get('/api/pet/1/owner')
assert 200 == response.status_code
data = loads(response.data)
assert 2 == len(data['pets'])
# And that we get a 404 if owner is null
response = self.app.get('/api/pet/3/owner')
assert 404 == response.status_code
class TestFunctionAPI(TestSupportPrefilled):
"""Unit tests for the :class:`flask_restless.views.FunctionAPI` class."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`testapp.Person` and
:class:`testapp.Computer` models.
"""
super(TestFunctionAPI, self).setUp()
self.manager.create_api(self.Person, allow_functions=True)
def test_function_evaluation(self):
"""Test that the :http:get:`/api/eval/person` endpoint returns the
result of evaluating functions.
"""
functions = [{'name': 'sum', 'field': 'age'},
{'name': 'avg', 'field': 'other'},
{'name': 'count', 'field': 'id'}]
query = dumps(dict(functions=functions))
response = self.app.get('/api/eval/person?q={0}'.format(query))
assert response.status_code == 200
data = loads(response.data)
assert 'sum__age' in data
assert data['sum__age'] == 102.0
assert 'avg__other' in data
assert data['avg__other'] == 16.2
assert 'count__id' in data
assert data['count__id'] == 5
def test_no_functions(self):
"""Tests that if no functions are defined, an empty response is
returned.
"""
# no data is invalid JSON
response = self.app.get('/api/eval/person')
assert response.status_code == 400
# so is the empty string
response = self.app.get('/api/eval/person?q=')
assert response.status_code == 400
# if we provide no functions, then we expect an empty response
response = self.app.get('/api/eval/person?q={0}'.format(dumps(dict())))
assert response.status_code == 204
def test_poorly_defined_functions(self):
"""Tests that poorly defined requests for function evaluations cause an
error message to be returned.
"""
# test for bad field name
search = {'functions': [{'name': 'sum', 'field': 'bogusfieldname'}]}
resp = self.app.get('/api/eval/person?q={0}'.format(dumps(search)))
assert resp.status_code == 400
assert 'message' in loads(resp.data)
assert 'bogusfieldname' in loads(resp.data)['message']
# test for bad function name
search = {'functions': [{'name': 'bogusfuncname', 'field': 'age'}]}
resp = self.app.get('/api/eval/person?q={0}'.format(dumps(search)))
assert resp.status_code == 400
assert 'message' in loads(resp.data)
assert 'bogusfuncname' in loads(resp.data)['message']
def test_jsonp(self):
"""Test for JSON-P callbacks."""
person1 = self.Person(age=10)
person2 = self.Person(age=20)
person3 = self.Person(age=35)
self.session.add_all([person1, person2, person3])
self.session.commit()
functions = [{'name': 'sum', 'field': 'age'}]
query = dumps(dict(functions=functions))
# JSONP should work on function evaluation endpoints as well as on
# normal GET endpoints.
response = self.app.get('/api/eval/person?'
'q={0}&callback=baz'.format(query))
assert response.status_code == 200
assert response.mimetype == 'application/javascript'
assert response.data.startswith(b'baz(')
assert response.data.endswith(b')')
# Add some more people so the result will be paginated.
for n in range(20):
self.session.add(self.Person(name=u'{0}'.format(n)))
self.session.commit()
response = self.app.get('/api/person?callback=baz')
assert response.status_code == 200
assert response.data.startswith(b'baz(')
assert response.data.endswith(b')')
# Get the dictionary representation of the JSON string inside the
# 'baz()' part of the JSONP response.
data = loads(response.data[4:-1])
assert 'meta' in data
assert 'data' in data
# The meta should include a JSON representation of the HTTP status.
assert 'status' in data['meta']
assert data['meta']['status'] == 200
# The metadata should include a JSON representation of the HTTP Link
# header information.
assert 'Link' in data['meta']
assert len(data['meta']['Link']) == 2
assert data['meta']['Link'][0]['rel'] == 'next'
assert data['meta']['Link'][1]['rel'] == 'last'
# TODO What other headers should the metadata include?
class TestAPI(TestSupport):
"""Unit tests for the :class:`flask_restless.views.API` class."""
def setUp(self):
"""Creates the database, the :class:`~flask.Flask` object, the
:class:`~flask_restless.manager.APIManager` for that application, and
creates the ReSTful API endpoints for the :class:`testapp.Person` and
:class:`testapp.Computer` models.
"""
# create the database
super(TestAPI, self).setUp()
# setup the URLs for the Person and Computer API
self.manager.create_api(self.Person,
methods=['GET', 'PATCH', 'POST', 'DELETE'])
self.manager.create_api(self.Computer,
methods=['GET', 'POST', 'PATCH'])
# setup the URLs for the Car manufacturer API
self.manager.create_api(self.CarManufacturer,
methods=['GET', 'PATCH', 'POST', 'DELETE'])
self.manager.create_api(self.CarModel,
methods=['GET', 'PATCH', 'POST', 'DELETE'])
self.manager.create_api(self.User, methods=['POST'],
primary_key='email')
# to facilitate searching
self.app.search = lambda url, q: self.app.get(url + '?q={0}'.format(q))
def test_post(self):
"""Test for creating a new instance of the database model using the
:http:method:`post` method.
"""
# Invalid JSON in request data should respond with error.
response = self.app.post('/api/person', data='Invalid JSON string')
assert response.status_code == 400
assert loads(response.data)['message'] == 'Unable to decode data'
# Now, let's test the validation stuff
# response = self.app.post('/api/person', data=dumps({'name': u'Test',
# 'age': 'oi'}))
# assert loads(response.data)['message'] == 'Validation error'
# assert loads(response.data)['error_list'].keys() == ['age']
# Test the integrity exception by violating the unique 'name' field
# of person
response = self.app.post('/api/person',
data=dumps({'name': u'George', 'age': 23}))
assert response.status_code == 201
# This errors as expected
response = self.app.post('/api/person',
data=dumps({'name': u'George', 'age': 23}))
assert response.status_code == 400
assert json.loads(response.data)['message'] == 'IntegrityError'
assert self.session.is_active, "Session is in `partial rollback` state"
# For issue #158 we make sure that the previous failure is rolled back
# so that we can add valid entries again
response = self.app.post('/api/person',
data=dumps({'name': u'Benjamin', 'age': 23}))
assert response.status_code == 201
response = self.app.post('/api/person',
data=dumps({'name': u'Lincoln', 'age': 23}))
assert response.status_code == 201
assert 'id' in loads(response.data)
response = self.app.get('/api/person/1')
assert response.status_code == 200
deep = {'computers': [], 'projects': []}
person = self.session.query(self.Person).filter_by(id=1).first()
inst = to_dict(person, deep)
assert loads(response.data) == inst
def test_post_m2m(self):
"""Test for creating a new instance of the database model that has a
many to many relation that uses an association object to allow extra
info to be stored on the helper table.
For more info, see issue #166.
"""
vim = self.Program(name=u'Vim')
emacs = self.Program(name=u'Emacs')
self.session.add_all([vim, emacs])
self.session.commit()
data = {
'vendor': u'Apple',
'name': u'iMac',
'programs': [
{
'program_id': 1,
'licensed': False
},
{
'program_id': 2,
'licensed': True
}
]
}
response = self.app.post('/api/computer', data=dumps(data))
assert response.status_code == 201
assert 'id' in loads(response.data)
response = self.app.get('/api/computer/1')
assert response.status_code == 200
def test_post_bad_parameter(self):
"""Tests that attempting to make a :http:method:`post` request with a
form parameter which does not exist on the specified model responds
with an error message.
"""
response = self.app.post('/api/person', data=dumps(dict(bogus=0)))
assert 400 == response.status_code
response = self.app.post('/api/person',
data=dumps(dict(is_minor=True)))
assert 400 == response.status_code
def test_post_nullable_date(self):
"""Tests the creation of a model with a nullable date field."""
self.manager.create_api(self.Star, methods=['GET', 'POST'])
data = dict(inception_time=None)
response = self.app.post('/api/star', data=dumps(data))
assert response.status_code == 201
response = self.app.get('/api/star/1')
assert response.status_code == 200
assert loads(response.data)['inception_time'] is None
def test_post_empty_date(self):
"""Tests that attempting to assign an empty date string to a date field
actually assigns a value of ``None``.
"""
self.manager.create_api(self.Star, methods=['GET', 'POST'])
data = dict(inception_time='')
response = self.app.post('/api/star', data=dumps(data))
assert response.status_code == 201
response = self.app.get('/api/star/1')
assert response.status_code == 200
assert loads(response.data)['inception_time'] is None
def test_post_date_functions(self):
"""Tests that ``'CURRENT_TIMESTAMP'`` gets converted into a datetime
object when making a request to set a date or time field.
"""
self.manager.create_api(self.Star, methods=['GET', 'POST'])
data = dict(inception_time='CURRENT_TIMESTAMP')
response = self.app.post('/api/star', data=dumps(data))
assert response.status_code == 201
response = self.app.get('/api/star/1')
assert response.status_code == 200
inception_time = loads(response.data)['inception_time']
assert inception_time is not None
inception_time = dateutil.parser.parse(inception_time)
diff = datetime.utcnow() - inception_time
assert diff.days == 0
assert (diff.seconds + diff.microseconds / 1000000.0) < 3600
def test_serialize_time(self):
"""Test for getting the JSON representation of a time field."""
self.manager.create_api(self.User, primary_key='id')
now = datetime.now().time()
user = self.User(id=1, email='foo', wakeup=now)
self.session.add(user)
self.session.commit()
response = self.app.get('/api/user/1')
assert response.status_code == 200
data = loads(response.data)
assert data['wakeup'] == now.isoformat()
def test_post_interval_functions(self):
oldJSONEncoder = self.flaskapp.json_encoder
class IntervalJSONEncoder(oldJSONEncoder):
def default(self, obj):
if isinstance(obj, timedelta):
return int(obj.days * 86400 + obj.seconds)
return oldJSONEncoder.default(self, obj)
self.flaskapp.json_encoder = IntervalJSONEncoder
self.manager.create_api(self.Satellite, methods=['GET', 'POST'])
data = dict(name="Callufrax_Minor", period=300)
response = self.app.post('/api/satellite', data=dumps(data))
assert response.status_code == 201
response = self.app.get('/api/satellite/Callufrax_Minor')
assert response.status_code == 200
assert loads(response.data)['period'] == 300
satellite = self.session.query(self.Satellite).first()
assert satellite.period == timedelta(0, 300)
def test_post_with_submodels(self):
"""Tests the creation of a model with a related field."""
data = {'name': u'John', 'age': 2041,
'computers': [{'name': u'lixeiro', 'vendor': u'Lemote'}]}
response = self.app.post('/api/person', data=dumps(data))
assert response.status_code == 201
assert 'id' in loads(response.data)
response = self.app.get('/api/person')
assert len(loads(response.data)['objects']) == 1
# Test with nested objects
data = {'name': 'Rodriguez', 'age': 70,
'computers': [{'name': 'iMac', 'vendor': 'Apple',
'programs': [{'program': {'name': 'iPhoto'}}]}]}
response = self.app.post('/api/person', data=dumps(data))
assert 201 == response.status_code
response = self.app.get('/api/computer/2/programs')
programs = loads(response.data)['objects']
assert programs[0]['program']['name'] == 'iPhoto'
def test_post_unicode_primary_key(self):
"""Test for creating a new instance of the database model using the
:http:method:`post` method with a Unicode primary key.
"""
response = self.app.post('/api/user', data=dumps({'id': 1,
'email': u'Юникод'}))
assert response.status_code == 201
def test_post_with_single_submodel(self):
data = {'vendor': u'Apple', 'name': u'iMac',
'owner': {'name': u'John', 'age': 2041}}
response = self.app.post('/api/computer', data=dumps(data))
assert response.status_code == 201
assert 'id' in loads(response.data)
# Test if owner was successfully created
response = self.app.get('/api/person')
assert len(loads(response.data)['objects']) == 1
def test_patch_update_relations(self):
"""Test for posting a new model and simultaneously adding related
instances *and* updating information on those instances.
For more information see issue #164.
"""
# First, create a new computer object with an empty `name` field and a
# new person with no related computers.
response = self.app.post('/api/computer', data=dumps({}))
assert 201 == response.status_code
response = self.app.post('/api/person', data=dumps({}))
assert 201 == response.status_code
# Second, patch the person by setting its list of related computer
# instances to include the previously created computer, *and*
# simultaneously update the `name` attribute of that computer.
data = dict(computers=[dict(id=1, name='foo')])
response = self.app.patch('/api/person/1', data=dumps(data))
assert 200 == response.status_code
# Check that the computer now has its `name` field set.
response = self.app.get('/api/computer/1')
assert 200 == response.status_code
assert 'foo' == loads(response.data)['name']
# Add a new computer by patching person
data = {'computers': [{'id': 1},
{'name': 'iMac', 'vendor': 'Apple',
'programs': [{'program': {'name': 'iPhoto'}}]}]}
response = self.app.patch('/api/person/1', data=dumps(data))
assert 200 == response.status_code
response = self.app.get('/api/computer/2/programs')
programs = loads(response.data)['objects']
assert programs[0]['program']['name'] == 'iPhoto'
# Add a program to the computer through the person
data = {'computers': [{'id': 1},
{'id': 2,
'programs': [{'program_id': 1},
{'program': {'name': 'iMovie'}}]}]}
response = self.app.patch('/api/person/1', data=dumps(data))
assert 200 == response.status_code
response = self.app.get('/api/computer/2/programs')
programs = loads(response.data)['objects']
assert programs[1]['program']['name'] == 'iMovie'
def test_patch_m2m(self):
"""Test for updating a model with a many to many relation that uses
an association object to allow extra data to be stored in the helper
table.
For more info, see issue #166
"""
response = self.app.post('/api/computer', data=dumps({}))
assert 201 == response.status_code
vim = self.Program(name=u'Vim')
emacs = self.Program(name=u'Emacs')
self.session.add_all([vim, emacs])
self.session.commit()
data = {
'programs': {
'add': [
{
'program_id': 1,
'licensed': False
}
]
}
}
response = self.app.patch('/api/computer/1', data=dumps(data))
computer = loads(response.data)
assert 200 == response.status_code
vim_relation = {
'computer_id': 1,
'program_id': 1,
'licensed': False
}
assert vim_relation in computer['programs']
data = {
'programs': {
'add': [
{
'program_id': 2,
'licensed': True
}
]
}
}
response = self.app.patch('/api/computer/1', data=dumps(data))
computer = loads(response.data)
assert 200 == response.status_code
emacs_relation = {
'computer_id': 1,
'program_id': 2,
'licensed': True
}
assert emacs_relation in computer['programs']
vim_relation = {
'computer_id': 1,
'program_id': 1,
'licensed': False
}
assert vim_relation in computer['programs']
def test_patch_remove_m2m(self):
"""Test for removing a relation on a model that uses an association
object to allow extra data to be stored in the helper table.
For more info, see issue #166
"""
response = self.app.post('/api/computer', data=dumps({}))
assert 201 == response.status_code
vim = self.Program(name=u'Vim')
emacs = self.Program(name=u'Emacs')
self.session.add_all([vim, emacs])
self.session.commit()
data = {
'programs': [
{
'program_id': 1,
'licensed': False
},
{
'program_id': 2,
'licensed': True
}
]
}
response = self.app.patch('/api/computer/1', data=dumps(data))
computer = loads(response.data)
assert 200 == response.status_code
vim_relation = {
'computer_id': 1,
'program_id': 1,
'licensed': False
}
emacs_relation = {
'computer_id': 1,
'program_id': 2,
'licensed': True
}
assert vim_relation in computer['programs']
assert emacs_relation in computer['programs']
data = {
'programs': {
'remove': [{'program_id': 1}]
}
}
response = self.app.patch('/api/computer/1', data=dumps(data))
computer = loads(response.data)
assert 200 == response.status_code
assert vim_relation not in computer['programs']
assert emacs_relation in computer['programs']
def test_patch_integrity_error(self):
self.session.add(self.Person(name=u"Waldorf", age=89))
self.session.add(self.Person(name=u"Statler", age=91))
self.session.commit()
# This errors as expected
response = self.app.patch('/api/person/1',
data=dumps({'name': u'Statler'}))
assert response.status_code == 400
assert json.loads(response.data)['message'] == 'IntegrityError'
assert self.session.is_active, "Session is in `partial rollback` state"
def test_delete(self):
"""Test for deleting an instance of the database using the
:http:method:`delete` method.
"""
# Creating the person who's gonna be deleted
response = self.app.post('/api/person',
data=dumps({'name': u'Lincoln', 'age': 23}))
assert response.status_code == 201
assert 'id' in loads(response.data)
# Making sure it has been created
deep = {'computers': [], 'projects': []}
person = self.session.query(self.Person).filter_by(id=1).first()
inst = to_dict(person, deep)
response = self.app.get('/api/person/1')
assert loads(response.data) == inst
# Deleting it
response = self.app.delete('/api/person/1')
assert response.status_code == 204
# Making sure it has been deleted
people = self.session.query(self.Person).filter_by(id=1)
assert people.count() == 0
def test_disallow_delete_many(self):
"""Tests for deleting many instances of a collection by using a search
query to select instances to delete.
"""
# Don't allow deleting many unless explicitly requested.
response = self.app.delete('/api/person')
assert response.status_code == 405
def test_delete_many(self):
"""Tests for deleting many instances of a collection by using a search
query to select instances to delete.
"""
# Recreate the API to allow delete many at /api2/person.
self.manager.create_api(self.Person, methods=['DELETE'],
allow_delete_many=True, url_prefix='/api2')
person1 = self.Person(name=u'foo')
person2 = self.Person(name=u'bar')
person3 = self.Person(name=u'baz')
self.session.add_all([person1, person2, person3])
self.session.commit()
search = {'filters': [{'name': 'name', 'val': 'ba%', 'op': 'like'}]}
response = self.app.delete('/api2/person?q={0}'.format(dumps(search)))
assert response.status_code == 200
data = loads(response.data)
assert data['num_deleted'] == 2
def test_delete_integrity_error(self):
"""Tests that an :exc:`IntegrityError` raised in a
:http:method:`delete` request is caught and returned to the client
safely.
"""
# TODO Fill me in.
pass
def test_delete_absent_instance(self):
"""Test that deleting an instance of the model which does not exist
fails.
This should give us a 404 when the object is not found.
"""
response = self.app.delete('/api/person/1')
assert response.status_code == 404
def test_disallow_patch_many(self):
"""Tests that disallowing "patch many" requests responds with a
:http:statuscode:`405`.
"""
response = self.app.patch('/api/person', data=dumps(dict(name='foo')))
assert response.status_code == 405
def test_put_same_as_patch(self):
"""Tests that :http:method:`put` requests are the same as
:http:method:`patch` requests.
"""
# recreate the api to allow patch many at /api/v2/person
self.manager.create_api(self.Person, methods=['GET', 'POST', 'PUT'],
allow_patch_many=True, url_prefix='/api/v2')
# Creating some people
self.app.post('/api/v2/person',
data=dumps({'name': u'Lincoln', 'age': 23}))
self.app.post('/api/v2/person',
data=dumps({'name': u'Lucy', 'age': 23}))
self.app.post('/api/v2/person',
data=dumps({'name': u'Mary', 'age': 25}))
# change a single entry
resp = self.app.put('/api/v2/person/1', data=dumps({'age': 24}))
assert resp.status_code == 200
resp = self.app.get('/api/v2/person/1')
assert resp.status_code == 200
assert loads(resp.data)['age'] == 24
# Changing the birth date field of the entire collection
day, month, year = 15, 9, 1986
birth_date = date(year, month, day).strftime('%d/%m/%Y') # iso8601
form = {'birth_date': birth_date}
self.app.put('/api/v2/person', data=dumps(form))
# Finally, testing if the change was made
response = self.app.get('/api/v2/person')
loaded = loads(response.data)['objects']
for i in loaded:
expected = '{0:4d}-{1:02d}-{2:02d}'.format(year, month, day)
assert i['birth_date'] == expected
def test_patch_empty(self):
"""Test for making a :http:method:`patch` request with no data."""
response = self.app.post('/api/person', data=dumps(dict(name='foo')))
assert response.status_code == 201
personid = loads(response.data)['id']
# here we really send no data
response = self.app.patch('/api/person/' + str(personid))
assert response.status_code == 400
# here we send the empty string (which is not valid JSON)
response = self.app.patch('/api/person/' + str(personid), data='')
assert response.status_code == 400
def test_patch_bad_parameter(self):
"""Tests that attempting to make a :http:method:`patch` request with a
form parameter which does not exist on the specified model responds
with an error message.
"""
response = self.app.post('/api/person', data=dumps({}))
assert 201 == response.status_code
response = self.app.patch('/api/person/1', data=dumps(dict(bogus=0)))
assert 400 == response.status_code
response = self.app.patch('/api/person/1',
data=dumps(dict(is_minor=True)))
assert 400 == response.status_code
def test_patch_many(self):
"""Test for updating a collection of instances of the model using the
:http:method:`patch` method.
"""
# recreate the api to allow patch many at /api/v2/person
self.manager.create_api(self.Person, methods=['GET', 'POST', 'PATCH'],
allow_patch_many=True, url_prefix='/api/v2')
# Creating some people
self.app.post('/api/v2/person',
data=dumps({'name': u'Lincoln', 'age': 23}))
self.app.post('/api/v2/person',
data=dumps({'name': u'Lucy', 'age': 23}))
self.app.post('/api/v2/person',
data=dumps({'name': u'Mary', 'age': 25}))
# Trying to pass invalid data to the update method
resp = self.app.patch('/api/v2/person', data='Hello there')
assert resp.status_code == 400
assert loads(resp.data)['message'] == 'Unable to decode data'
# Changing the birth date field of the entire collection
day, month, year = 15, 9, 1986
birth_date = date(year, month, day).strftime('%d/%m/%Y') # iso8601
form = {'birth_date': birth_date}
self.app.patch('/api/v2/person', data=dumps(form))
# Finally, testing if the change was made
response = self.app.get('/api/v2/person')
loaded = loads(response.data)['objects']
for i in loaded:
expected = '{0:4d}-{1:02d}-{2:02d}'.format(year, month, day)
assert i['birth_date'] == expected
def test_patch_many_with_filter(self):
"""Test for updating a collection of instances of the model using a
:http:method:patch request with filters.
"""
# recreate the api to allow patch many at /api/v2/person
self.manager.create_api(self.Person, methods=['GET', 'POST', 'PATCH'],
allow_patch_many=True, url_prefix='/api/v2')
# Creating some people
self.app.post('/api/v2/person',
data=dumps({'name': u'Lincoln', 'age': 23}))
self.app.post('/api/v2/person',
data=dumps({'name': u'Lucy', 'age': 23}))
self.app.post('/api/v2/person',
data=dumps({'name': u'Mary', 'age': 25}))
search = {'filters': [{'name': 'name', 'val': u'Lincoln',
'op': 'equals'}]}
# Changing the birth date field for objects where name field equals
# Lincoln
day, month, year = 15, 9, 1986
birth_date = date(year, month, day).strftime('%d/%m/%Y') # iso8601
form = {'birth_date': birth_date, 'q': search}
response = self.app.patch('/api/v2/person', data=dumps(form))
num_modified = loads(response.data)['num_modified']
assert num_modified == 1
def test_single_update(self):
"""Test for updating a single instance of the model using the
:http:method:`patch` method.
"""
resp = self.app.post('/api/person', data=dumps({'name': u'Lincoln',
'age': 10}))
assert resp.status_code == 201
assert 'id' in loads(resp.data)
# Trying to pass invalid data to the update method
resp = self.app.patch('/api/person/1', data='Invalid JSON string')
assert resp.status_code == 400
assert loads(resp.data)['message'] == 'Unable to decode data'
resp = self.app.patch('/api/person/1', data=dumps({'age': 24}))
assert resp.status_code == 200
resp = self.app.get('/api/person/1')
assert resp.status_code == 200
assert loads(resp.data)['age'] == 24
def test_patch_404(self):
"""Tests that making a :http:method:`patch` request to an instance
which does not exist results in a :http:statuscode:`404`.
"""
resp = self.app.patch('/api/person/1', data=dumps(dict(name='foo')))
assert resp.status_code == 404
def test_patch_with_single_submodel(self):
# Create a new object with a single submodel
data = {'vendor': u'Apple', 'name': u'iMac',
'owner': {'name': u'John', 'age': 2041}}
response = self.app.post('/api/computer', data=dumps(data))
assert response.status_code == 201
data = loads(response.data)
assert 1 == data['owner']['id']
assert u'John' == data['owner']['name']
assert 2041 == data['owner']['age']
# Update the submodel
data = {'id': 1, 'owner': {'id': 1, 'age': 29}}
response = self.app.patch('/api/computer/1', data=dumps(data))
assert response.status_code == 200
data = loads(response.data)
assert u'John' == data['owner']['name']
assert 29 == data['owner']['age']
def test_patch_set_submodel(self):
"""Test for assigning a list to a relation of a model using
:http:method:`patch`.
"""
# create the person
response = self.app.post('/api/person', data=dumps({}))
assert response.status_code == 201
# patch the person with some computers
data = {'computers': [{'name': u'lixeiro', 'vendor': u'Lemote'},
{'name': u'foo', 'vendor': u'bar'}]}
response = self.app.patch('/api/person/1', data=dumps(data))
assert 200 == response.status_code
data = loads(response.data)
assert 2 == len(data['computers'])
assert u'lixeiro' == data['computers'][0]['name']
assert u'Lemote' == data['computers'][0]['vendor']
assert u'foo' == data['computers'][1]['name']
assert u'bar' == data['computers'][1]['vendor']
# change one of the computers
data = {'computers': [{'id': data['computers'][0]['id']},
{'id': data['computers'][1]['id'],
'vendor': u'Apple'}]}
response = self.app.patch('/api/person/1', data=dumps(data))
assert 200 == response.status_code
data = loads(response.data)
assert 2 == len(data['computers'])
assert u'lixeiro' == data['computers'][0]['name']
assert u'Lemote' == data['computers'][0]['vendor']
assert u'foo' == data['computers'][1]['name']
assert u'Apple' == data['computers'][1]['vendor']
# patch the person with some new computers
data = {'computers': [{'name': u'hey', 'vendor': u'you'},
{'name': u'big', 'vendor': u'money'},
{'name': u'milk', 'vendor': u'chocolate'}]}
response = self.app.patch('/api/person/1', data=dumps(data))
assert 200 == response.status_code
data = loads(response.data)