-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtest_sqlalchemy_data_layer.py
More file actions
2111 lines (1652 loc) · 72 KB
/
test_sqlalchemy_data_layer.py
File metadata and controls
2111 lines (1652 loc) · 72 KB
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
from 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, request
from marshmallow_jsonapi.flask import Schema, Relationship
from marshmallow import Schema as MarshmallowSchema
from marshmallow_jsonapi import fields
from marshmallow import ValidationError
from werkzeug.exceptions import Unauthorized
from flask_combo_jsonapi import Api, ResourceList, ResourceDetail, ResourceRelationship, JsonApiException
from flask_combo_jsonapi.pagination import add_pagination_links
from flask_combo_jsonapi.exceptions import RelationNotFound, InvalidSort, InvalidFilters, InvalidInclude, BadRequest
from flask_combo_jsonapi.querystring import QueryStringManager as QSManager
from flask_combo_jsonapi.data_layers.alchemy import SqlalchemyDataLayer
from flask_combo_jsonapi.data_layers.base import BaseDataLayer
from flask_combo_jsonapi.data_layers.filtering.alchemy import Node
from flask_combo_jsonapi.utils import SPLIT_REL
import flask_combo_jsonapi.decorators
import flask_combo_jsonapi.resource
import flask_combo_jsonapi.schema
@pytest.fixture(scope="module")
def base():
yield declarative_base()
@pytest.fixture(scope="module")
def person_tag_model(base):
class Person_Tag(base):
__tablename__ = "person_tag"
id = Column(Integer, ForeignKey("person.person_id"), primary_key=True, index=True)
key = Column(String, primary_key=True)
value = Column(String, primary_key=True)
yield Person_Tag
@pytest.fixture(scope="module")
def person_single_tag_model(base):
class Person_Single_Tag(base):
__tablename__ = "person_single_tag"
id = Column(Integer, ForeignKey("person.person_id"), primary_key=True, index=True)
key = Column(String)
value = Column(String)
yield Person_Single_Tag
@pytest.fixture(scope="module")
def string_json_attribute_person_model(base):
"""
This approach to faking JSON support for testing with sqlite is borrowed from:
https://avacariu.me/articles/2016/compiling-json-as-text-for-sqlite-with-sqlalchemy
"""
import sqlalchemy.types as types
import simplejson as json
class StringyJSON(types.TypeDecorator):
"""Stores and retrieves JSON as TEXT."""
impl = types.TEXT
def process_bind_param(self, value, dialect):
if value is not None:
value = json.dumps(value)
return value
def process_result_value(self, value, dialect):
if value is not None:
value = json.loads(value)
return value
# TypeEngine.with_variant says "use StringyJSON instead when
# connecting to 'sqlite'"
try:
MagicJSON = types.JSON().with_variant(StringyJSON, "sqlite")
except AttributeError:
from sqlalchemy.dialects.postgresql import JSON
MagicJSON = JSON().with_variant(StringyJSON, "sqlite")
class StringJsonAttributePerson(base):
__tablename__ = "string_json_attribute_person"
person_id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
birth_date = Column(DateTime)
# This model uses a String type for "json_tags" to avoid dependency on a nonstandard SQL type in testing, \
# while still demonstrating support
address = Column(MagicJSON)
tags = Column(MagicJSON)
yield StringJsonAttributePerson
@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")
tags = relationship("Person_Tag", cascade="save-update, merge, delete, delete-orphan")
single_tag = relationship(
"Person_Single_Tag", uselist=False, cascade="save-update, merge, delete, delete-orphan"
)
computers_owned = relationship("Computer")
address = relationship("Address", backref="person", uselist=False)
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 address_model(base):
class Address(base):
__tablename__ = "address"
id = Column(Integer, primary_key=True)
street = Column(String)
city = Column(String)
state = Column(String)
zip = Column(String)
person_id = Column(Integer, ForeignKey("person.person_id"))
yield Address
@pytest.fixture(scope="module")
def engine(
person_tag_model, person_single_tag_model, person_model,
computer_model, string_json_attribute_person_model,
address_model
):
engine = create_engine("sqlite:///:memory:")
person_tag_model.metadata.create_all(engine)
person_single_tag_model.metadata.create_all(engine)
person_model.metadata.create_all(engine)
computer_model.metadata.create_all(engine)
string_json_attribute_person_model.metadata.create_all(engine)
address_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 persons(session, person_model):
persons = []
session_ = session
for i in range(100):
person_ = person_model(name=f"test{i}")
session_.add(person_)
persons.append(person_)
session_.commit()
yield persons
for person_ in persons:
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()
def computer_2(session, computer_model):
computer_ = computer_model(serial="2")
session_ = session
session_.add(computer_)
session_.commit()
yield computer_
session_.delete(computer_)
session_.commit()
@pytest.fixture()
def address(session, address_model):
address_ = address_model(state='NYC')
session_ = session
session_.add(address_)
session_.commit()
yield address_
session_.delete(address_)
session_.commit()
@pytest.fixture(scope="module")
def custom_auth_decorator():
def deco(f):
def wrapper_f(*args, **kwargs):
auth = request.headers.get("auth", None)
if auth == '123':
raise Unauthorized()
return f(*args, **kwargs)
return wrapper_f
yield deco
@pytest.fixture(scope="module")
def custom_auth_decorator_2():
def deco(f):
def wrapper_f(*args, **kwargs):
auth = request.headers.get("auth", None)
if auth == '1234':
raise Unauthorized()
return f(*args, **kwargs)
return wrapper_f
yield deco
@pytest.fixture(scope="module")
def person_tag_schema():
class PersonTagSchema(MarshmallowSchema):
class Meta:
type_ = "person_tag"
id = fields.Str(dump_only=True, load_only=True)
key = fields.Str()
value = fields.Str()
yield PersonTagSchema
@pytest.fixture(scope="module")
def person_single_tag_schema():
class PersonSingleTagSchema(MarshmallowSchema):
class Meta:
type_ = "person_single_tag"
id = fields.Str(dump_only=True, load_only=True)
key = fields.Str()
value = fields.Str()
yield PersonSingleTagSchema
@pytest.fixture(scope="module")
def address_schema():
class AddressSchema(MarshmallowSchema):
street = fields.String(required=True)
city = fields.String(required=True)
state = fields.String(load_default="NC")
zip = fields.String(required=True)
yield AddressSchema
@pytest.fixture(scope="module")
def person_address_schema():
class PersonAddressSchema(Schema):
class Meta:
type_ = "address"
id = fields.Str(dump_only=True)
street = fields.String()
city = fields.String()
state = fields.String()
zip = fields.String()
person = Relationship(
related_view="api.person_detail",
related_view_kwargs={"person_id": "<person.person_id>"},
schema="PersonSchema",
id_field="person_id",
type_="person",
)
yield PersonAddressSchema
@pytest.fixture(scope="module")
def string_json_attribute_person_schema(address_schema):
class StringJsonAttributePersonSchema(Schema):
class Meta:
type_ = "string_json_attribute_person"
self_view = "api.string_json_attribute_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()
address = fields.Nested(address_schema, many=False)
tags = fields.List(fields.Dict())
yield StringJsonAttributePersonSchema
@pytest.fixture(scope="module")
def person_schema(person_tag_schema, person_single_tag_schema, person_address_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, 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,
)
tags = fields.Nested(person_tag_schema, many=True)
single_tag = fields.Nested(person_single_tag_schema)
computers_owned = Relationship(
related_view="api.computer_list",
related_view_kwargs={"person_id": "<person_id>"},
schema="ComputerSchema",
type_="computer",
many=True,
)
address = Relationship(
schema="PersonAddressSchema",
type_="address",
)
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",
dump_default=None,
load_default=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, person_schema, before_create_object):
class PersonList(ResourceList):
schema = person_schema
data_layer = {
"model": person_model,
"session": session,
"methods": {"before_create_object": before_create_object},
}
get_schema_kwargs = dict()
post_schema_kwargs = dict()
yield PersonList
@pytest.fixture(scope="module")
def custom_query_string_manager():
class QS(QSManager):
def _simple_filters(self, dict_):
return [{"name": key, "op": "in" if isinstance(value, list) else "eq", "val": value}
for (key, value) in dict_.items()]
yield QS
@pytest.fixture(scope="module")
def person_list_custom_qs_manager(session, person_model, person_schema, custom_query_string_manager):
class PersonList(ResourceList):
schema = person_schema
data_layer = {
"model": person_model,
"session": session,
}
get_schema_kwargs = dict()
qs_manager_class = custom_query_string_manager
yield PersonList
@pytest.fixture(scope="module")
def person_list_2(session, person_model, person_schema):
class PersonList(ResourceList):
schema = person_schema
data_layer = {
"model": person_model,
"session": session,
}
get_schema_kwargs = dict()
yield PersonList
@pytest.fixture(scope="module")
def person_detail(session, person_model, person_schema, before_update_object, before_delete_object,
custom_auth_decorator_2):
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_schema_kwargs = dict()
patch_schema_kwargs = dict()
delete_schema_kwargs = dict()
decorators = (custom_auth_decorator_2,)
yield PersonDetail
@pytest.fixture(scope="module")
def person_computers(session, person_model, person_schema):
class PersonComputersRelationship(ResourceRelationship):
schema = person_schema
data_layer = {"session": session, "model": person_model, "url_field": "person_id"}
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 fixed_count_for_collection_count():
return 42
@pytest.fixture(scope="module")
def computer_list_resource_with_disable_collection_count(
session, computer_model, computer_schema, fixed_count_for_collection_count
):
class ComputerList(ResourceList):
disable_collection_count = True, fixed_count_for_collection_count
schema = computer_schema
data_layer = {"model": computer_model, "session": session}
yield ComputerList
@pytest.fixture(scope="module")
def computer_detail(session, computer_model, 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, computer_schema):
class ComputerOwnerRelationship(ResourceRelationship):
schema = computer_schema
data_layer = {"session": session, "model": computer_model}
yield ComputerOwnerRelationship
@pytest.fixture(scope="module")
def string_json_attribute_person_detail(
session, string_json_attribute_person_model, string_json_attribute_person_schema
):
class StringJsonAttributePersonDetail(ResourceDetail):
schema = string_json_attribute_person_schema
data_layer = {"session": session, "model": string_json_attribute_person_model}
yield StringJsonAttributePersonDetail
@pytest.fixture(scope="module")
def string_json_attribute_person_list(session, string_json_attribute_person_model, string_json_attribute_person_schema):
class StringJsonAttributePersonList(ResourceList):
schema = string_json_attribute_person_schema
data_layer = {"session": session, "model": string_json_attribute_person_model}
yield StringJsonAttributePersonList
@pytest.fixture()
def api_blueprint(client):
bp = Blueprint("api", __name__)
yield bp
@pytest.fixture()
def api_blueprint_custom(client):
bp = Blueprint("api_custom", __name__)
yield bp
@pytest.fixture()
def app_disabled_pagination(app):
app.config['PAGE_SIZE'] = 0
yield app
app.config['PAGE_SIZE'] = 30
@pytest.fixture()
def register_routes_custom_qs(
client,
app,
api_blueprint_custom,
register_routes,
custom_query_string_manager,
person_list_2,
):
api = Api(blueprint=api_blueprint_custom, qs_manager_class=custom_query_string_manager)
api.route(person_list_2, "person_list_qs", "/qs/persons")
api.init_app(app)
@pytest.fixture()
def register_routes(
client,
app,
api_blueprint,
custom_auth_decorator,
person_list,
person_detail,
person_computers,
person_list_custom_qs_manager,
person_list_raise_jsonapiexception,
person_list_raise_exception,
person_list_response,
person_list_without_schema,
computer_list,
computer_detail,
computer_list_resource_with_disable_collection_count,
computer_owner,
string_json_attribute_person_detail,
string_json_attribute_person_list,
):
api = Api(blueprint=api_blueprint, decorators=(custom_auth_decorator,))
api.route(person_list, "person_list", "/persons")
api.route(person_list_custom_qs_manager, "person_list_custom_qs_manager", "/persons_qs")
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_owned", "/persons/<int:person_id>/relationships/computers-owned")
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_resource_with_disable_collection_count,
"computer_list_with_disabled_count",
"/computers_with_disabled_count",
"/persons/<int:person_id>/computers_with_disabled_count",
)
api.route(computer_list, "computer_list", "/computers", "/persons/<int:person_id>/computers")
api.route(computer_detail, "computer_detail", "/computers/<int:id>")
api.route(computer_owner, "computer_owner", "/computers/<int:id>/relationships/owner")
api.route(string_json_attribute_person_list, "string_json_attribute_person_list", "/string_json_attribute_persons")
api.route(
string_json_attribute_person_detail,
"string_json_attribute_person_detail",
"/string_json_attribute_persons/<int:person_id>",
)
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_combo_jsonapi.decorators, "request", request)
with pytest.raises(Exception):
flask_combo_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, json={}, 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_combo_jsonapi.resource, "request", request)
monkeypatch.setattr(flask_combo_jsonapi.decorators, "current_app", app)
monkeypatch.setattr(flask_combo_jsonapi.decorators, "request", request)
monkeypatch.setattr(rl.schema, "load", schema_load_mock)
r = super(flask_combo_jsonapi.resource.Resource, ResourceList).__new__(ResourceList)
with pytest.raises(Exception):
r.dispatch_request()
rl.post()
with pytest.raises(Exception):
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_combo_jsonapi.schema.compute_schema(person_schema, dict(), qsm, ["id"])
flask_combo_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_default_pagination(client, register_routes, persons):
with client:
response = client.get("/persons", content_type="application/vnd.api+json")
assert response.status_code == 200
assert len(response.json['data']) == 30
assert response.json['meta']['count'] == len(persons)
assert 'last' in response.json['links']
assert 'first' in response.json['links']
assert 'next' in response.json['links']
def test_get_list_default_pagination_default_disabled(client, app_disabled_pagination, register_routes, persons):
with client:
response = client.get("/persons", content_type="application/vnd.api+json")
assert response.status_code == 200
assert len(response.json['data']) == len(persons)
assert 'last' not in response.json['links']
assert 'first' not in response.json['links']
assert 'next' not in response.json['links']
def test_get_list_relationship_filter_with_dot_attribute(session, client, register_routes, person, person_2, computer,
computer_2):
computer.person = person
computer_2.person = person_2
session.commit()
with client:
querystring = urlencode(
{
"filter": json.dumps(
[
{
"name": "computers.serial",
"op": "eq",
"val": computer.serial,
}
]
),
}
)
response = client.get("/persons" + "?" + querystring, content_type="application/vnd.api+json")
assert response.status_code == 200
assert len(response.json['data']) == 1
def test_get_list_simple_filter_relationship_with_dot_attribute(session, client, register_routes, person, person_2,
computer, computer_2):
computer.person = person
computer_2.person = person_2
session.commit()
with client:
querystring = urlencode(
{
"filter[computers.serial]": computer.serial
}
)
response = client.get("/persons" + "?" + querystring, content_type="application/vnd.api+json")
assert response.status_code == 200
assert len(response.json['data']) == 1
def test_get_list_simple_filter_relationship_id_complete(session, client, register_routes, person, person_2,
computer, computer_2):
computer.person = person
computer_2.person = person_2
session.commit()
with client:
querystring = urlencode(
{
"filter[computers]": computer_2.id
}
)
response = client.get("/persons" + "?" + querystring, content_type="application/vnd.api+json")
assert response.status_code == 200
assert len(response.json['data']) == 1
def test_get_list_with_simple_filter(client, register_routes, person, person_2):
with client:
querystring = urlencode(
{
"page[number]": 1,
"page[size]": 1,
"fields[person]": "name,birth_date",
"sort": "-name",
"filter[name]": "test",
}
)
response = client.get("/persons" + "?" + querystring, content_type="application/vnd.api+json")
assert response.status_code == 200
assert response.json["meta"]["count"] == 1
def test_get_list_with_simple_filter_relationship_custom_qs(session, client, register_routes, person, person_2,
computer, computer_2):
computer.person = person
computer_2.person = person_2
session.commit()
with client:
querystring = urlencode(
{
"filter[computers.id]": f'{computer_2.id},{computer.id}',
"include": "computers",
"sort": "-name",
}
)
response = client.get("/persons_qs" + "?" + querystring, content_type="application/vnd.api+json")
assert response.status_code == 200
assert len(response.json['data']) == 2
assert response.json['data'][0]['id'] == str(person_2.person_id)
assert response.json['data'][1]['id'] == str(person.person_id)
def test_get_list_with_simple_filter_relationship_custom_qs_api(session, client, register_routes_custom_qs, person,
person_2, computer, computer_2):
computer.person = person
computer_2.person = person_2
session.commit()
with client:
querystring = urlencode(
{
"filter[computers.id]": f'{computer_2.id},{computer.id}',
"include": "computers",
"sort": "-name",
}
)
response = client.get("/qs/persons" + "?" + querystring, content_type="application/vnd.api+json")
assert response.status_code == 200
assert len(response.json['data']) == 2
assert response.json['data'][0]['id'] == str(person_2.person_id)
assert response.json['data'][1]['id'] == str(person.person_id)
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):