Debian Codegraph @

tests/admin_views/test_actions.py

raw
1 import json
2
3 from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
4 from django.contrib.admin.views.main import IS_POPUP_VAR
5 from django.contrib.auth.models import Permission, User
6 from django.core import mail
7 from django.db import connection
8 from django.template.loader import render_to_string
9 from django.template.response import TemplateResponse
10 from django.test import TestCase, override_settings
11 from django.test.utils import CaptureQueriesContext
12 from django.urls import reverse
13
14 from .admin import SubscriberAdmin
15 from .forms import MediaActionForm
16 from .models import (
17 Actor,
18 Answer,
19 Book,
20 ExternalSubscriber,
21 Question,
22 Subscriber,
23 UnchangeableObject,
24 )
25
26
27 @override_settings(ROOT_URLCONF="admin_views.urls")
28 class AdminActionsTest(TestCase):
29 @classmethod
30 def setUpTestData(cls):
31 cls.superuser = User.objects.create_superuser(
32 username="super", password="secret", email="[email protected]"
33 )
34 cls.s1 = ExternalSubscriber.objects.create(
35 name="John Doe", email="[email protected]"
36 )
37 cls.s2 = Subscriber.objects.create(
38 name="Max Mustermann", email="[email protected]"
39 )
40
41 def setUp(self):
42 self.client.force_login(self.superuser)
43
44 def test_model_admin_custom_action(self):
45 """A custom action defined in a ModelAdmin method."""
46 action_data = {
47 ACTION_CHECKBOX_NAME: [self.s1.pk],
48 "action": "mail_admin",
49 "index": 0,
50 }
51 self.client.post(
52 reverse("admin:admin_views_subscriber_changelist"), action_data
53 )
54 self.assertEqual(len(mail.outbox), 1)
55 self.assertEqual(mail.outbox[0].subject, "Greetings from a ModelAdmin action")
56
57 def test_model_admin_default_delete_action(self):
58 action_data = {
59 ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk],
60 "action": "delete_selected",
61 "index": 0,
62 }
63 delete_confirmation_data = {
64 ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk],
65 "action": "delete_selected",
66 "post": "yes",
67 }
68 confirmation = self.client.post(
69 reverse("admin:admin_views_subscriber_changelist"), action_data
70 )
71 self.assertIsInstance(confirmation, TemplateResponse)
72 self.assertContains(
73 confirmation, "Are you sure you want to delete the selected subscribers?"
74 )
75 self.assertContains(confirmation, "<h1>Delete multiple objects</h1>")
76 self.assertContains(confirmation, "<h2>Summary</h2>")
77 self.assertContains(confirmation, "<li>Subscribers: 2</li>")
78 self.assertContains(confirmation, "<li>External subscribers: 1</li>")
79 self.assertContains(confirmation, ACTION_CHECKBOX_NAME, count=2)
80 with CaptureQueriesContext(connection) as ctx:
81 self.client.post(
82 reverse("admin:admin_views_subscriber_changelist"),
83 delete_confirmation_data,
84 )
85 # Log entries are inserted in bulk.
86 self.assertEqual(
87 len(
88 [
89 q["sql"]
90 for q in ctx.captured_queries
91 if q["sql"].startswith("INSERT")
92 ]
93 ),
94 1,
95 )
96 self.assertEqual(Subscriber.objects.count(), 0)
97
98 def test_default_delete_action_nonexistent_pk(self):
99 self.assertFalse(Subscriber.objects.filter(id=9998).exists())
100 action_data = {
101 ACTION_CHECKBOX_NAME: ["9998"],
102 "action": "delete_selected",
103 "index": 0,
104 }
105 response = self.client.post(
106 reverse("admin:admin_views_subscriber_changelist"), action_data
107 )
108 self.assertContains(
109 response, "Are you sure you want to delete the selected subscribers?"
110 )
111 self.assertContains(response, "<ul></ul>", html=True)
112
113 @override_settings(USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=3)
114 def test_non_localized_pk(self):
115 """
116 If USE_THOUSAND_SEPARATOR is set, the ids for the objects selected for
117 deletion are rendered without separators.
118 """
119 s = ExternalSubscriber.objects.create(id=9999)
120 action_data = {
121 ACTION_CHECKBOX_NAME: [s.pk, self.s2.pk],
122 "action": "delete_selected",
123 "index": 0,
124 }
125 response = self.client.post(
126 reverse("admin:admin_views_subscriber_changelist"), action_data
127 )
128 self.assertTemplateUsed(response, "admin/delete_selected_confirmation.html")
129 self.assertContains(response, 'value="9999"') # Instead of 9,999
130 self.assertContains(response, 'value="%s"' % self.s2.pk)
131
132 def test_model_admin_default_delete_action_protected(self):
133 """
134 The default delete action where some related objects are protected
135 from deletion.
136 """
137 q1 = Question.objects.create(question="Why?")
138 a1 = Answer.objects.create(question=q1, answer="Because.")
139 a2 = Answer.objects.create(question=q1, answer="Yes.")
140 q2 = Question.objects.create(question="Wherefore?")
141 action_data = {
142 ACTION_CHECKBOX_NAME: [q1.pk, q2.pk],
143 "action": "delete_selected",
144 "index": 0,
145 }
146 delete_confirmation_data = action_data.copy()
147 delete_confirmation_data["post"] = "yes"
148 response = self.client.post(
149 reverse("admin:admin_views_question_changelist"), action_data
150 )
151 self.assertContains(
152 response, "would require deleting the following protected related objects"
153 )
154 self.assertContains(
155 response,
156 '<li>Answer: <a href="%s">Because.</a></li>'
157 % reverse("admin:admin_views_answer_change", args=(a1.pk,)),
158 html=True,
159 )
160 self.assertContains(
161 response,
162 '<li>Answer: <a href="%s">Yes.</a></li>'
163 % reverse("admin:admin_views_answer_change", args=(a2.pk,)),
164 html=True,
165 )
166 # A POST request to delete protected objects displays the page which
167 # says the deletion is prohibited.
168 response = self.client.post(
169 reverse("admin:admin_views_question_changelist"), delete_confirmation_data
170 )
171 self.assertContains(
172 response, "would require deleting the following protected related objects"
173 )
174 self.assertEqual(Question.objects.count(), 2)
175
176 def test_model_admin_default_delete_action_no_change_url(self):
177 """
178 The default delete action doesn't break if a ModelAdmin removes the
179 change_view URL (#20640).
180 """
181 obj = UnchangeableObject.objects.create()
182 action_data = {
183 ACTION_CHECKBOX_NAME: obj.pk,
184 "action": "delete_selected",
185 "index": "0",
186 }
187 response = self.client.post(
188 reverse("admin:admin_views_unchangeableobject_changelist"), action_data
189 )
190 # No 500 caused by NoReverseMatch. The page doesn't display a link to
191 # the nonexistent change page.
192 self.assertContains(
193 response, "<li>Unchangeable object: %s</li>" % obj, 1, html=True
194 )
195
196 def test_delete_queryset_hook(self):
197 delete_confirmation_data = {
198 ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk],
199 "action": "delete_selected",
200 "post": "yes",
201 "index": 0,
202 }
203 SubscriberAdmin.overridden = False
204 self.client.post(
205 reverse("admin:admin_views_subscriber_changelist"), delete_confirmation_data
206 )
207 # SubscriberAdmin.delete_queryset() sets overridden to True.
208 self.assertIs(SubscriberAdmin.overridden, True)
209 self.assertEqual(Subscriber.objects.count(), 0)
210
211 def test_delete_selected_uses_get_deleted_objects(self):
212 """The delete_selected action uses ModelAdmin.get_deleted_objects()."""
213 book = Book.objects.create(name="Test Book")
214 data = {
215 ACTION_CHECKBOX_NAME: [book.pk],
216 "action": "delete_selected",
217 "index": 0,
218 }
219 response = self.client.post(reverse("admin2:admin_views_book_changelist"), data)
220 # BookAdmin.get_deleted_objects() returns custom text.
221 self.assertContains(response, "a deletable object")
222
223 def test_custom_function_mail_action(self):
224 """A custom action may be defined in a function."""
225 action_data = {
226 ACTION_CHECKBOX_NAME: [self.s1.pk],
227 "action": "external_mail",
228 "index": 0,
229 }
230 self.client.post(
231 reverse("admin:admin_views_externalsubscriber_changelist"), action_data
232 )
233 self.assertEqual(len(mail.outbox), 1)
234 self.assertEqual(mail.outbox[0].subject, "Greetings from a function action")
235
236 def test_custom_function_action_with_redirect(self):
237 """Another custom action defined in a function."""
238 action_data = {
239 ACTION_CHECKBOX_NAME: [self.s1.pk],
240 "action": "redirect_to",
241 "index": 0,
242 }
243 response = self.client.post(
244 reverse("admin:admin_views_externalsubscriber_changelist"), action_data
245 )
246 self.assertEqual(response.status_code, 302)
247
248 def test_default_redirect(self):
249 """
250 Actions which don't return an HttpResponse are redirected to the same
251 page, retaining the querystring (which may contain changelist info).
252 """
253 action_data = {
254 ACTION_CHECKBOX_NAME: [self.s1.pk],
255 "action": "external_mail",
256 "index": 0,
257 }
258 url = reverse("admin:admin_views_externalsubscriber_changelist") + "?o=1"
259 response = self.client.post(url, action_data)
260 self.assertRedirects(response, url)
261
262 def test_custom_function_action_streaming_response(self):
263 """A custom action may return a StreamingHttpResponse."""
264 action_data = {
265 ACTION_CHECKBOX_NAME: [self.s1.pk],
266 "action": "download",
267 "index": 0,
268 }
269 response = self.client.post(
270 reverse("admin:admin_views_externalsubscriber_changelist"), action_data
271 )
272 content = b"".join(list(response))
273 self.assertEqual(content, b"This is the content of the file")
274 self.assertEqual(response.status_code, 200)
275
276 def test_custom_function_action_no_perm_response(self):
277 """A custom action may returns an HttpResponse with a 403 code."""
278 action_data = {
279 ACTION_CHECKBOX_NAME: [self.s1.pk],
280 "action": "no_perm",
281 "index": 0,
282 }
283 response = self.client.post(
284 reverse("admin:admin_views_externalsubscriber_changelist"), action_data
285 )
286 self.assertEqual(response.status_code, 403)
287 self.assertEqual(response.content, b"No permission to perform this action")
288
289 def test_actions_ordering(self):
290 """Actions are ordered as expected."""
291 response = self.client.get(
292 reverse("admin:admin_views_externalsubscriber_changelist")
293 )
294 self.assertContains(
295 response,
296 """<label>Action: <select name="action" required>
297 <option value="" selected>---------</option>
298 <option value="delete_selected">Delete selected external
299 subscribers</option>
300 <option value="redirect_to">Redirect to (Awesome action)</option>
301 <option value="external_mail">External mail (Another awesome
302 action)</option>
303 <option value="download">Download subscription</option>
304 <option value="no_perm">No permission to run</option>
305 </select>""",
306 html=True,
307 )
308
309 def test_model_without_action(self):
310 """A ModelAdmin might not have any actions."""
311 response = self.client.get(
312 reverse("admin:admin_views_oldsubscriber_changelist")
313 )
314 self.assertIsNone(response.context["action_form"])
315 self.assertNotContains(
316 response,
317 '<input type="checkbox" class="action-select"',
318 msg_prefix="Found an unexpected action toggle checkboxbox in response",
319 )
320 self.assertNotContains(response, '<input type="checkbox" class="action-select"')
321
322 def test_model_without_action_still_has_jquery(self):
323 """
324 A ModelAdmin without any actions still has jQuery included on the page.
325 """
326 response = self.client.get(
327 reverse("admin:admin_views_oldsubscriber_changelist")
328 )
329 self.assertIsNone(response.context["action_form"])
330 self.assertContains(
331 response,
332 "jquery.min.js",
333 msg_prefix=(
334 "jQuery missing from admin pages for model with no admin actions"
335 ),
336 )
337
338 def test_action_column_class(self):
339 """The checkbox column class is present in the response."""
340 response = self.client.get(reverse("admin:admin_views_subscriber_changelist"))
341 self.assertIsNotNone(response.context["action_form"])
342 self.assertContains(response, "action-checkbox-column")
343
344 def test_multiple_actions_form(self):
345 """
346 Actions come from the form whose submit button was pressed (#10618).
347 """
348 action_data = {
349 ACTION_CHECKBOX_NAME: [self.s1.pk],
350 # Two different actions selected on the two forms...
351 "action": ["external_mail", "delete_selected"],
352 # ...but "go" was clicked on the top form.
353 "index": 0,
354 }
355 self.client.post(
356 reverse("admin:admin_views_externalsubscriber_changelist"), action_data
357 )
358 # The action sends mail rather than deletes.
359 self.assertEqual(len(mail.outbox), 1)
360 self.assertEqual(mail.outbox[0].subject, "Greetings from a function action")
361
362 def test_media_from_actions_form(self):
363 """
364 The action form's media is included in the changelist view's media.
365 """
366 response = self.client.get(reverse("admin:admin_views_subscriber_changelist"))
367 media_path = MediaActionForm.Media.js[0]
368 self.assertIsInstance(response.context["action_form"], MediaActionForm)
369 self.assertIn("media", response.context)
370 self.assertIn(media_path, response.context["media"]._js)
371 self.assertContains(response, media_path)
372
373 def test_user_message_on_none_selected(self):
374 """
375 User sees a warning when 'Go' is pressed and no items are selected.
376 """
377 action_data = {
378 ACTION_CHECKBOX_NAME: [],
379 "action": "delete_selected",
380 "index": 0,
381 }
382 url = reverse("admin:admin_views_subscriber_changelist")
383 response = self.client.post(url, action_data)
384 self.assertRedirects(response, url, fetch_redirect_response=False)
385 response = self.client.get(response.url)
386 msg = (
387 "Items must be selected in order to perform actions on them. No items have "
388 "been changed."
389 )
390 self.assertContains(response, msg)
391 self.assertEqual(Subscriber.objects.count(), 2)
392
393 def test_user_message_on_no_action(self):
394 """
395 User sees a warning when 'Go' is pressed and no action is selected.
396 """
397 action_data = {
398 ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk],
399 "action": "",
400 "index": 0,
401 }
402 url = reverse("admin:admin_views_subscriber_changelist")
403 response = self.client.post(url, action_data)
404 self.assertRedirects(response, url, fetch_redirect_response=False)
405 response = self.client.get(response.url)
406 self.assertContains(response, "No action selected.")
407 self.assertEqual(Subscriber.objects.count(), 2)
408
409 def test_selection_counter(self):
410 """The selection counter is there."""
411 response = self.client.get(reverse("admin:admin_views_subscriber_changelist"))
412 self.assertContains(response, "0 of 2 selected")
413
414 def test_popup_actions(self):
415 """Actions aren't shown in popups."""
416 changelist_url = reverse("admin:admin_views_subscriber_changelist")
417 response = self.client.get(changelist_url)
418 self.assertIsNotNone(response.context["action_form"])
419 response = self.client.get(changelist_url + "?%s" % IS_POPUP_VAR)
420 self.assertIsNone(response.context["action_form"])
421
422 def test_popup_template_response_on_add(self):
423 """
424 Success on popups shall be rendered from template in order to allow
425 easy customization.
426 """
427 response = self.client.post(
428 reverse("admin:admin_views_actor_add") + "?%s=1" % IS_POPUP_VAR,
429 {"name": "Troy McClure", "age": "55", IS_POPUP_VAR: "1"},
430 )
431 self.assertEqual(response.status_code, 200)
432 self.assertEqual(
433 response.template_name,
434 [
435 "admin/admin_views/actor/popup_response.html",
436 "admin/admin_views/popup_response.html",
437 "admin/popup_response.html",
438 ],
439 )
440 self.assertTemplateUsed(response, "admin/popup_response.html")
441
442 def test_popup_template_response_on_change(self):
443 instance = Actor.objects.create(name="David Tennant", age=45)
444 response = self.client.post(
445 reverse("admin:admin_views_actor_change", args=(instance.pk,))
446 + "?%s=1" % IS_POPUP_VAR,
447 {"name": "David Tennant", "age": "46", IS_POPUP_VAR: "1"},
448 )
449 self.assertEqual(response.status_code, 200)
450 self.assertEqual(
451 response.template_name,
452 [
453 "admin/admin_views/actor/popup_response.html",
454 "admin/admin_views/popup_response.html",
455 "admin/popup_response.html",
456 ],
457 )
458 self.assertTemplateUsed(response, "admin/popup_response.html")
459
460 def test_popup_template_response_on_delete(self):
461 instance = Actor.objects.create(name="David Tennant", age=45)
462 response = self.client.post(
463 reverse("admin:admin_views_actor_delete", args=(instance.pk,))
464 + "?%s=1" % IS_POPUP_VAR,
465 {IS_POPUP_VAR: "1"},
466 )
467 self.assertEqual(response.status_code, 200)
468 self.assertEqual(
469 response.template_name,
470 [
471 "admin/admin_views/actor/popup_response.html",
472 "admin/admin_views/popup_response.html",
473 "admin/popup_response.html",
474 ],
475 )
476 self.assertTemplateUsed(response, "admin/popup_response.html")
477
478 def test_popup_template_escaping(self):
479 popup_response_data = json.dumps(
480 {
481 "new_value": "new_value\\",
482 "obj": "obj\\",
483 "value": "value\\",
484 }
485 )
486 context = {
487 "popup_response_data": popup_response_data,
488 }
489 output = render_to_string("admin/popup_response.html", context)
490 self.assertIn(r"&quot;value\\&quot;", output)
491 self.assertIn(r"&quot;new_value\\&quot;", output)
492 self.assertIn(r"&quot;obj\\&quot;", output)
493
494
495 @override_settings(ROOT_URLCONF="admin_views.urls")
496 class AdminActionsPermissionTests(TestCase):
497 @classmethod
498 def setUpTestData(cls):
499 cls.s1 = ExternalSubscriber.objects.create(
500 name="John Doe", email="[email protected]"
501 )
502 cls.s2 = Subscriber.objects.create(
503 name="Max Mustermann", email="[email protected]"
504 )
505 cls.user = User.objects.create_user(
506 username="user",
507 password="secret",
508 email="[email protected]",
509 is_staff=True,
510 )
511 permission = Permission.objects.get(codename="change_subscriber")
512 cls.user.user_permissions.add(permission)
513
514 def setUp(self):
515 self.client.force_login(self.user)
516
517 def test_model_admin_no_delete_permission(self):
518 """
519 Permission is denied if the user doesn't have delete permission for the
520 model (Subscriber).
521 """
522 action_data = {
523 ACTION_CHECKBOX_NAME: [self.s1.pk],
524 "action": "delete_selected",
525 }
526 url = reverse("admin:admin_views_subscriber_changelist")
527 response = self.client.post(url, action_data)
528 self.assertRedirects(response, url, fetch_redirect_response=False)
529 response = self.client.get(response.url)
530 self.assertContains(response, "No action selected.")
531
532 def test_model_admin_no_delete_permission_externalsubscriber(self):
533 """
534 Permission is denied if the user doesn't have delete permission for a
535 related model (ExternalSubscriber).
536 """
537 permission = Permission.objects.get(codename="delete_subscriber")
538 self.user.user_permissions.add(permission)
539 delete_confirmation_data = {
540 ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk],
541 "action": "delete_selected",
542 "post": "yes",
543 }
544 response = self.client.post(
545 reverse("admin:admin_views_subscriber_changelist"), delete_confirmation_data
546 )
547 self.assertEqual(response.status_code, 403)