Debian Codegraph @

tests/test_utils.py

raw
1 from unittest import mock
2
3 from django.test import TestCase, override_settings
4 from django.urls import path
5
6 from rest_framework.decorators import action
7 from rest_framework.routers import SimpleRouter
8 from rest_framework.serializers import ModelSerializer
9 from rest_framework.utils import json
10 from rest_framework.utils.breadcrumbs import get_breadcrumbs
11 from rest_framework.utils.formatting import lazy_format
12 from rest_framework.utils.model_meta import FieldInfo, RelationInfo
13 from rest_framework.utils.urls import remove_query_param, replace_query_param
14 from rest_framework.views import APIView
15 from rest_framework.viewsets import ModelViewSet
16 from tests.models import BasicModel
17
18
19 class Root(APIView):
20 pass
21
22
23 class ResourceRoot(APIView):
24 pass
25
26
27 class ResourceInstance(APIView):
28 pass
29
30
31 class NestedResourceRoot(APIView):
32 pass
33
34
35 class NestedResourceInstance(APIView):
36 pass
37
38
39 class CustomNameResourceInstance(APIView):
40 def get_view_name(self):
41 return "Foo"
42
43
44 class ResourceViewSet(ModelViewSet):
45 serializer_class = ModelSerializer
46 queryset = BasicModel.objects.all()
47
48 @action(detail=False)
49 def list_action(self, request, *args, **kwargs):
50 raise NotImplementedError
51
52 @action(detail=True)
53 def detail_action(self, request, *args, **kwargs):
54 raise NotImplementedError
55
56 @action(detail=True, name='Custom Name')
57 def named_action(self, request, *args, **kwargs):
58 raise NotImplementedError
59
60 @action(detail=True, suffix='Custom Suffix')
61 def suffixed_action(self, request, *args, **kwargs):
62 raise NotImplementedError
63
64
65 router = SimpleRouter()
66 router.register(r'resources', ResourceViewSet)
67 urlpatterns = [
68 path('', Root.as_view()),
69 path('resource/', ResourceRoot.as_view()),
70 path('resource/customname', CustomNameResourceInstance.as_view()),
71 path('resource/<int:key>', ResourceInstance.as_view()),
72 path('resource/<int:key>/', NestedResourceRoot.as_view()),
73 path('resource/<int:key>/<str:other>', NestedResourceInstance.as_view()),
74 ]
75 urlpatterns += router.urls
76
77
78 @override_settings(ROOT_URLCONF='tests.test_utils')
79 class BreadcrumbTests(TestCase):
80 """
81 Tests the breadcrumb functionality used by the HTML renderer.
82 """
83 def test_root_breadcrumbs(self):
84 url = '/'
85 assert get_breadcrumbs(url) == [('Root', '/')]
86
87 def test_resource_root_breadcrumbs(self):
88 url = '/resource/'
89 assert get_breadcrumbs(url) == [
90 ('Root', '/'), ('Resource Root', '/resource/')
91 ]
92
93 def test_resource_instance_breadcrumbs(self):
94 url = '/resource/123'
95 assert get_breadcrumbs(url) == [
96 ('Root', '/'),
97 ('Resource Root', '/resource/'),
98 ('Resource Instance', '/resource/123')
99 ]
100
101 def test_resource_instance_customname_breadcrumbs(self):
102 url = '/resource/customname'
103 assert get_breadcrumbs(url) == [
104 ('Root', '/'),
105 ('Resource Root', '/resource/'),
106 ('Foo', '/resource/customname')
107 ]
108
109 def test_nested_resource_breadcrumbs(self):
110 url = '/resource/123/'
111 assert get_breadcrumbs(url) == [
112 ('Root', '/'),
113 ('Resource Root', '/resource/'),
114 ('Resource Instance', '/resource/123'),
115 ('Nested Resource Root', '/resource/123/')
116 ]
117
118 def test_nested_resource_instance_breadcrumbs(self):
119 url = '/resource/123/abc'
120 assert get_breadcrumbs(url) == [
121 ('Root', '/'),
122 ('Resource Root', '/resource/'),
123 ('Resource Instance', '/resource/123'),
124 ('Nested Resource Root', '/resource/123/'),
125 ('Nested Resource Instance', '/resource/123/abc')
126 ]
127
128 def test_broken_url_breadcrumbs_handled_gracefully(self):
129 url = '/foobar'
130 assert get_breadcrumbs(url) == [('Root', '/')]
131
132 def test_modelviewset_resource_instance_breadcrumbs(self):
133 url = '/resources/1/'
134 assert get_breadcrumbs(url) == [
135 ('Root', '/'),
136 ('Resource List', '/resources/'),
137 ('Resource Instance', '/resources/1/')
138 ]
139
140 def test_modelviewset_list_action_breadcrumbs(self):
141 url = '/resources/list_action/'
142 assert get_breadcrumbs(url) == [
143 ('Root', '/'),
144 ('Resource List', '/resources/'),
145 ('List action', '/resources/list_action/'),
146 ]
147
148 def test_modelviewset_detail_action_breadcrumbs(self):
149 url = '/resources/1/detail_action/'
150 assert get_breadcrumbs(url) == [
151 ('Root', '/'),
152 ('Resource List', '/resources/'),
153 ('Resource Instance', '/resources/1/'),
154 ('Detail action', '/resources/1/detail_action/'),
155 ]
156
157 def test_modelviewset_action_name_kwarg(self):
158 url = '/resources/1/named_action/'
159 assert get_breadcrumbs(url) == [
160 ('Root', '/'),
161 ('Resource List', '/resources/'),
162 ('Resource Instance', '/resources/1/'),
163 ('Custom Name', '/resources/1/named_action/'),
164 ]
165
166 def test_modelviewset_action_suffix_kwarg(self):
167 url = '/resources/1/suffixed_action/'
168 assert get_breadcrumbs(url) == [
169 ('Root', '/'),
170 ('Resource List', '/resources/'),
171 ('Resource Instance', '/resources/1/'),
172 ('Resource Custom Suffix', '/resources/1/suffixed_action/'),
173 ]
174
175
176 class JsonFloatTests(TestCase):
177 """
178 Internally, wrapped json functions should adhere to strict float handling
179 """
180
181 def test_dumps(self):
182 with self.assertRaises(ValueError):
183 json.dumps(float('inf'))
184
185 with self.assertRaises(ValueError):
186 json.dumps(float('nan'))
187
188 def test_loads(self):
189 with self.assertRaises(ValueError):
190 json.loads("Infinity")
191
192 with self.assertRaises(ValueError):
193 json.loads("NaN")
194
195
196 @override_settings(REST_FRAMEWORK={'STRICT_JSON': False})
197 class NonStrictJsonFloatTests(JsonFloatTests):
198 """
199 'STRICT_JSON = False' should not somehow affect internal json behavior
200 """
201
202
203 class UrlsReplaceQueryParamTests(TestCase):
204 """
205 Tests the replace_query_param functionality.
206 """
207 def test_valid_unicode_preserved(self):
208 # Encoded string: '查询'
209 q = '/?q=%E6%9F%A5%E8%AF%A2'
210 new_key = 'page'
211 new_value = 2
212 value = '%E6%9F%A5%E8%AF%A2'
213
214 assert new_key in replace_query_param(q, new_key, new_value)
215 assert value in replace_query_param(q, new_key, new_value)
216
217 def test_valid_unicode_replaced(self):
218 q = '/?page=1'
219 value = '1'
220 new_key = 'q'
221 new_value = '%E6%9F%A5%E8%AF%A2'
222
223 assert new_key in replace_query_param(q, new_key, new_value)
224 assert value in replace_query_param(q, new_key, new_value)
225
226 def test_invalid_unicode(self):
227 # Encoded string: '��<script>alert(313)</script>=1'
228 q = '/e/?%FF%FE%3C%73%63%72%69%70%74%3E%61%6C%65%72%74%28%33%31%33%29%3C%2F%73%63%72%69%70%74%3E=1'
229 key = 'from'
230 value = 'login'
231
232 assert key in replace_query_param(q, key, value)
233
234
235 class UrlsRemoveQueryParamTests(TestCase):
236 """
237 Tests the remove_query_param functionality.
238 """
239 def test_valid_unicode_removed(self):
240 q = '/?page=2345&q=%E6%9F%A5%E8%AF%A2'
241 key = 'page'
242 value = '2345'
243 removed_key = 'q'
244
245 assert key in remove_query_param(q, removed_key)
246 assert value in remove_query_param(q, removed_key)
247 assert '%' not in remove_query_param(q, removed_key)
248
249 def test_invalid_unicode(self):
250 q = '/?from=login&page=2&%FF%FE%3C%73%63%72%69%70%74%3E%61%6C%65%72%74%28%33%31%33%29%3C%2F%73%63%72%69%70%74%3E=1'
251 key = 'from'
252 removed_key = 'page'
253
254 assert key in remove_query_param(q, removed_key)
255
256
257 class LazyFormatTests(TestCase):
258 def test_it_formats_correctly(self):
259 formatted = lazy_format('Does {} work? {answer}: %s', 'it', answer='Yes')
260 assert str(formatted) == 'Does it work? Yes: %s'
261 assert formatted % 'it does' == 'Does it work? Yes: it does'
262
263 def test_it_formats_lazily(self):
264 message = mock.Mock(wraps='message')
265 formatted = lazy_format(message)
266 assert message.format.call_count == 0
267 str(formatted)
268 assert message.format.call_count == 1
269 str(formatted)
270 assert message.format.call_count == 1
271
272
273 class ModelMetaNamedTupleNames(TestCase):
274 def test_named_tuple_names(self):
275 assert FieldInfo.__name__ == 'FieldInfo'
276 assert RelationInfo.__name__ == 'RelationInfo'