forked from django-tastypie/django-tastypie
/
resources.py
1999 lines (1634 loc) · 102 KB
/
resources.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
import base64
import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import FieldError
from django.core import mail
from django.core.urlresolvers import reverse
from django import forms
from django.http import HttpRequest
from django.test import TestCase
from django.utils import dateformat
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import Authorization
from tastypie.bundle import Bundle
from tastypie.exceptions import InvalidFilterError, InvalidSortError, ImmediateHttpResponse, BadRequest, NotFound
from tastypie import fields
from tastypie.resources import Resource, ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie.serializers import Serializer
from tastypie.throttle import CacheThrottle
from tastypie.validation import Validation, FormValidation
from core.models import Note, Subject
from core.tests.mocks import MockRequest
try:
import json
except ImportError:
import simplejson as json
class CustomSerializer(Serializer):
pass
class TestObject(object):
name = None
view_count = None
date_joined = None
class BasicResource(Resource):
name = fields.CharField(attribute='name')
view_count = fields.IntegerField(attribute='view_count', default=0)
date_joined = fields.DateTimeField(null=True)
class Meta:
object_class = TestObject
resource_name = 'basic'
def dehydrate_date_joined(self, bundle):
if getattr(bundle.obj, 'date_joined', None) is not None:
return bundle.obj.date_joined
if bundle.data.get('date_joined') is not None:
return bundle.data.get('date_joined')
return datetime.datetime(2010, 3, 27, 22, 30, 0)
def hydrate_date_joined(self, bundle):
bundle.obj.date_joined = bundle.data['date_joined']
return bundle
class AnotherBasicResource(BasicResource):
name = fields.CharField(attribute='name')
view_count = fields.IntegerField(attribute='view_count', default=0)
date_joined = fields.DateField(attribute='created')
is_active = fields.BooleanField(attribute='is_active', default=True)
class Meta:
object_class = TestObject
resource_name = 'anotherbasic'
def dehydrate(self, bundle):
if hasattr(bundle.obj, 'bar'):
bundle.data['bar'] = bundle.obj.bar
return bundle
def hydrate(self, bundle):
if 'bar' in bundle.data:
bundle.obj.bar = 'O HAI BAR!'
return bundle
class NoUriBasicResource(BasicResource):
name = fields.CharField(attribute='name')
view_count = fields.IntegerField(attribute='view_count', default=0)
date_joined = fields.DateTimeField(null=True)
class Meta:
object_class = TestObject
include_resource_uri = False
class NullableNameResource(Resource):
name = fields.CharField(attribute='name', null=True)
class Meta:
object_class = TestObject
resource_name = 'nullable_name'
class ResourceTestCase(TestCase):
def test_fields(self):
basic = BasicResource()
self.assertEqual(len(basic.fields), 4)
self.assert_('name' in basic.fields)
self.assertEqual(isinstance(basic.fields['name'], fields.CharField), True)
self.assertEqual(basic.fields['name']._resource, basic.__class__)
self.assertEqual(basic.fields['name'].instance_name, 'name')
self.assert_('view_count' in basic.fields)
self.assertEqual(isinstance(basic.fields['view_count'], fields.IntegerField), True)
self.assertEqual(basic.fields['view_count']._resource, basic.__class__)
self.assertEqual(basic.fields['view_count'].instance_name, 'view_count')
self.assert_('date_joined' in basic.fields)
self.assertEqual(isinstance(basic.fields['date_joined'], fields.DateTimeField), True)
self.assertEqual(basic.fields['date_joined']._resource, basic.__class__)
self.assertEqual(basic.fields['date_joined'].instance_name, 'date_joined')
self.assert_('resource_uri' in basic.fields)
self.assertEqual(isinstance(basic.fields['resource_uri'], fields.CharField), True)
self.assertEqual(basic.fields['resource_uri']._resource, basic.__class__)
self.assertEqual(basic.fields['resource_uri'].instance_name, 'resource_uri')
self.assertEqual(basic._meta.resource_name, 'basic')
another = AnotherBasicResource()
self.assertEqual(len(another.fields), 5)
self.assert_('name' in another.fields)
self.assertEqual(isinstance(another.name, fields.CharField), True)
self.assertEqual(another.fields['name']._resource, another.__class__)
self.assertEqual(another.fields['name'].instance_name, 'name')
self.assert_('view_count' in another.fields)
self.assertEqual(isinstance(another.view_count, fields.IntegerField), True)
self.assertEqual(another.fields['view_count']._resource, another.__class__)
self.assertEqual(another.fields['view_count'].instance_name, 'view_count')
self.assert_('date_joined' in another.fields)
self.assertEqual(isinstance(another.date_joined, fields.DateField), True)
self.assertEqual(another.fields['date_joined']._resource, another.__class__)
self.assertEqual(another.fields['date_joined'].instance_name, 'date_joined')
self.assert_('is_active' in another.fields)
self.assertEqual(isinstance(another.is_active, fields.BooleanField), True)
self.assertEqual(another.fields['is_active']._resource, another.__class__)
self.assertEqual(another.fields['is_active'].instance_name, 'is_active')
self.assert_('resource_uri' in another.fields)
self.assertEqual(isinstance(another.resource_uri, fields.CharField), True)
self.assertEqual(another.fields['resource_uri']._resource, another.__class__)
self.assertEqual(another.fields['resource_uri'].instance_name, 'resource_uri')
self.assertEqual(another._meta.resource_name, 'anotherbasic')
nouri = NoUriBasicResource()
self.assertEqual(len(nouri.fields), 3)
self.assert_('name' in nouri.fields)
self.assertEqual(isinstance(nouri.name, fields.CharField), True)
self.assertEqual(nouri.fields['name']._resource, nouri.__class__)
self.assertEqual(nouri.fields['name'].instance_name, 'name')
self.assert_('view_count' in nouri.fields)
self.assertEqual(isinstance(nouri.view_count, fields.IntegerField), True)
self.assertEqual(nouri.fields['view_count']._resource, nouri.__class__)
self.assertEqual(nouri.fields['view_count'].instance_name, 'view_count')
self.assert_('date_joined' in nouri.fields)
self.assertEqual(isinstance(nouri.date_joined, fields.DateTimeField), True)
self.assertEqual(nouri.fields['date_joined']._resource, nouri.__class__)
self.assertEqual(nouri.fields['date_joined'].instance_name, 'date_joined')
# Note - automatic resource naming.
self.assertEqual(nouri._meta.resource_name, 'nouribasic')
def test_full_dehydrate(self):
test_object_1 = TestObject()
test_object_1.name = 'Daniel'
test_object_1.view_count = 12
test_object_1.date_joined = datetime.datetime(2010, 3, 30, 9, 0, 0)
test_object_1.foo = "Hi, I'm ignored."
basic = BasicResource()
# Sanity check.
self.assertEqual(basic.name.value, None)
self.assertEqual(basic.view_count.value, None)
self.assertEqual(basic.date_joined.value, None)
bundle_1 = basic.full_dehydrate(test_object_1)
self.assertEqual(bundle_1.data['name'], 'Daniel')
self.assertEqual(bundle_1.data['view_count'], 12)
self.assertEqual(bundle_1.data['date_joined'].year, 2010)
self.assertEqual(bundle_1.data['date_joined'].day, 30)
self.assertEqual(bundle_1.data.get('bar'), None)
# Now check the fallback behaviors.
test_object_2 = TestObject()
test_object_2.name = 'Daniel'
basic_2 = BasicResource()
bundle_2 = basic_2.full_dehydrate(test_object_2)
self.assertEqual(bundle_2.data['name'], 'Daniel')
self.assertEqual(bundle_2.data['view_count'], 0)
self.assertEqual(bundle_2.data['date_joined'].year, 2010)
self.assertEqual(bundle_2.data['date_joined'].day, 27)
test_object_3 = TestObject()
test_object_3.name = 'Joe'
test_object_3.view_count = 5
test_object_3.created = datetime.datetime(2010, 3, 29, 11, 0, 0)
test_object_3.is_active = False
test_object_3.bar = "But sometimes I'm not ignored!"
another_1 = AnotherBasicResource()
another_bundle_1 = another_1.full_dehydrate(test_object_3)
self.assertEqual(another_bundle_1.data['name'], 'Joe')
self.assertEqual(another_bundle_1.data['view_count'], 5)
self.assertEqual(another_bundle_1.data['date_joined'].year, 2010)
self.assertEqual(another_bundle_1.data['date_joined'].day, 29)
self.assertEqual(another_bundle_1.data['is_active'], False)
self.assertEqual(another_bundle_1.data['bar'], "But sometimes I'm not ignored!")
def test_full_hydrate(self):
basic = BasicResource()
basic_bundle_1 = Bundle(data={
'name': 'Daniel',
'view_count': 6,
'date_joined': datetime.datetime(2010, 2, 15, 12, 0, 0)
})
# Now load up the data.
hydrated = basic.full_hydrate(basic_bundle_1)
self.assertEqual(hydrated.data['name'], 'Daniel')
self.assertEqual(hydrated.data['view_count'], 6)
self.assertEqual(hydrated.data['date_joined'], datetime.datetime(2010, 2, 15, 12, 0, 0))
self.assertEqual(hydrated.obj.name, 'Daniel')
self.assertEqual(hydrated.obj.view_count, 6)
self.assertEqual(hydrated.obj.date_joined, datetime.datetime(2010, 2, 15, 12, 0, 0))
another = AnotherBasicResource()
another_bundle_1 = Bundle(data={
'name': 'Daniel',
'view_count': 6,
'date_joined': datetime.datetime(2010, 2, 15, 12, 0, 0),
})
# Now load up the data (without the ``bar`` key).
hydrated = another.full_hydrate(another_bundle_1)
self.assertEqual(hydrated.data['name'], 'Daniel')
self.assertEqual(hydrated.data['view_count'], 6)
self.assertEqual(hydrated.data['date_joined'], datetime.datetime(2010, 2, 15, 12, 0, 0))
self.assertEqual(hydrated.obj.name, 'Daniel')
self.assertEqual(hydrated.obj.view_count, 6)
self.assertEqual(hydrated.obj.date_joined, datetime.datetime(2010, 2, 15, 12, 0, 0))
self.assertEqual(hasattr(hydrated.obj, 'bar'), False)
another_bundle_2 = Bundle(data={
'name': 'Daniel',
'view_count': 6,
'date_joined': datetime.datetime(2010, 2, 15, 12, 0, 0),
'bar': True,
})
# Now load up the data (this time with the ``bar`` key).
hydrated = another.full_hydrate(another_bundle_2)
self.assertEqual(hydrated.data['name'], 'Daniel')
self.assertEqual(hydrated.data['view_count'], 6)
self.assertEqual(hydrated.data['date_joined'], datetime.datetime(2010, 2, 15, 12, 0, 0))
self.assertEqual(hydrated.obj.name, 'Daniel')
self.assertEqual(hydrated.obj.view_count, 6)
self.assertEqual(hydrated.obj.date_joined, datetime.datetime(2010, 2, 15, 12, 0, 0))
self.assertEqual(hydrated.obj.bar, 'O HAI BAR!')
# Test that a nullable value with a previous non-null value
# can be set to None.
nullable = NullableNameResource()
obj = nullable._meta.object_class()
obj.name = "Daniel"
null_bundle = Bundle(obj=obj, data={'name': None})
hydrated = nullable.full_hydrate(null_bundle)
self.assertTrue(hydrated.obj.name is None)
# Test that a nullable value with a previous non-null value
# is not overridden if no value was given
obj = nullable._meta.object_class()
obj.name = "Daniel"
empty_null_bundle = Bundle(obj=obj, data={})
hydrated = nullable.full_hydrate(empty_null_bundle)
self.assertEquals(hydrated.obj.name, "Daniel")
def test_obj_get_list(self):
basic = BasicResource()
self.assertRaises(NotImplementedError, basic.obj_get_list)
def test_obj_delete_list(self):
basic = BasicResource()
self.assertRaises(NotImplementedError, basic.obj_delete_list)
def test_obj_get(self):
basic = BasicResource()
self.assertRaises(NotImplementedError, basic.obj_get, pk=1)
def test_obj_create(self):
basic = BasicResource()
bundle = Bundle()
self.assertRaises(NotImplementedError, basic.obj_create, bundle)
def test_obj_update(self):
basic = BasicResource()
bundle = Bundle()
self.assertRaises(NotImplementedError, basic.obj_update, bundle)
def test_obj_delete(self):
basic = BasicResource()
self.assertRaises(NotImplementedError, basic.obj_delete)
def test_rollback(self):
basic = BasicResource()
bundles_seen = []
self.assertRaises(NotImplementedError, basic.rollback, bundles_seen)
def test_build_schema(self):
basic = BasicResource()
self.assertEqual(basic.build_schema(), {
'fields': {
'view_count': {
'help_text': 'Integer data. Ex: 2673',
'readonly': False,
'type': 'integer',
'nullable': False
},
'date_joined': {
'help_text': 'A date & time as a string. Ex: "2010-11-10T03:07:43"',
'readonly': False,
'type': 'datetime',
'nullable': True
},
'name': {
'help_text': 'Unicode string data. Ex: "Hello World"',
'readonly': False,
'type': 'string',
'nullable': False
},
'resource_uri': {
'help_text': 'Unicode string data. Ex: "Hello World"',
'readonly': True,
'type': 'string',
'nullable': False
}
},
'default_format': 'application/json'
})
basic = BasicResource()
basic._meta.ordering = ['date_joined', 'name']
basic._meta.filtering = {'date_joined': ['gt', 'gte'], 'name': ALL}
self.assertEqual(basic.build_schema(), {
'fields': {
'view_count': {
'help_text': 'Integer data. Ex: 2673',
'readonly': False,
'type': 'integer',
'nullable': False
},
'date_joined': {
'help_text': 'A date & time as a string. Ex: "2010-11-10T03:07:43"',
'readonly': False,
'type': 'datetime',
'nullable': True
},
'name': {
'help_text': 'Unicode string data. Ex: "Hello World"',
'readonly': False,
'type': 'string',
'nullable': False
},
'resource_uri': {
'help_text': 'Unicode string data. Ex: "Hello World"',
'readonly': True,
'type': 'string',
'nullable': False
}
},
'default_format': 'application/json',
'ordering': ['date_joined', 'name'],
'filtering': {
'date_joined': ['gt', 'gte'],
'name': ALL,
}
})
def test_subclassing(self):
class CommonMeta:
default_format = 'application/xml'
class MiniResource(Resource):
abcd = fields.CharField(default='abcd')
efgh = fields.IntegerField(default=1234)
class Meta:
resource_name = 'mini'
mini = MiniResource()
self.assertEqual(len(mini.fields), 3)
class AnotherMiniResource(MiniResource):
ijkl = fields.BooleanField(default=True)
class Meta(CommonMeta):
resource_name = 'anothermini'
another = AnotherMiniResource()
self.assertEqual(len(another.fields), 4)
self.assertEqual(another._meta.default_format, 'application/xml')
def test_method_check(self):
basic = BasicResource()
request = HttpRequest()
request.method = 'GET'
request.GET = {'format': 'json'}
# No allowed methods. Kaboom.
self.assertRaises(ImmediateHttpResponse, basic.method_check, request)
# Not an allowed request.
self.assertRaises(ImmediateHttpResponse, basic.method_check, request, allowed=['post'])
# Allowed (single).
request_method = basic.method_check(request, allowed=['get'])
self.assertEqual(request_method, 'get')
# Allowed (multiple).
request_method = basic.method_check(request, allowed=['post', 'get', 'put'])
self.assertEqual(request_method, 'get')
request = HttpRequest()
request.method = 'POST'
request.POST = {'format': 'json'}
# Not an allowed request.
self.assertRaises(ImmediateHttpResponse, basic.method_check, request, allowed=['get'])
# Allowed (multiple).
request_method = basic.method_check(request, allowed=['post', 'get', 'put'])
self.assertEqual(request_method, 'post')
def test_auth_check(self):
basic = BasicResource()
request = HttpRequest()
request.GET = {'format': 'json'}
# Allowed (single).
try:
basic.is_authenticated(request)
except:
self.fail()
def test_create_response(self):
basic = BasicResource()
request = HttpRequest()
request.GET = {'format': 'json'}
data = {'hello': 'world'}
output = basic.create_response(request, data)
self.assertEqual(output.status_code, 200)
self.assertEqual(output.content, '{"hello": "world"}')
request.GET = {'format': 'xml'}
data = {'objects': [{'hello': 'world', 'abc': 123}], 'meta': {'page': 1}}
output = basic.create_response(request, data)
self.assertEqual(output.status_code, 200)
self.assertEqual(output.content, '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<response><objects type="list"><object type="hash"><abc type="integer">123</abc><hello>world</hello></object></objects><meta type="hash"><page type="integer">1</page></meta></response>')
# ====================
# Model-based tests...
# ====================
class NoteResource(ModelResource):
class Meta:
resource_name = 'notes'
filtering = {
'content': ['startswith', 'exact'],
'title': ALL,
'slug': ['exact'],
}
ordering = ['title', 'slug', 'resource_uri']
queryset = Note.objects.filter(is_active=True)
def get_resource_uri(self, bundle_or_obj):
return '/api/v1/notes/%s/' % bundle_or_obj.obj.id
class LightlyCustomNoteResource(NoteResource):
class Meta:
resource_name = 'noteish'
allowed_methods = ['get']
queryset = Note.objects.filter(is_active=True)
class TinyLimitNoteResource(NoteResource):
class Meta:
limit = 3
resource_name = 'littlenote'
allowed_methods = ['get']
queryset = Note.objects.filter(is_active=True)
class VeryCustomNoteResource(NoteResource):
author = fields.CharField(attribute='author__username')
constant = fields.IntegerField(default=20)
class Meta:
limit = 50
resource_name = 'notey'
serializer = CustomSerializer()
list_allowed_methods = ['get']
detail_allowed_methods = ['get', 'post', 'put']
queryset = Note.objects.all()
fields = ['title', 'content', 'created', 'is_active']
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
def get_resource_uri(self, bundle_or_obj):
return '/api/v1/users/%s/' % bundle_or_obj.obj.id
class DetailedNoteResource(ModelResource):
user = fields.ForeignKey(UserResource, 'author')
hello_world = fields.CharField(default='world')
class Meta:
resource_name = 'detailednotes'
filtering = {
'content': ['startswith', 'exact'],
'title': ALL,
'slug': ['exact'],
'user': ALL,
'hello_world': ['exact'], # Note this is invalid for filtering.
}
ordering = ['title', 'slug', 'user']
queryset = Note.objects.filter(is_active=True)
def get_resource_uri(self, bundle_or_obj):
return '/api/v1/notes/%s/' % bundle_or_obj.obj.id
class ThrottledNoteResource(NoteResource):
class Meta:
resource_name = 'throttlednotes'
queryset = Note.objects.filter(is_active=True)
throttle = CacheThrottle(throttle_at=2, timeframe=5, expiration=5)
class BasicAuthNoteResource(NoteResource):
class Meta:
resource_name = 'notes'
queryset = Note.objects.filter(is_active=True)
authentication = BasicAuthentication()
class NoUriNoteResource(ModelResource):
class Meta:
queryset = Note.objects.filter(is_active=True)
include_resource_uri = False
class WithAbsoluteURLNoteResource(ModelResource):
class Meta:
queryset = Note.objects.filter(is_active=True)
include_absolute_url = True
resource_name = 'withabsoluteurlnote'
def get_resource_uri(self, bundle_or_obj):
return '/api/v1/withabsoluteurlnote/%s/' % bundle_or_obj.obj.id
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'users'
class SubjectResource(ModelResource):
class Meta:
queryset = Subject.objects.all()
resource_name = 'subjects'
class RelatedNoteResource(ModelResource):
author = fields.ForeignKey(UserResource, 'author')
subjects = fields.ManyToManyField(SubjectResource, 'subjects')
class Meta:
queryset = Note.objects.all()
resource_name = 'relatednotes'
filtering = {
'author': ALL,
'subjects': ALL_WITH_RELATIONS,
}
fields = ['title', 'slug', 'content', 'created', 'is_active']
class AnotherRelatedNoteResource(ModelResource):
author = fields.ForeignKey(UserResource, 'author')
subjects = fields.ManyToManyField(SubjectResource, 'subjects', full=True)
class Meta:
queryset = Note.objects.all()
resource_name = 'relatednotes'
filtering = {
'author': ALL,
'subjects': ALL_WITH_RELATIONS,
}
fields = ['title', 'slug', 'content', 'created', 'is_active']
class NullableRelatedNoteResource(AnotherRelatedNoteResource):
author = fields.ForeignKey(UserResource, 'author')
subjects = fields.ManyToManyField(SubjectResource, 'subjects', null=True)
class TestOptionsResource(ModelResource):
class Meta:
queryset = Note.objects.all()
allowed_methods = ['post']
list_allowed_methods = ['post', 'put']
# Per user authorization bits.
class PerUserAuthorization(Authorization):
def apply_limits(self, request, object_list):
if request and hasattr(request, 'user'):
if request.user.is_authenticated():
object_list = object_list.filter(author=request.user)
else:
object_list = object_list.none()
return object_list
class PerUserNoteResource(NoteResource):
class Meta:
resource_name = 'perusernotes'
queryset = Note.objects.all()
authorization = PerUserAuthorization()
def apply_authorization_limits(self, request, object_list):
# Just to demonstrate the per-resource hooks.
object_list = super(PerUserNoteResource, self).apply_authorization_limits(request, object_list)
return object_list.filter(is_active=True)
# End per user authorization bits.
class ModelResourceTestCase(TestCase):
fixtures = ['note_testdata.json']
urls = 'core.tests.field_urls'
def setUp(self):
super(ModelResourceTestCase, self).setUp()
self.note_1 = Note.objects.get(pk=1)
self.subject_1 = Subject.objects.create(
name='News',
url='/news/'
)
self.subject_2 = Subject.objects.create(
name='Photos',
url='/photos/'
)
self.note_1.subjects.add(self.subject_1)
self.note_1.subjects.add(self.subject_2)
def test_init(self):
# Very minimal & stock.
resource_1 = NoteResource()
self.assertEqual(len(resource_1.fields), 8)
self.assertNotEqual(resource_1._meta.queryset, None)
self.assertEqual(resource_1._meta.resource_name, 'notes')
self.assertEqual(resource_1._meta.limit, 20)
self.assertEqual(resource_1._meta.list_allowed_methods, ['get', 'post', 'put', 'delete'])
self.assertEqual(resource_1._meta.detail_allowed_methods, ['get', 'post', 'put', 'delete'])
self.assertEqual(isinstance(resource_1._meta.serializer, Serializer), True)
# Lightly custom.
resource_2 = LightlyCustomNoteResource()
self.assertEqual(len(resource_2.fields), 8)
self.assertNotEqual(resource_2._meta.queryset, None)
self.assertEqual(resource_2._meta.resource_name, 'noteish')
self.assertEqual(resource_2._meta.limit, 20)
self.assertEqual(resource_2._meta.list_allowed_methods, ['get'])
self.assertEqual(resource_2._meta.detail_allowed_methods, ['get'])
self.assertEqual(isinstance(resource_2._meta.serializer, Serializer), True)
# Highly custom.
resource_3 = VeryCustomNoteResource()
self.assertEqual(len(resource_3.fields), 7)
self.assertNotEqual(resource_3._meta.queryset, None)
self.assertEqual(resource_3._meta.resource_name, 'notey')
self.assertEqual(resource_3._meta.limit, 50)
self.assertEqual(resource_3._meta.list_allowed_methods, ['get'])
self.assertEqual(resource_3._meta.detail_allowed_methods, ['get', 'post', 'put'])
self.assertEqual(isinstance(resource_3._meta.serializer, CustomSerializer), True)
# Note - automatic resource naming.
resource_4 = NoUriNoteResource()
self.assertEqual(resource_4._meta.resource_name, 'nourinote')
# Test to make sure that, even with a mix of basic & advanced
# configuration, options are set right.
resource_5 = TestOptionsResource()
self.assertEqual(resource_5._meta.allowed_methods, ['post'])
# Should be the overridden values.
self.assertEqual(resource_5._meta.list_allowed_methods, ['post', 'put'])
# Should inherit from the basic configuration.
self.assertEqual(resource_5._meta.detail_allowed_methods, ['post'])
def test_can_create(self):
resource_1 = NoteResource()
self.assertEqual(resource_1.can_create(), True)
resource_2 = LightlyCustomNoteResource()
self.assertEqual(resource_2.can_create(), False)
def test_can_update(self):
resource_1 = NoteResource()
self.assertEqual(resource_1.can_update(), True)
resource_2 = LightlyCustomNoteResource()
self.assertEqual(resource_2.can_update(), False)
resource_3 = TestOptionsResource()
self.assertEqual(resource_3.can_update(), True)
def test_can_delete(self):
resource_1 = NoteResource()
self.assertEqual(resource_1.can_delete(), True)
resource_2 = LightlyCustomNoteResource()
self.assertEqual(resource_2.can_delete(), False)
def test_fields(self):
# Different from the ``ResourceTestCase.test_fields``, we're checking
# some related bits here & self-referential bits later on.
resource_1 = RelatedNoteResource()
self.assertEqual(len(resource_1.fields), 8)
self.assert_('author' in resource_1.fields)
self.assertTrue(isinstance(resource_1.fields['author'], fields.ToOneField))
self.assertEqual(resource_1.fields['author']._resource, resource_1.__class__)
self.assertEqual(resource_1.fields['author'].instance_name, 'author')
self.assertTrue('subjects' in resource_1.fields)
self.assertTrue(isinstance(resource_1.fields['subjects'], fields.ToManyField))
self.assertEqual(resource_1.fields['subjects']._resource, resource_1.__class__)
self.assertEqual(resource_1.fields['subjects'].instance_name, 'subjects')
def test_urls(self):
# The common case, where the ``Api`` specifies the name.
resource = NoteResource(api_name='v1')
patterns = resource.urls
self.assertEqual(len(patterns), 4)
self.assertEqual([pattern.name for pattern in patterns], ['api_dispatch_list', 'api_get_schema', 'api_get_multiple', 'api_dispatch_detail'])
self.assertEqual(reverse('api_dispatch_list', kwargs={
'api_name': 'v1',
'resource_name': 'notes',
}), '/api/v1/notes/')
self.assertEqual(reverse('api_dispatch_detail', kwargs={
'api_name': 'v1',
'resource_name': 'notes',
'pk': 1,
}), '/api/v1/notes/1/')
# Start over.
resource = NoteResource()
patterns = resource.urls
self.assertEqual(len(patterns), 4)
self.assertEqual([pattern.name for pattern in patterns], ['api_dispatch_list', 'api_get_schema', 'api_get_multiple', 'api_dispatch_detail'])
self.assertEqual(reverse('api_dispatch_list', urlconf='core.tests.manual_urls', kwargs={
'resource_name': 'notes',
}), '/notes/')
self.assertEqual(reverse('api_dispatch_detail', urlconf='core.tests.manual_urls', kwargs={
'resource_name': 'notes',
'pk': 1,
}), '/notes/1/')
def test_determine_format(self):
resource = NoteResource()
request = HttpRequest()
# Default.
self.assertEqual(resource.determine_format(request), 'application/json')
# Test forcing the ``format`` parameter.
request.GET = {'format': 'json'}
self.assertEqual(resource.determine_format(request), 'application/json')
request.GET = {'format': 'jsonp'}
self.assertEqual(resource.determine_format(request), 'text/javascript')
request.GET = {'format': 'xml'}
self.assertEqual(resource.determine_format(request), 'application/xml')
request.GET = {'format': 'yaml'}
self.assertEqual(resource.determine_format(request), 'text/yaml')
request.GET = {'format': 'foo'}
self.assertEqual(resource.determine_format(request), 'application/json')
# Test the ``Accept`` header.
request.META = {'HTTP_ACCEPT': 'application/json'}
self.assertEqual(resource.determine_format(request), 'application/json')
request.META = {'HTTP_ACCEPT': 'text/javascript'}
self.assertEqual(resource.determine_format(request), 'text/javascript')
request.META = {'HTTP_ACCEPT': 'application/xml'}
self.assertEqual(resource.determine_format(request), 'application/xml')
request.META = {'HTTP_ACCEPT': 'text/yaml'}
self.assertEqual(resource.determine_format(request), 'text/yaml')
request.META = {'HTTP_ACCEPT': 'text/html'}
self.assertEqual(resource.determine_format(request), 'text/html')
request.META = {'HTTP_ACCEPT': 'application/json,application/xml;q=0.9,*/*;q=0.8'}
self.assertEqual(resource.determine_format(request), 'application/json')
request.META = {'HTTP_ACCEPT': 'text/plain,application/xml,application/json;q=0.9,*/*;q=0.8'}
self.assertEqual(resource.determine_format(request), 'application/xml')
def test_build_filters(self):
resource = NoteResource()
# Valid none.
self.assertEqual(resource.build_filters(), {})
self.assertEqual(resource.build_filters(filters=None), {})
# Not in the filtering dict.
self.assertEqual(resource.build_filters(filters={'resource_url__exact': '/foo/bar/'}), {})
# Filter valid but disallowed.
self.assertRaises(InvalidFilterError, resource.build_filters, filters={'slug__startswith': 'whee'})
# Skipped due to not being recognized.
self.assertEqual(resource.build_filters(filters={'moof__exact': 'baz'}), {})
# Invalid simple (implicit ``__exact``).
self.assertEqual(resource.build_filters(filters={'title': 'Hello world.'}), {'title__exact': 'Hello world.'})
# Valid simple (explicit ``__exact``).
self.assertEqual(resource.build_filters(filters={'title__exact': 'Hello world.'}), {'title__exact': 'Hello world.'})
# Valid simple (non-``__exact``).
self.assertEqual(resource.build_filters(filters={'content__startswith': 'Hello'}), {'content__startswith': 'Hello'})
# Valid boolean.
self.assertEqual(resource.build_filters(filters={'title': 'true'}), {'title__exact': True})
self.assertEqual(resource.build_filters(filters={'title': 'True'}), {'title__exact': True})
self.assertEqual(resource.build_filters(filters={'title': True}), {'title__exact': True})
self.assertEqual(resource.build_filters(filters={'title': 'false'}), {'title__exact': False})
self.assertEqual(resource.build_filters(filters={'title': 'False'}), {'title__exact': False})
self.assertEqual(resource.build_filters(filters={'title': False}), {'title__exact': False})
self.assertEqual(resource.build_filters(filters={'title': 'nil'}), {'title__exact': None})
self.assertEqual(resource.build_filters(filters={'title': 'none'}), {'title__exact': None})
self.assertEqual(resource.build_filters(filters={'title': 'None'}), {'title__exact': None})
self.assertEqual(resource.build_filters(filters={'title': None}), {'title__exact': None})
# Valid multiple.
self.assertEqual(resource.build_filters(filters={
'slug__exact': 'Hello',
'title__exact': 'RAGE',
'content__startswith': 'A thing here.'
}), {'slug__exact': 'Hello', 'content__startswith': 'A thing here.', 'title__exact': 'RAGE'})
# Valid multiple (model attribute differs from field name).
resource_2 = DetailedNoteResource()
filters_1 = {
'slug__exact': 'Hello',
'title__exact': 'RAGE',
'content__startswith': 'A thing here.',
'user__gt': 2,
}
self.assertEqual(resource_2.build_filters(filters=filters_1), {'title__exact': 'RAGE', 'slug__exact': 'Hello', 'author__gt': 2, 'content__startswith': 'A thing here.'})
# No relationship traversal to the filter, please.
resource_3 = RelatedNoteResource()
self.assertRaises(InvalidFilterError, resource_3.build_filters, filters={'author__username__startswith': 'j'})
# Allow relationship traversal.
self.assertEqual(resource_3.build_filters(filters={'subjects__name__startswith': 'News'}), {'subjects__name__startswith': 'News'})
def test_apply_sorting(self):
resource = NoteResource()
# Valid none.
object_list = resource.obj_get_list()
ordered_list = resource.apply_sorting(object_list)
self.assertEqual([obj.id for obj in ordered_list], [1, 2, 4, 6])
object_list = resource.obj_get_list()
ordered_list = resource.apply_sorting(object_list, options=None)
self.assertEqual([obj.id for obj in ordered_list], [1, 2, 4, 6])
# Not a valid field.
object_list = resource.obj_get_list()
self.assertRaises(InvalidSortError, resource.apply_sorting, object_list, options={'order_by': 'foobar'})
# Not in the ordering dict.
object_list = resource.obj_get_list()
self.assertRaises(InvalidSortError, resource.apply_sorting, object_list, options={'order_by': 'content'})
# No attribute to sort by.
object_list = resource.obj_get_list()
self.assertRaises(InvalidSortError, resource.apply_sorting, object_list, options={'order_by': 'resource_uri'})
# Valid ascending.
object_list = resource.obj_get_list()
ordered_list = resource.apply_sorting(object_list, options={'order_by': 'title'})
self.assertEqual([obj.id for obj in ordered_list], [2, 1, 6, 4])
object_list = resource.obj_get_list()
ordered_list = resource.apply_sorting(object_list, options={'order_by': 'slug'})
self.assertEqual([obj.id for obj in ordered_list], [2, 1, 6, 4])
# Valid descending.
object_list = resource.obj_get_list()
ordered_list = resource.apply_sorting(object_list, options={'order_by': '-title'})
self.assertEqual([obj.id for obj in ordered_list], [4, 6, 1, 2])
object_list = resource.obj_get_list()
ordered_list = resource.apply_sorting(object_list, options={'order_by': '-slug'})
self.assertEqual([obj.id for obj in ordered_list], [4, 6, 1, 2])
# Ensure the deprecated parameter still works.
object_list = resource.obj_get_list()
ordered_list = resource.apply_sorting(object_list, options={'sort_by': '-title'})
self.assertEqual([obj.id for obj in ordered_list], [4, 6, 1, 2])
# Valid combination.
object_list = resource.obj_get_list()
ordered_list = resource.apply_sorting(object_list, options={'order_by': ['title', '-slug']})
self.assertEqual([obj.id for obj in ordered_list], [2, 1, 6, 4])
# Valid (model attribute differs from field name).
resource_2 = DetailedNoteResource()
object_list = resource_2.obj_get_list()
ordered_list = resource_2.apply_sorting(object_list, options={'order_by': '-user'})
self.assertEqual([obj.id for obj in ordered_list], [6, 4, 2, 1])
# Invalid relation.
resource_2 = DetailedNoteResource()
object_list = resource_2.obj_get_list()
ordered_list = resource_2.apply_sorting(object_list, options={'order_by': '-user__baz'})
try:
[obj.id for obj in ordered_list]
self.fail()
except FieldError:
pass
# Valid relation.
resource_2 = DetailedNoteResource()
object_list = resource_2.obj_get_list()
ordered_list = resource_2.apply_sorting(object_list, options={'order_by': 'user__username'})
self.assertEqual([obj.id for obj in ordered_list], [4, 6, 1, 2])
resource_2 = DetailedNoteResource()
object_list = resource_2.obj_get_list()
ordered_list = resource_2.apply_sorting(object_list, options={'order_by': '-user__username'})
self.assertEqual([obj.id for obj in ordered_list], [1, 2, 4, 6])
# Valid relational combination.
resource_2 = DetailedNoteResource()
object_list = resource_2.obj_get_list()
ordered_list = resource_2.apply_sorting(object_list, options={'order_by': ['-user__username', 'title']})
self.assertEqual([obj.id for obj in ordered_list], [2, 1, 6, 4])
def test_get_list(self):
resource = NoteResource()
request = HttpRequest()
request.GET = {'format': 'json'}
resp = resource.get_list(request)
self.assertEqual(resp.status_code, 200)
self.assertEqual(resp.content, '{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 4}, "objects": [{"content": "This is my very first post using my shiny new API. Pretty sweet, huh?", "created": "2010-03-30T20:05:00", "id": "1", "is_active": true, "resource_uri": "/api/v1/notes/1/", "slug": "first-post", "title": "First Post!", "updated": "2010-03-30T20:05:00"}, {"content": "The dog ate my cat today. He looks seriously uncomfortable.", "created": "2010-03-31T20:05:00", "id": "2", "is_active": true, "resource_uri": "/api/v1/notes/2/", "slug": "another-post", "title": "Another Post", "updated": "2010-03-31T20:05:00"}, {"content": "My neighborhood\'s been kinda weird lately, especially after the lava flow took out the corner store. Granny can hardly outrun the magma with her walker.", "created": "2010-04-01T20:05:00", "id": "4", "is_active": true, "resource_uri": "/api/v1/notes/4/", "slug": "recent-volcanic-activity", "title": "Recent Volcanic Activity.", "updated": "2010-04-01T20:05:00"}, {"content": "Man, the second eruption came on fast. Granny didn\'t have a chance. On the upshot, I was able to save her walker and I got a cool shawl out of the deal!", "created": "2010-04-02T10:05:00", "id": "6", "is_active": true, "resource_uri": "/api/v1/notes/6/", "slug": "grannys-gone", "title": "Granny\'s Gone", "updated": "2010-04-02T10:05:00"}]}')
# Test slicing.
# First an invalid offset.
request.GET = {'format': 'json', 'offset': 'abc', 'limit': 1}
try:
resp = resource.get_list(request)
self.fail()
except BadRequest, e:
pass
# Try again with ``wrap_view`` for sanity.
resp = resource.wrap_view('get_list')(request)
self.assertEqual(resp.status_code, 400)
# Then an out of range offset.
request.GET = {'format': 'json', 'offset': -1, 'limit': 1}