1
- from django .template .defaultfilters import dictsort
1
+ from django .template .defaultfilters import _property_resolver , dictsort
2
2
from django .test import SimpleTestCase
3
3
4
4
5
+ class User :
6
+ password = 'abc'
7
+
8
+ _private = 'private'
9
+
10
+ @property
11
+ def test_property (self ):
12
+ return 'cde'
13
+
14
+ def test_method (self ):
15
+ """This is just a test method."""
16
+
17
+
5
18
class FunctionTests (SimpleTestCase ):
6
19
20
+ def test_property_resolver (self ):
21
+ user = User ()
22
+ dict_data = {'a' : {
23
+ 'b1' : {'c' : 'result1' },
24
+ 'b2' : user ,
25
+ 'b3' : {'0' : 'result2' },
26
+ 'b4' : [0 , 1 , 2 ],
27
+ }}
28
+ list_data = ['a' , 'b' , 'c' ]
29
+ tests = [
30
+ ('a.b1.c' , dict_data , 'result1' ),
31
+ ('a.b2.password' , dict_data , 'abc' ),
32
+ ('a.b2.test_property' , dict_data , 'cde' ),
33
+ # The method should not get called.
34
+ ('a.b2.test_method' , dict_data , user .test_method ),
35
+ ('a.b3.0' , dict_data , 'result2' ),
36
+ (0 , list_data , 'a' ),
37
+ ]
38
+ for arg , data , expected_value in tests :
39
+ with self .subTest (arg = arg ):
40
+ self .assertEqual (_property_resolver (arg )(data ), expected_value )
41
+ # Invalid lookups.
42
+ fail_tests = [
43
+ ('a.b1.d' , dict_data , AttributeError ),
44
+ ('a.b2.password.0' , dict_data , AttributeError ),
45
+ ('a.b2._private' , dict_data , AttributeError ),
46
+ ('a.b4.0' , dict_data , AttributeError ),
47
+ ('a' , list_data , AttributeError ),
48
+ ('0' , list_data , TypeError ),
49
+ (4 , list_data , IndexError ),
50
+ ]
51
+ for arg , data , expected_exception in fail_tests :
52
+ with self .subTest (arg = arg ):
53
+ with self .assertRaises (expected_exception ):
54
+ _property_resolver (arg )(data )
55
+
7
56
def test_sort (self ):
8
57
sorted_dicts = dictsort (
9
58
[{'age' : 23 , 'name' : 'Barbara-Ann' },
@@ -21,7 +70,7 @@ def test_sort(self):
21
70
22
71
def test_dictsort_complex_sorting_key (self ):
23
72
"""
24
- Since dictsort uses template.Variable under the hood, it can sort
73
+ Since dictsort uses dict.get()/getattr() under the hood, it can sort
25
74
on keys like 'foo.bar'.
26
75
"""
27
76
data = [
@@ -60,3 +109,9 @@ def test_invalid_values(self):
60
109
self .assertEqual (dictsort ('Hello!' , 'age' ), '' )
61
110
self .assertEqual (dictsort ({'a' : 1 }, 'age' ), '' )
62
111
self .assertEqual (dictsort (1 , 'age' ), '' )
112
+
113
+ def test_invalid_args (self ):
114
+ """Fail silently if invalid lookups are passed."""
115
+ self .assertEqual (dictsort ([{}], '._private' ), '' )
116
+ self .assertEqual (dictsort ([{'_private' : 'test' }], '_private' ), '' )
117
+ self .assertEqual (dictsort ([{'nested' : {'_private' : 'test' }}], 'nested._private' ), '' )
0 commit comments