-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathtest_sqlalchemy_data_layer.py
1591 lines (1292 loc) · 56.2 KB
/
test_sqlalchemy_data_layer.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
# -*- coding: utf-8 -*-
from six.moves.urllib.parse import urlencode, parse_qs
import pytest
from sqlalchemy import create_engine, Column, Integer, DateTime, String, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from flask import Blueprint, make_response, json
from marshmallow_jsonapi.flask import Schema, Relationship
from marshmallow_jsonapi import fields
from marshmallow import ValidationError
from flask_rest_jsonapi import Api, ResourceList, ResourceDetail, ResourceRelationship, JsonApiException
from flask_rest_jsonapi.pagination import add_pagination_links
from flask_rest_jsonapi.exceptions import RelationNotFound, InvalidSort, InvalidFilters, InvalidInclude, BadRequest
from flask_rest_jsonapi.querystring import QueryStringManager as QSManager
from flask_rest_jsonapi.data_layers.alchemy import SqlalchemyDataLayer
from flask_rest_jsonapi.data_layers.base import BaseDataLayer
from flask_rest_jsonapi.data_layers.filtering.alchemy import Node
import flask_rest_jsonapi.decorators
import flask_rest_jsonapi.resource
import flask_rest_jsonapi.schema
@pytest.fixture(scope="module")
def base():
yield declarative_base()
@pytest.fixture(scope="module")
def person_model(base):
class Person(base):
__tablename__ = 'person'
person_id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
birth_date = Column(DateTime)
computers = relationship("Computer", backref="person")
yield Person
@pytest.fixture(scope="module")
def computer_model(base):
class Computer(base):
__tablename__ = 'computer'
id = Column(Integer, primary_key=True)
serial = Column(String, nullable=False)
person_id = Column(Integer, ForeignKey('person.person_id'))
yield Computer
@pytest.fixture(scope="module")
def engine(person_model, computer_model):
engine = create_engine("sqlite:///:memory:")
person_model.metadata.create_all(engine)
computer_model.metadata.create_all(engine)
return engine
@pytest.fixture(scope="module")
def session(engine):
Session = sessionmaker(bind=engine)
return Session()
@pytest.fixture()
def person(session, person_model):
person_ = person_model(name='test')
session_ = session
session_.add(person_)
session_.commit()
yield person_
session_.delete(person_)
session_.commit()
@pytest.fixture()
def person_2(session, person_model):
person_ = person_model(name='test2')
session_ = session
session_.add(person_)
session_.commit()
yield person_
session_.delete(person_)
session_.commit()
@pytest.fixture()
def computer(session, computer_model):
computer_ = computer_model(serial='1')
session_ = session
session_.add(computer_)
session_.commit()
yield computer_
session_.delete(computer_)
session_.commit()
@pytest.fixture(scope="module")
def dummy_decorator():
def deco(f):
def wrapper_f(*args, **kwargs):
return f(*args, **kwargs)
return wrapper_f
yield deco
@pytest.fixture(scope="module")
def person_schema():
class PersonSchema(Schema):
class Meta:
type_ = 'person'
self_view = 'api.person_detail'
self_view_kwargs = {'person_id': '<id>'}
id = fields.Integer(as_string=True, dump_only=True, attribute='person_id')
name = fields.Str(required=True)
birth_date = fields.DateTime()
computers = Relationship(related_view='api.computer_list',
related_view_kwargs={'person_id': '<person_id>'},
schema='ComputerSchema',
type_='computer',
many=True)
yield PersonSchema
@pytest.fixture(scope="module")
def computer_schema():
class ComputerSchema(Schema):
class Meta:
type_ = 'computer'
self_view = 'api.computer_detail'
self_view_kwargs = {'id': '<id>'}
id = fields.Integer(as_string=True, dump_only=True)
serial = fields.Str(required=True)
owner = Relationship(attribute='person',
default=None,
missing=None,
related_view='api.person_detail',
related_view_kwargs={'person_id': '<person.person_id>'},
schema='PersonSchema',
id_field='person_id',
type_='person')
yield ComputerSchema
@pytest.fixture(scope="module")
def before_create_object():
def before_create_object_(self, data, view_kwargs):
pass
yield before_create_object_
@pytest.fixture(scope="module")
def before_update_object():
def before_update_object_(self, obj, data, view_kwargs):
pass
yield before_update_object_
@pytest.fixture(scope="module")
def before_delete_object():
def before_delete_object_(self, obj, view_kwargs):
pass
yield before_delete_object_
@pytest.fixture(scope="module")
def person_list(session, person_model, dummy_decorator, person_schema, before_create_object):
class PersonList(ResourceList):
schema = person_schema
data_layer = {'model': person_model,
'session': session,
'mzthods': {'before_create_object': before_create_object}}
get_decorators = [dummy_decorator]
post_decorators = [dummy_decorator]
get_schema_kwargs = dict()
post_schema_kwargs = dict()
yield PersonList
@pytest.fixture(scope="module")
def person_detail(session, person_model, dummy_decorator, person_schema, before_update_object, before_delete_object):
class PersonDetail(ResourceDetail):
schema = person_schema
data_layer = {'model': person_model,
'session': session,
'url_field': 'person_id',
'methods': {'before_update_object': before_update_object,
'before_delete_object': before_delete_object}}
get_decorators = [dummy_decorator]
patch_decorators = [dummy_decorator]
delete_decorators = [dummy_decorator]
get_schema_kwargs = dict()
patch_schema_kwargs = dict()
delete_schema_kwargs = dict()
yield PersonDetail
@pytest.fixture(scope="module")
def person_computers(session, person_model, dummy_decorator, person_schema):
class PersonComputersRelationship(ResourceRelationship):
schema = person_schema
data_layer = {'session': session,
'model': person_model,
'url_field': 'person_id'}
get_decorators = [dummy_decorator]
post_decorators = [dummy_decorator]
patch_decorators = [dummy_decorator]
delete_decorators = [dummy_decorator]
yield PersonComputersRelationship
@pytest.fixture(scope="module")
def person_list_raise_jsonapiexception():
class PersonList(ResourceList):
def get(self):
raise JsonApiException('', '')
yield PersonList
@pytest.fixture(scope="module")
def person_list_raise_exception():
class PersonList(ResourceList):
def get(self):
raise Exception()
yield PersonList
@pytest.fixture(scope="module")
def person_list_response():
class PersonList(ResourceList):
def get(self):
return make_response('')
yield PersonList
@pytest.fixture(scope="module")
def person_list_without_schema(session, person_model):
class PersonList(ResourceList):
data_layer = {'model': person_model,
'session': session}
def get(self):
return make_response('')
yield PersonList
@pytest.fixture(scope="module")
def query():
def query_(self, view_kwargs):
if view_kwargs.get('person_id') is not None:
return self.session.query(computer_model).join(person_model).filter_by(person_id=view_kwargs['person_id'])
return self.session.query(computer_model)
yield query_
@pytest.fixture(scope="module")
def computer_list(session, computer_model, computer_schema, query):
class ComputerList(ResourceList):
schema = computer_schema
data_layer = {'model': computer_model,
'session': session,
'methods': {'query': query}}
yield ComputerList
@pytest.fixture(scope="module")
def computer_detail(session, computer_model, dummy_decorator, computer_schema):
class ComputerDetail(ResourceDetail):
schema = computer_schema
data_layer = {'model': computer_model,
'session': session}
methods = ['GET', 'PATCH']
yield ComputerDetail
@pytest.fixture(scope="module")
def computer_owner(session, computer_model, dummy_decorator, computer_schema):
class ComputerOwnerRelationship(ResourceRelationship):
schema = computer_schema
data_layer = {'session': session,
'model': computer_model}
yield ComputerOwnerRelationship
@pytest.fixture(scope="module")
def api_blueprint(client):
bp = Blueprint('api', __name__)
yield bp
@pytest.fixture(scope="module")
def register_routes(client, app, api_blueprint, person_list, person_detail, person_computers,
person_list_raise_jsonapiexception, person_list_raise_exception, person_list_response,
person_list_without_schema, computer_list, computer_detail, computer_owner):
api = Api(blueprint=api_blueprint)
api.route(person_list, 'person_list', '/persons')
api.route(person_detail, 'person_detail', '/persons/<int:person_id>')
api.route(person_computers, 'person_computers', '/persons/<int:person_id>/relationships/computers')
api.route(person_computers, 'person_computers_error', '/persons/<int:person_id>/relationships/computer')
api.route(person_list_raise_jsonapiexception, 'person_list_jsonapiexception', '/persons_jsonapiexception')
api.route(person_list_raise_exception, 'person_list_exception', '/persons_exception')
api.route(person_list_response, 'person_list_response', '/persons_response')
api.route(person_list_without_schema, 'person_list_without_schema', '/persons_without_schema')
api.route(computer_list, 'computer_list', '/computers', '/persons/<int:person_id>/computers')
api.route(computer_list, 'computer_detail', '/computers/<int:id>')
api.route(computer_owner, 'computer_owner', '/computers/<int:id>/relationships/owner')
api.init_app(app)
@pytest.fixture(scope="module")
def get_object_mock():
class get_object(object):
foo = type('foo', (object,), {
'property': type('prop', (object,), {
'mapper': type('map', (object,), {
'class_': 'test'
})()
})()
})()
def __init__(self, kwargs):
pass
return get_object
def test_add_pagination_links(app):
with app.app_context():
qs = {'page[number]': '2', 'page[size]': '10'}
qsm = QSManager(qs, None)
pagination_dict = dict()
add_pagination_links(pagination_dict, 43, qsm, str())
last_page_dict = parse_qs(pagination_dict['links']['last'][1:])
assert len(last_page_dict['page[number]']) == 1
assert last_page_dict['page[number]'][0] == '5'
def test_Node(person_model, person_schema, monkeypatch):
from copy import deepcopy
filt = {
'val': '0000',
'field': True,
'not': dict(),
'name': 'name',
'op': 'eq',
'strip': lambda: 's'
}
filt['not'] = deepcopy(filt)
del filt['not']['not']
n = Node(person_model,
filt,
None,
person_schema)
with pytest.raises(TypeError):
# print(n.val is None and n.field is None)
# # n.column
n.resolve()
with pytest.raises(AttributeError):
n.model = None
n.column
with pytest.raises(InvalidFilters):
n.model = person_model
n.filter_['op'] = ''
n.operator
with pytest.raises(InvalidFilters):
n.related_model
with pytest.raises(InvalidFilters):
n.related_schema
def test_check_method_requirements(monkeypatch):
self = type('self', (object,), dict())
request = type('request', (object,), dict(method='GET'))
monkeypatch.setattr(flask_rest_jsonapi.decorators, 'request', request)
with pytest.raises(Exception):
flask_rest_jsonapi.decorators.check_method_requirements(lambda: 1)(self())
def test_json_api_exception():
JsonApiException(None, None, title='test', status='test')
def test_query_string_manager(person_schema):
query_string = {'page[slumber]': '3'}
qsm = QSManager(query_string, person_schema)
with pytest.raises(BadRequest):
qsm.pagination
#qsm.qs['sort'] = 'computers'
#with pytest.raises(InvalidSort):
#qsm.sorting
def test_resource(app, person_model, person_schema, session, monkeypatch):
def schema_load_mock(*args):
raise ValidationError(dict(errors=[dict(status=None, title=None)]))
with app.app_context():
query_string = {'page[slumber]': '3'}
app = type('app', (object,), dict(config=dict(DEBUG=True)))
headers = {'Content-Type': 'application/vnd.api+json'}
request = type('request', (object,), dict(method='POST',
headers=headers,
get_json=dict,
args=query_string))
dl = SqlalchemyDataLayer(dict(session=session, model=person_model))
rl = ResourceList()
rd = ResourceDetail()
rl._data_layer = dl
rl.schema = person_schema
rd._data_layer = dl
rd.schema = person_schema
monkeypatch.setattr(flask_rest_jsonapi.resource, 'request', request)
monkeypatch.setattr(flask_rest_jsonapi.resource, 'current_app', app)
monkeypatch.setattr(flask_rest_jsonapi.decorators, 'request', request)
monkeypatch.setattr(rl.schema, 'load', schema_load_mock)
r = super(flask_rest_jsonapi.resource.Resource, ResourceList)\
.__new__(ResourceList)
with pytest.raises(Exception):
r.dispatch_request()
rl.post()
rd.patch()
def test_compute_schema(person_schema):
query_string = {'page[number]': '3', 'fields[person]': list()}
qsm = QSManager(query_string, person_schema)
with pytest.raises(InvalidInclude):
flask_rest_jsonapi.schema.compute_schema(person_schema, dict(), qsm, ['id'])
flask_rest_jsonapi.schema.compute_schema(person_schema, dict(only=list()), qsm, list())
# test good cases
def test_get_list(client, register_routes, person, person_2):
with client:
querystring = urlencode({'page[number]': 1,
'page[size]': 1,
'fields[person]': 'name,birth_date',
'sort': '-name',
'include': 'computers.owner',
'filter': json.dumps(
[
{
'and': [
{
'name': 'computers',
'op': 'any',
'val': {
'name': 'serial',
'op': 'eq',
'val': '0000'
}
},
{
'or': [
{
'name': 'name',
'op': 'like',
'val': '%test%'
},
{
'name': 'name',
'op': 'like',
'val': '%test2%'
}
]
}
]
}
])})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 200
def test_get_list_sort_relationship(client, register_routes, person, person_2):
with client:
querystring = urlencode({'page[number]': 1,
'page[size]': 1,
'fields[person]': 'name,birth_date',
'sort': '-computers',
'include': 'computers.owner',
'filter': json.dumps(
[
{
'and': [
{
'name': 'computers',
'op': 'any',
'val': {
'name': 'serial',
'op': 'eq',
'val': '0000'
}
},
{
'or': [
{
'name': 'name',
'op': 'like',
'val': '%test%'
},
{
'name': 'name',
'op': 'like',
'val': '%test2%'
}
]
}
]
}
])})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 200
def test_get_list_disable_pagination(client, register_routes):
with client:
querystring = urlencode({'page[size]': 0})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 200
def test_head_list(client, register_routes):
with client:
response = client.head('/persons', content_type='application/vnd.api+json')
assert response.status_code == 200
def test_post_list(client, register_routes, computer):
payload = {
'data': {
'type': 'person',
'attributes': {
'name': 'test'
},
'relationships': {
'computers': {
'data': [
{
'type': 'computer',
'id': str(computer.id)
}
]
}
}
}
}
with client:
response = client.post('/persons', data=json.dumps(payload), content_type='application/vnd.api+json')
assert response.status_code == 201
def test_post_list_single(client, register_routes, person):
payload = {
'data': {
'type': 'computer',
'attributes': {
'serial': '1'
},
'relationships': {
'owner': {
'data': {
'type': 'person',
'id': str(person.person_id)
}
}
}
}
}
with client:
response = client.post('/computers', data=json.dumps(payload), content_type='application/vnd.api+json')
assert response.status_code == 201
def test_get_detail(client, register_routes, person):
with client:
response = client.get('/persons/' + str(person.person_id), content_type='application/vnd.api+json')
assert response.status_code == 200
def test_patch_detail(client, register_routes, computer, person):
payload = {
'data': {
'id': str(person.person_id),
'type': 'person',
'attributes': {
'name': 'test2'
},
'relationships': {
'computers': {
'data': [
{
'type': 'computer',
'id': str(computer.id)
}
]
}
}
}
}
with client:
response = client.patch('/persons/' + str(person.person_id),
data=json.dumps(payload),
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_delete_detail(client, register_routes, person):
with client:
response = client.delete('/persons/' + str(person.person_id), content_type='application/vnd.api+json')
assert response.status_code == 200
def test_get_relationship(session, client, register_routes, computer, person):
session_ = session
person.computers = [computer]
session_.commit()
with client:
response = client.get('/persons/' + str(person.person_id) + '/relationships/computers?include=computers',
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_get_relationship_empty(client, register_routes, person):
with client:
response = client.get('/persons/' + str(person.person_id) + '/relationships/computers?include=computers',
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_get_relationship_single(session, client, register_routes, computer, person):
session_ = session
computer.person = person
session_.commit()
with client:
response = client.get('/computers/' + str(computer.id) + '/relationships/owner',
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_get_relationship_single_empty(session, client, register_routes, computer):
with client:
response = client.get('/computers/' + str(computer.id) + '/relationships/owner',
content_type='application/vnd.api+json')
response_json = json.loads(response.get_data())
assert None is response_json['data']
assert response.status_code == 200
def test_issue_49(session, client, register_routes, person, person_2):
with client:
for p in [person, person_2]:
response = client.get('/persons/' + str(p.person_id) + '/relationships/computers?include=computers',
content_type='application/vnd.api+json')
assert response.status_code == 200
assert (json.loads(response.get_data()))['links']['related'] == '/persons/' + str(p.person_id) + '/computers'
def test_post_relationship(client, register_routes, computer, person):
payload = {
'data': [
{
'type': 'computer',
'id': str(computer.id)
}
]
}
with client:
response = client.post('/persons/' + str(person.person_id) + '/relationships/computers?include=computers',
data=json.dumps(payload),
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_post_relationship_not_list(client, register_routes, computer, person):
payload = {
'data': {
'type': 'person',
'id': str(person.person_id)
}
}
with client:
response = client.post('/computers/' + str(computer.id) + '/relationships/owner',
data=json.dumps(payload),
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_patch_relationship(client, register_routes, computer, person):
payload = {
'data': [
{
'type': 'computer',
'id': str(computer.id)
}
]
}
with client:
response = client.patch('/persons/' + str(person.person_id) + '/relationships/computers?include=computers',
data=json.dumps(payload),
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_patch_relationship_single(client, register_routes, computer, person):
payload = {
'data': {
'type': 'person',
'id': str(person.person_id)
}
}
with client:
response = client.patch('/computers/' + str(computer.id) + '/relationships/owner',
data=json.dumps(payload),
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_delete_relationship(session, client, register_routes, computer, person):
session_ = session
person.computers = [computer]
session_.commit()
payload = {
'data': [
{
'type': 'computer',
'id': str(computer.id)
}
]
}
with client:
response = client.delete('/persons/' + str(person.person_id) + '/relationships/computers?include=computers',
data=json.dumps(payload),
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_delete_relationship_single(session, client, register_routes, computer, person):
session_ = session
computer.person = person
session_.commit()
payload = {
'data': {
'type': 'person',
'id': str(person.person_id)
}
}
with client:
response = client.delete('/computers/' + str(computer.id) + '/relationships/owner',
data=json.dumps(payload),
content_type='application/vnd.api+json')
assert response.status_code == 200
def test_get_list_response(client, register_routes):
with client:
response = client.get('/persons_response', content_type='application/vnd.api+json')
assert response.status_code == 200
# test various Accept headers
def test_single_accept_header(client, register_routes):
with client:
response = client.get('/persons', content_type='application/vnd.api+json', headers={'Accept': 'application/vnd.api+json'})
assert response.status_code == 200
def test_multiple_accept_header(client, register_routes):
with client:
response = client.get('/persons', content_type='application/vnd.api+json', headers={'Accept': '*/*, application/vnd.api+json, application/vnd.api+json;q=0.9'})
assert response.status_code == 200
def test_wrong_accept_header(client, register_routes):
with client:
response = client.get('/persons', content_type='application/vnd.api+json', headers={'Accept': 'application/vnd.api+json;q=0.7, application/vnd.api+json;q=0.9'})
assert response.status_code == 406
# test Content-Type error
def test_wrong_content_type(client, register_routes):
with client:
response = client.post('/persons', headers={'Content-Type': 'application/vnd.api+json;q=0.8'})
assert response.status_code == 415
@pytest.fixture(scope="module")
def wrong_data_layer():
class WrongDataLayer(object):
pass
yield WrongDataLayer
def test_wrong_data_layer_inheritence(wrong_data_layer):
with pytest.raises(Exception):
class PersonDetail(ResourceDetail):
data_layer = {'class': wrong_data_layer}
PersonDetail()
def test_wrong_data_layer_kwargs_type():
with pytest.raises(Exception):
class PersonDetail(ResourceDetail):
data_layer = list()
PersonDetail()
def test_get_list_jsonapiexception(client, register_routes):
with client:
response = client.get('/persons_jsonapiexception', content_type='application/vnd.api+json')
assert response.status_code == 500
def test_get_list_exception(client, register_routes):
with client:
response = client.get('/persons_exception', content_type='application/vnd.api+json')
assert response.status_code == 500
def test_get_list_without_schema(client, register_routes):
with client:
response = client.post('/persons_without_schema', content_type='application/vnd.api+json')
assert response.status_code == 500
def test_get_list_bad_request(client, register_routes):
with client:
querystring = urlencode({'page[number': 3})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_list_invalid_fields(client, register_routes):
with client:
querystring = urlencode({'fields[person]': 'error'})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_list_invalid_include(client, register_routes):
with client:
querystring = urlencode({'include': 'error'})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_list_invalid_filters_parsing(client, register_routes):
with client:
querystring = urlencode({'filter': 'error'})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_list_invalid_page(client, register_routes):
with client:
querystring = urlencode({'page[number]': 'error'})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_list_invalid_sort(client, register_routes):
with client:
querystring = urlencode({'sort': 'error'})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_detail_object_not_found(client, register_routes):
with client:
response = client.get('/persons/3', content_type='application/vnd.api+json')
assert response.status_code == 200
def test_post_relationship_related_object_not_found(client, register_routes, person):
payload = {
'data': [
{
'type': 'computer',
'id': '2'
}
]
}
with client:
response = client.post('/persons/' + str(person.person_id) + '/relationships/computers',
data=json.dumps(payload),
content_type='application/vnd.api+json')
assert response.status_code == 404
def test_get_relationship_relationship_field_not_found(client, register_routes, person):
with client:
response = client.get('/persons/' + str(person.person_id) + '/relationships/computer',
content_type='application/vnd.api+json')
assert response.status_code == 500
def test_get_list_invalid_filters_val(client, register_routes):
with client:
querystring = urlencode({'filter': json.dumps([{'name': 'computers', 'op': 'any'}])})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_list_name(client, register_routes):
with client:
querystring = urlencode({'filter': json.dumps([{'name': 'computers__serial', 'op': 'any', 'val': '1'}])})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 200
def test_get_list_no_name(client, register_routes):
with client:
querystring = urlencode({'filter': json.dumps([{'op': 'any', 'val': '1'}])})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_list_no_op(client, register_routes):
with client:
querystring = urlencode({'filter': json.dumps([{'name': 'computers__serial', 'val': '1'}])})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_list_attr_error(client, register_routes):
with client:
querystring = urlencode({'filter': json.dumps([{'name': 'error', 'op': 'eq', 'val': '1'}])})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_get_list_field_error(client, register_routes):
with client:
querystring = urlencode({'filter': json.dumps([{'name': 'name', 'op': 'eq', 'field': 'error'}])})
response = client.get('/persons' + '?' + querystring, content_type='application/vnd.api+json')
assert response.status_code == 400
def test_sqlalchemy_data_layer_without_session(person_model, person_list):
with pytest.raises(Exception):
SqlalchemyDataLayer(dict(model=person_model, resource=person_list))
def test_sqlalchemy_data_layer_without_model(session, person_list):
with pytest.raises(Exception):
SqlalchemyDataLayer(dict(session=session, resource=person_list))
def test_sqlalchemy_data_layer_create_object_error(session, person_model, person_list):
with pytest.raises(JsonApiException):
dl = SqlalchemyDataLayer(dict(session=session, model=person_model, resource=person_list))
dl.create_object(dict(), dict())
def test_sqlalchemy_data_layer_get_object_error(session, person_model):
with pytest.raises(Exception):
dl = SqlalchemyDataLayer(dict(session=session, model=person_model, id_field='error'))
dl.get_object(dict())
def test_sqlalchemy_data_layer_update_object_error(session, person_model, person_list, monkeypatch):
def commit_mock():
raise JsonApiException()
with pytest.raises(JsonApiException):
dl = SqlalchemyDataLayer(dict(session=session, model=person_model, resource=person_list))
monkeypatch.setattr(dl.session, 'commit', commit_mock)
dl.update_object(dict(), dict(), dict())
def test_sqlalchemy_data_layer_delete_object_error(session, person_model, person_list, monkeypatch):
def commit_mock():
raise JsonApiException()
def delete_mock(obj):
pass
with pytest.raises(JsonApiException):
dl = SqlalchemyDataLayer(dict(session=session, model=person_model, resource=person_list))
monkeypatch.setattr(dl.session, 'commit', commit_mock)
monkeypatch.setattr(dl.session, 'delete', delete_mock)
dl.delete_object(dict(), dict())
def test_sqlalchemy_data_layer_create_relationship_field_not_found(session, person_model):
with pytest.raises(Exception):
dl = SqlalchemyDataLayer(dict(session=session, model=person_model))