forked from carltongibson/django-filter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_filterset.py
630 lines (500 loc) · 21.1 KB
/
test_filterset.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
from __future__ import absolute_import, unicode_literals
import mock
import sys
if sys.version_info >= (2, 7):
import unittest
else: # pragma: nocover
from django.utils import unittest # noqa
from django.db import models
from django.test import TestCase
from django_filters.filterset import FilterSet
from django_filters.filterset import FILTER_FOR_DBFIELD_DEFAULTS
from django_filters.filterset import get_model_field
from django_filters.filters import CharFilter
from django_filters.filters import NumberFilter
from django_filters.filters import ChoiceFilter
from django_filters.filters import ModelChoiceFilter
from django_filters.filters import ModelMultipleChoiceFilter
from .models import User
from .models import AdminUser
from .models import Book
from .models import Profile
from .models import Comment
from .models import Restaurant
from .models import NetworkSetting
from .models import SubnetMaskField
from .models import Account
from .models import BankAccount
from .models import Node
from .models import DirectedNode
from .models import Worker
from .models import Business
def checkItemsEqual(L1, L2):
"""
TestCase.assertItemsEqual() is not available in Python 2.6.
"""
return len(L1) == len(L2) and sorted(L1) == sorted(L2)
class HelperMethodsTests(TestCase):
@unittest.skip('todo')
def test_get_declared_filters(self):
pass
def test_get_model_field(self):
result = get_model_field(User, 'unknown__name')
self.assertIsNone(result)
@unittest.skip('todo')
def test_filters_for_model(self):
pass
@unittest.skip('todo')
def test_filterset_factory(self):
pass
class DbFieldDefaultFiltersTests(TestCase):
def test_expected_db_fields_get_filters(self):
to_check = [
models.BooleanField,
models.CharField,
models.CommaSeparatedIntegerField,
models.DateField,
models.DateTimeField,
models.DecimalField,
models.EmailField,
models.FilePathField,
models.FloatField,
models.IntegerField,
models.IPAddressField,
models.NullBooleanField,
models.PositiveIntegerField,
models.PositiveSmallIntegerField,
models.SlugField,
models.SmallIntegerField,
models.TextField,
models.TimeField,
models.URLField,
models.ForeignKey,
models.OneToOneField,
models.ManyToManyField,
]
msg = "%s expected to be found in FILTER_FOR_DBFIELD_DEFAULTS"
for m in to_check:
self.assertIn(m, FILTER_FOR_DBFIELD_DEFAULTS, msg % m.__name__)
def test_expected_db_fields_do_not_get_filters(self):
to_check = [
models.Field,
models.BigIntegerField,
models.GenericIPAddressField,
models.FileField,
models.ImageField,
]
msg = "%s expected to not be found in FILTER_FOR_DBFIELD_DEFAULTS"
for m in to_check:
self.assertNotIn(m, FILTER_FOR_DBFIELD_DEFAULTS, msg % m.__name__)
class FilterSetFilterForFieldTests(TestCase):
def test_filter_found_for_field(self):
f = User._meta.get_field('username')
result = FilterSet.filter_for_field(f, 'username')
self.assertIsInstance(result, CharFilter)
self.assertEqual(result.name, 'username')
def test_filter_found_for_autofield(self):
f = User._meta.get_field('id')
result = FilterSet.filter_for_field(f, 'id')
self.assertIsInstance(result, NumberFilter)
self.assertEqual(result.name, 'id')
def test_field_with_extras(self):
f = User._meta.get_field('favorite_books')
result = FilterSet.filter_for_field(f, 'favorite_books')
self.assertIsInstance(result, ModelMultipleChoiceFilter)
self.assertEqual(result.name, 'favorite_books')
self.assertTrue('queryset' in result.extra)
self.assertIsNotNone(result.extra['queryset'])
self.assertEqual(result.extra['queryset'].model, Book)
def test_field_with_choices(self):
f = User._meta.get_field('status')
result = FilterSet.filter_for_field(f, 'status')
self.assertIsInstance(result, ChoiceFilter)
self.assertEqual(result.name, 'status')
self.assertTrue('choices' in result.extra)
self.assertIsNotNone(result.extra['choices'])
def test_field_that_is_subclassed(self):
f = User._meta.get_field('first_name')
result = FilterSet.filter_for_field(f, 'first_name')
self.assertIsInstance(result, CharFilter)
def test_symmetrical_selfref_m2m_field(self):
f = Node._meta.get_field('adjacents')
result = FilterSet.filter_for_field(f, 'adjacents')
self.assertIsInstance(result, ModelMultipleChoiceFilter)
self.assertEqual(result.name, 'adjacents')
self.assertTrue('queryset' in result.extra)
self.assertIsNotNone(result.extra['queryset'])
self.assertEqual(result.extra['queryset'].model, Node)
def test_non_symmetrical_selfref_m2m_field(self):
f = DirectedNode._meta.get_field('outbound_nodes')
result = FilterSet.filter_for_field(f, 'outbound_nodes')
self.assertIsInstance(result, ModelMultipleChoiceFilter)
self.assertEqual(result.name, 'outbound_nodes')
self.assertTrue('queryset' in result.extra)
self.assertIsNotNone(result.extra['queryset'])
self.assertEqual(result.extra['queryset'].model, DirectedNode)
def test_m2m_field_with_through_model(self):
f = Business._meta.get_field('employees')
result = FilterSet.filter_for_field(f, 'employees')
self.assertIsInstance(result, ModelMultipleChoiceFilter)
self.assertEqual(result.name, 'employees')
self.assertTrue('queryset' in result.extra)
self.assertIsNotNone(result.extra['queryset'])
self.assertEqual(result.extra['queryset'].model, Worker)
@unittest.skip('todo')
def test_filter_overrides(self):
pass
class FilterSetFilterForReverseFieldTests(TestCase):
def test_reverse_o2o_relationship(self):
f = Account._meta.get_field_by_name('profile')[0]
result = FilterSet.filter_for_reverse_field(f, 'profile')
self.assertIsInstance(result, ModelChoiceFilter)
self.assertEqual(result.name, 'profile')
self.assertTrue('queryset' in result.extra)
self.assertIsNotNone(result.extra['queryset'])
self.assertEqual(result.extra['queryset'].model, Profile)
def test_reverse_fk_relationship(self):
f = User._meta.get_field_by_name('comments')[0]
result = FilterSet.filter_for_reverse_field(f, 'comments')
self.assertIsInstance(result, ModelMultipleChoiceFilter)
self.assertEqual(result.name, 'comments')
self.assertTrue('queryset' in result.extra)
self.assertIsNotNone(result.extra['queryset'])
self.assertEqual(result.extra['queryset'].model, Comment)
def test_reverse_m2m_relationship(self):
f = Book._meta.get_field_by_name('lovers')[0]
result = FilterSet.filter_for_reverse_field(f, 'lovers')
self.assertIsInstance(result, ModelMultipleChoiceFilter)
self.assertEqual(result.name, 'lovers')
self.assertTrue('queryset' in result.extra)
self.assertIsNotNone(result.extra['queryset'])
self.assertEqual(result.extra['queryset'].model, User)
def test_reverse_non_symmetrical_selfref_m2m_field(self):
f = DirectedNode._meta.get_field_by_name('inbound_nodes')[0]
result = FilterSet.filter_for_reverse_field(f, 'inbound_nodes')
self.assertIsInstance(result, ModelMultipleChoiceFilter)
self.assertEqual(result.name, 'inbound_nodes')
self.assertTrue('queryset' in result.extra)
self.assertIsNotNone(result.extra['queryset'])
self.assertEqual(result.extra['queryset'].model, DirectedNode)
def test_reverse_m2m_field_with_through_model(self):
f = Worker._meta.get_field_by_name('employers')[0]
result = FilterSet.filter_for_reverse_field(f, 'employers')
self.assertIsInstance(result, ModelMultipleChoiceFilter)
self.assertEqual(result.name, 'employers')
self.assertTrue('queryset' in result.extra)
self.assertIsNotNone(result.extra['queryset'])
self.assertEqual(result.extra['queryset'].model, Business)
class FilterSetClassCreationTests(TestCase):
def test_no_filters(self):
class F(FilterSet):
pass
self.assertEqual(len(F.declared_filters), 0)
self.assertEqual(len(F.base_filters), 0)
def test_declaring_filter(self):
class F(FilterSet):
username = CharFilter()
self.assertEqual(len(F.declared_filters), 1)
self.assertListEqual(list(F.declared_filters), ['username'])
self.assertEqual(len(F.base_filters), 1)
self.assertListEqual(list(F.base_filters), ['username'])
def test_model_derived(self):
class F(FilterSet):
class Meta:
model = Book
self.assertEqual(len(F.declared_filters), 0)
self.assertEqual(len(F.base_filters), 3)
self.assertListEqual(list(F.base_filters),
['title', 'price', 'average_rating'])
def test_declared_and_model_derived(self):
class F(FilterSet):
username = CharFilter()
class Meta:
model = Book
self.assertEqual(len(F.declared_filters), 1)
self.assertEqual(len(F.base_filters), 4)
self.assertListEqual(list(F.base_filters),
['title', 'price', 'average_rating', 'username'])
def test_meta_fields_with_declared_and_model_derived(self):
class F(FilterSet):
username = CharFilter()
class Meta:
model = Book
fields = ('username', 'price')
self.assertEqual(len(F.declared_filters), 1)
self.assertEqual(len(F.base_filters), 2)
self.assertListEqual(list(F.base_filters), ['username', 'price'])
def test_meta_fields_dictionary_derived(self):
class F(FilterSet):
class Meta:
model = Book
fields = {'price': ['exact', 'gte', 'lte'], }
self.assertEqual(len(F.declared_filters), 0)
self.assertEqual(len(F.base_filters), 3)
expected_list = ['price', 'price__gte', 'price__lte', ]
self.assertTrue(checkItemsEqual(list(F.base_filters), expected_list))
def test_meta_fields_containing_autofield(self):
class F(FilterSet):
username = CharFilter()
class Meta:
model = Book
fields = ('id', 'username', 'price')
self.assertEqual(len(F.declared_filters), 1)
self.assertEqual(len(F.base_filters), 3)
self.assertListEqual(list(F.base_filters), ['id', 'username', 'price'])
def test_meta_fields_dictionary_autofield(self):
class F(FilterSet):
username = CharFilter()
class Meta:
model = Book
fields = {'id': ['exact'],
'username': ['exact'],
}
self.assertEqual(len(F.declared_filters), 1)
self.assertEqual(len(F.base_filters), 2)
expected_list = ['id', 'username']
self.assertTrue(checkItemsEqual(list(F.base_filters), expected_list))
def test_meta_fields_containing_unknown(self):
with self.assertRaises(TypeError):
class F(FilterSet):
username = CharFilter()
class Meta:
model = Book
fields = ('username', 'price', 'other')
def test_meta_fields_dictionary_containing_unknown(self):
with self.assertRaises(TypeError):
class F(FilterSet):
class Meta:
model = Book
fields = {'id': ['exact'],
'title': ['exact'],
'other': ['exact'],
}
def test_meta_exlude_with_declared_and_declared_wins(self):
class F(FilterSet):
username = CharFilter()
class Meta:
model = Book
exclude = ('username', 'price')
self.assertEqual(len(F.declared_filters), 1)
self.assertEqual(len(F.base_filters), 3)
self.assertListEqual(list(F.base_filters),
['title', 'average_rating', 'username'])
def test_meta_fields_and_exlude_and_exclude_wins(self):
class F(FilterSet):
username = CharFilter()
class Meta:
model = Book
fields = ('username', 'title', 'price')
exclude = ('title',)
self.assertEqual(len(F.declared_filters), 1)
self.assertEqual(len(F.base_filters), 2)
self.assertListEqual(list(F.base_filters),
['username', 'price'])
def test_filterset_class_inheritance(self):
class F(FilterSet):
class Meta:
model = Book
class G(F):
pass
self.assertEqual(set(F.base_filters), set(G.base_filters))
class F(FilterSet):
other = CharFilter
class Meta:
model = Book
class G(F):
pass
self.assertEqual(set(F.base_filters), set(G.base_filters))
def test_abstract_model_inheritance(self):
class F(FilterSet):
class Meta:
model = Restaurant
self.assertEqual(set(F.base_filters), set(['name', 'serves_pizza']))
class F(FilterSet):
class Meta:
model = Restaurant
fields = ['name', 'serves_pizza']
self.assertEqual(set(F.base_filters), set(['name', 'serves_pizza']))
def test_custom_field_ignored(self):
class F(FilterSet):
class Meta:
model = NetworkSetting
self.assertEqual(list(F.base_filters.keys()), ['ip'])
def test_custom_field_gets_filter_from_override(self):
class F(FilterSet):
filter_overrides = {
SubnetMaskField: {'filter_class': CharFilter}}
class Meta:
model = NetworkSetting
self.assertEqual(list(F.base_filters.keys()), ['ip', 'mask'])
def test_filterset_for_proxy_model(self):
class F(FilterSet):
class Meta:
model = User
class ProxyF(FilterSet):
class Meta:
model = AdminUser
self.assertEqual(list(F.base_filters), list(ProxyF.base_filters))
@unittest.expectedFailure
def test_filterset_for_mti_model(self):
class F(FilterSet):
class Meta:
model = Account
class FtiF(FilterSet):
class Meta:
model = BankAccount
# fails due to 'account_ptr' getting picked up
self.assertEqual(
list(F.base_filters) + ['amount_saved'],
list(FtiF.base_filters))
class FilterSetInstantiationTests(TestCase):
def test_creating_instance(self):
class F(FilterSet):
class Meta:
model = User
fields = ['username']
f = F()
self.assertFalse(f.is_bound)
self.assertIsNotNone(f.queryset)
self.assertEqual(len(f.filters), len(F.base_filters))
for name, filter_ in f.filters.items():
self.assertEqual(
filter_.model,
User,
"%s does not have model set correctly" % name)
def test_creating_bound_instance(self):
class F(FilterSet):
class Meta:
model = User
fields = ['username']
f = F({'username': 'username'})
self.assertTrue(f.is_bound)
def test_creating_with_queryset(self):
class F(FilterSet):
class Meta:
model = User
fields = ['username']
m = mock.Mock()
f = F(queryset=m)
self.assertEqual(f.queryset, m)
class FilterSetOrderingTests(TestCase):
def setUp(self):
self.alex = User.objects.create(username='alex', status=1)
self.jacob = User.objects.create(username='jacob', status=2)
self.aaron = User.objects.create(username='aaron', status=2)
self.carl = User.objects.create(username='carl', status=0)
# user_ids = list(User.objects.all().values_list('pk', flat=True))
self.qs = User.objects.all().order_by('id')
def test_ordering_when_unbound(self):
class F(FilterSet):
class Meta:
model = User
fields = ['username', 'status']
order_by = ['status']
f = F(queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['carl', 'alex', 'jacob', 'aaron'], lambda o: o.username)
def test_ordering(self):
class F(FilterSet):
class Meta:
model = User
fields = ['username', 'status']
order_by = ['username', 'status']
f = F({'o': 'username'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['aaron', 'alex', 'carl', 'jacob'], lambda o: o.username)
f = F({'o': 'status'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['carl', 'alex', 'jacob', 'aaron'], lambda o: o.username)
def test_ordering_on_unknown_value(self):
class F(FilterSet):
class Meta:
model = User
fields = ['username', 'status']
order_by = ['status']
f = F({'o': 'username'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, [], lambda o: o.username)
def test_ordering_on_unknown_value_results_in_default_ordering_without_strict(self):
class F(FilterSet):
strict = False
class Meta:
model = User
fields = ['username', 'status']
order_by = ['status']
f = F({'o': 'username'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['alex', 'jacob', 'aaron', 'carl'], lambda o: o.username)
def test_ordering_on_different_field(self):
class F(FilterSet):
class Meta:
model = User
fields = ['username', 'status']
order_by = True
f = F({'o': 'username'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['aaron', 'alex', 'carl', 'jacob'], lambda o: o.username)
f = F({'o': 'status'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['carl', 'alex', 'jacob', 'aaron'], lambda o: o.username)
@unittest.skip('todo')
def test_ordering_uses_filter_name(self):
class F(FilterSet):
account = CharFilter(name='username')
class Meta:
model = User
fields = ['account', 'status']
order_by = True
f = F({'o': 'username'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['aaron', 'alex', 'carl', 'jacob'], lambda o: o.username)
def test_ordering_with_overridden_field_name(self):
"""
Set the `order_by_field` on the queryset and ensure that the
field name is respected.
"""
class F(FilterSet):
order_by_field = 'order'
class Meta:
model = User
fields = ['username', 'status']
order_by = ['status']
f = F({'order': 'status'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['carl', 'alex', 'jacob', 'aaron'], lambda o: o.username)
def test_ordering_descending_set(self):
class F(FilterSet):
class Meta:
model = User
fields = ['username', 'status']
order_by = ['username', '-username']
f = F({'o': '-username'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['jacob', 'carl', 'alex', 'aaron'], lambda o: o.username)
def test_ordering_descending_unset(self):
""" Test ordering descending works when order_by=True. """
class F(FilterSet):
class Meta:
model = User
fields = ['username', 'status']
order_by = True
f = F({'o': '-username'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['jacob', 'carl', 'alex', 'aaron'], lambda o: o.username)
def test_custom_ordering(self):
class F(FilterSet):
debug = True
class Meta:
model = User
fields = ['username', 'status']
order_by = ['username', 'status']
def get_order_by(self, order_choice):
if order_choice == 'status':
return ['status', 'username']
return super(F, self).get_order_by(order_choice)
f = F({'o': 'username'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['aaron', 'alex', 'carl', 'jacob'], lambda o: o.username)
f = F({'o': 'status'}, queryset=self.qs)
self.assertQuerysetEqual(
f.qs, ['carl', 'alex', 'aaron', 'jacob'], lambda o: o.username)