test_autocomplete_view.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. import datetime
  2. import json
  3. from contextlib import contextmanager
  4. from django.contrib import admin
  5. from django.contrib.admin.tests import AdminSeleniumTestCase
  6. from django.contrib.admin.views.autocomplete import AutocompleteJsonView
  7. from django.contrib.auth.models import Permission, User
  8. from django.contrib.contenttypes.models import ContentType
  9. from django.core.exceptions import PermissionDenied
  10. from django.http import Http404
  11. from django.test import RequestFactory, override_settings
  12. from django.urls import reverse, reverse_lazy
  13. from .admin import AnswerAdmin, QuestionAdmin
  14. from .models import (
  15. Answer, Author, Authorship, Bonus, Book, Employee, Manager, Parent,
  16. PKChild, Question, Toy, WorkHour,
  17. )
  18. from .tests import AdminViewBasicTestCase
  19. PAGINATOR_SIZE = AutocompleteJsonView.paginate_by
  20. class AuthorAdmin(admin.ModelAdmin):
  21. ordering = ['id']
  22. search_fields = ['id']
  23. class AuthorshipInline(admin.TabularInline):
  24. model = Authorship
  25. autocomplete_fields = ['author']
  26. class BookAdmin(admin.ModelAdmin):
  27. inlines = [AuthorshipInline]
  28. site = admin.AdminSite(name='autocomplete_admin')
  29. site.register(Question, QuestionAdmin)
  30. site.register(Answer, AnswerAdmin)
  31. site.register(Author, AuthorAdmin)
  32. site.register(Book, BookAdmin)
  33. site.register(Employee, search_fields=['name'])
  34. site.register(WorkHour, autocomplete_fields=['employee'])
  35. site.register(Manager, search_fields=['name'])
  36. site.register(Bonus, autocomplete_fields=['recipient'])
  37. site.register(PKChild, search_fields=['name'])
  38. site.register(Toy, autocomplete_fields=['child'])
  39. @contextmanager
  40. def model_admin(model, model_admin, admin_site=site):
  41. org_admin = admin_site._registry.get(model)
  42. if org_admin:
  43. admin_site.unregister(model)
  44. admin_site.register(model, model_admin)
  45. try:
  46. yield
  47. finally:
  48. if org_admin:
  49. admin_site._registry[model] = org_admin
  50. class AutocompleteJsonViewTests(AdminViewBasicTestCase):
  51. as_view_args = {'admin_site': site}
  52. opts = {
  53. 'app_label': Answer._meta.app_label,
  54. 'model_name': Answer._meta.model_name,
  55. 'field_name': 'question'
  56. }
  57. factory = RequestFactory()
  58. url = reverse_lazy('autocomplete_admin:autocomplete')
  59. @classmethod
  60. def setUpTestData(cls):
  61. cls.user = User.objects.create_user(
  62. username='user', password='secret',
  63. email='user@example.com', is_staff=True,
  64. )
  65. super().setUpTestData()
  66. def test_success(self):
  67. q = Question.objects.create(question='Is this a question?')
  68. request = self.factory.get(self.url, {'term': 'is', **self.opts})
  69. request.user = self.superuser
  70. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  71. self.assertEqual(response.status_code, 200)
  72. data = json.loads(response.content.decode('utf-8'))
  73. self.assertEqual(data, {
  74. 'results': [{'id': str(q.pk), 'text': q.question}],
  75. 'pagination': {'more': False},
  76. })
  77. def test_custom_to_field(self):
  78. q = Question.objects.create(question='Is this a question?')
  79. request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'question_with_to_field'})
  80. request.user = self.superuser
  81. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  82. self.assertEqual(response.status_code, 200)
  83. data = json.loads(response.content.decode('utf-8'))
  84. self.assertEqual(data, {
  85. 'results': [{'id': str(q.uuid), 'text': q.question}],
  86. 'pagination': {'more': False},
  87. })
  88. def test_custom_to_field_permission_denied(self):
  89. Question.objects.create(question='Is this a question?')
  90. request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'question_with_to_field'})
  91. request.user = self.user
  92. with self.assertRaises(PermissionDenied):
  93. AutocompleteJsonView.as_view(**self.as_view_args)(request)
  94. def test_custom_to_field_custom_pk(self):
  95. q = Question.objects.create(question='Is this a question?')
  96. opts = {
  97. 'app_label': Question._meta.app_label,
  98. 'model_name': Question._meta.model_name,
  99. 'field_name': 'related_questions',
  100. }
  101. request = self.factory.get(self.url, {'term': 'is', **opts})
  102. request.user = self.superuser
  103. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  104. self.assertEqual(response.status_code, 200)
  105. data = json.loads(response.content.decode('utf-8'))
  106. self.assertEqual(data, {
  107. 'results': [{'id': str(q.big_id), 'text': q.question}],
  108. 'pagination': {'more': False},
  109. })
  110. def test_to_field_resolution_with_mti(self):
  111. """
  112. to_field resolution should correctly resolve for target models using
  113. MTI. Tests for single and multi-level cases.
  114. """
  115. tests = [
  116. (Employee, WorkHour, 'employee'),
  117. (Manager, Bonus, 'recipient'),
  118. ]
  119. for Target, Remote, related_name in tests:
  120. with self.subTest(target_model=Target, remote_model=Remote, related_name=related_name):
  121. o = Target.objects.create(name="Frida Kahlo", gender=2, code="painter", alive=False)
  122. opts = {
  123. 'app_label': Remote._meta.app_label,
  124. 'model_name': Remote._meta.model_name,
  125. 'field_name': related_name,
  126. }
  127. request = self.factory.get(self.url, {'term': 'frida', **opts})
  128. request.user = self.superuser
  129. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  130. self.assertEqual(response.status_code, 200)
  131. data = json.loads(response.content.decode('utf-8'))
  132. self.assertEqual(data, {
  133. 'results': [{'id': str(o.pk), 'text': o.name}],
  134. 'pagination': {'more': False},
  135. })
  136. def test_to_field_resolution_with_fk_pk(self):
  137. p = Parent.objects.create(name="Bertie")
  138. c = PKChild.objects.create(parent=p, name="Anna")
  139. opts = {
  140. 'app_label': Toy._meta.app_label,
  141. 'model_name': Toy._meta.model_name,
  142. 'field_name': 'child',
  143. }
  144. request = self.factory.get(self.url, {'term': 'anna', **opts})
  145. request.user = self.superuser
  146. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  147. self.assertEqual(response.status_code, 200)
  148. data = json.loads(response.content.decode('utf-8'))
  149. self.assertEqual(data, {
  150. 'results': [{'id': str(c.pk), 'text': c.name}],
  151. 'pagination': {'more': False},
  152. })
  153. def test_field_does_not_exist(self):
  154. request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'does_not_exist'})
  155. request.user = self.superuser
  156. with self.assertRaises(PermissionDenied):
  157. AutocompleteJsonView.as_view(**self.as_view_args)(request)
  158. def test_field_no_related_field(self):
  159. request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'answer'})
  160. request.user = self.superuser
  161. with self.assertRaises(PermissionDenied):
  162. AutocompleteJsonView.as_view(**self.as_view_args)(request)
  163. def test_field_does_not_allowed(self):
  164. request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'related_questions'})
  165. request.user = self.superuser
  166. with self.assertRaises(PermissionDenied):
  167. AutocompleteJsonView.as_view(**self.as_view_args)(request)
  168. def test_limit_choices_to(self):
  169. # Answer.question_with_to_field defines limit_choices_to to "those not
  170. # starting with 'not'".
  171. q = Question.objects.create(question='Is this a question?')
  172. Question.objects.create(question='Not a question.')
  173. request = self.factory.get(self.url, {'term': 'is', **self.opts, 'field_name': 'question_with_to_field'})
  174. request.user = self.superuser
  175. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  176. self.assertEqual(response.status_code, 200)
  177. data = json.loads(response.content.decode('utf-8'))
  178. self.assertEqual(data, {
  179. 'results': [{'id': str(q.uuid), 'text': q.question}],
  180. 'pagination': {'more': False},
  181. })
  182. def test_must_be_logged_in(self):
  183. response = self.client.get(self.url, {'term': '', **self.opts})
  184. self.assertEqual(response.status_code, 200)
  185. self.client.logout()
  186. response = self.client.get(self.url, {'term': '', **self.opts})
  187. self.assertEqual(response.status_code, 302)
  188. def test_has_view_or_change_permission_required(self):
  189. """
  190. Users require the change permission for the related model to the
  191. autocomplete view for it.
  192. """
  193. request = self.factory.get(self.url, {'term': 'is', **self.opts})
  194. request.user = self.user
  195. with self.assertRaises(PermissionDenied):
  196. AutocompleteJsonView.as_view(**self.as_view_args)(request)
  197. for permission in ('view', 'change'):
  198. with self.subTest(permission=permission):
  199. self.user.user_permissions.clear()
  200. p = Permission.objects.get(
  201. content_type=ContentType.objects.get_for_model(Question),
  202. codename='%s_question' % permission,
  203. )
  204. self.user.user_permissions.add(p)
  205. request.user = User.objects.get(pk=self.user.pk)
  206. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  207. self.assertEqual(response.status_code, 200)
  208. def test_search_use_distinct(self):
  209. """
  210. Searching across model relations use QuerySet.distinct() to avoid
  211. duplicates.
  212. """
  213. q1 = Question.objects.create(question='question 1')
  214. q2 = Question.objects.create(question='question 2')
  215. q2.related_questions.add(q1)
  216. q3 = Question.objects.create(question='question 3')
  217. q3.related_questions.add(q1)
  218. request = self.factory.get(self.url, {'term': 'question', **self.opts})
  219. request.user = self.superuser
  220. class DistinctQuestionAdmin(QuestionAdmin):
  221. search_fields = ['related_questions__question', 'question']
  222. with model_admin(Question, DistinctQuestionAdmin):
  223. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  224. self.assertEqual(response.status_code, 200)
  225. data = json.loads(response.content.decode('utf-8'))
  226. self.assertEqual(len(data['results']), 3)
  227. def test_missing_search_fields(self):
  228. class EmptySearchAdmin(QuestionAdmin):
  229. search_fields = []
  230. with model_admin(Question, EmptySearchAdmin):
  231. msg = 'EmptySearchAdmin must have search_fields for the autocomplete_view.'
  232. with self.assertRaisesMessage(Http404, msg):
  233. site.autocomplete_view(self.factory.get(self.url, {'term': '', **self.opts}))
  234. def test_get_paginator(self):
  235. """Search results are paginated."""
  236. class PKOrderingQuestionAdmin(QuestionAdmin):
  237. ordering = ['pk']
  238. Question.objects.bulk_create(Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10))
  239. # The first page of results.
  240. request = self.factory.get(self.url, {'term': '', **self.opts})
  241. request.user = self.superuser
  242. with model_admin(Question, PKOrderingQuestionAdmin):
  243. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  244. self.assertEqual(response.status_code, 200)
  245. data = json.loads(response.content.decode('utf-8'))
  246. self.assertEqual(data, {
  247. 'results': [{'id': str(q.pk), 'text': q.question} for q in Question.objects.all()[:PAGINATOR_SIZE]],
  248. 'pagination': {'more': True},
  249. })
  250. # The second page of results.
  251. request = self.factory.get(self.url, {'term': '', 'page': '2', **self.opts})
  252. request.user = self.superuser
  253. with model_admin(Question, PKOrderingQuestionAdmin):
  254. response = AutocompleteJsonView.as_view(**self.as_view_args)(request)
  255. self.assertEqual(response.status_code, 200)
  256. data = json.loads(response.content.decode('utf-8'))
  257. self.assertEqual(data, {
  258. 'results': [{'id': str(q.pk), 'text': q.question} for q in Question.objects.all()[PAGINATOR_SIZE:]],
  259. 'pagination': {'more': False},
  260. })
  261. def test_serialize_result(self):
  262. class AutocompleteJsonSerializeResultView(AutocompleteJsonView):
  263. def serialize_result(self, obj, to_field_name):
  264. return {
  265. **super().serialize_result(obj, to_field_name),
  266. 'posted': str(obj.posted),
  267. }
  268. Question.objects.create(question='Question 1', posted=datetime.date(2021, 8, 9))
  269. Question.objects.create(question='Question 2', posted=datetime.date(2021, 8, 7))
  270. request = self.factory.get(self.url, {'term': 'question', **self.opts})
  271. request.user = self.superuser
  272. response = AutocompleteJsonSerializeResultView.as_view(**self.as_view_args)(request)
  273. self.assertEqual(response.status_code, 200)
  274. data = json.loads(response.content.decode('utf-8'))
  275. self.assertEqual(data, {
  276. 'results': [
  277. {'id': str(q.pk), 'text': q.question, 'posted': str(q.posted)}
  278. for q in Question.objects.order_by('-posted')
  279. ],
  280. 'pagination': {'more': False},
  281. })
  282. @override_settings(ROOT_URLCONF='admin_views.urls')
  283. class SeleniumTests(AdminSeleniumTestCase):
  284. available_apps = ['admin_views'] + AdminSeleniumTestCase.available_apps
  285. def setUp(self):
  286. self.superuser = User.objects.create_superuser(
  287. username='super', password='secret', email='super@example.com',
  288. )
  289. self.admin_login(username='super', password='secret', login_url=reverse('autocomplete_admin:index'))
  290. @contextmanager
  291. def select2_ajax_wait(self, timeout=10):
  292. from selenium.common.exceptions import NoSuchElementException
  293. from selenium.webdriver.support import expected_conditions as ec
  294. yield
  295. with self.disable_implicit_wait():
  296. try:
  297. loading_element = self.selenium.find_element_by_css_selector(
  298. 'li.select2-results__option.loading-results'
  299. )
  300. except NoSuchElementException:
  301. pass
  302. else:
  303. self.wait_until(ec.staleness_of(loading_element), timeout=timeout)
  304. def test_select(self):
  305. from selenium.webdriver.common.keys import Keys
  306. from selenium.webdriver.support.ui import Select
  307. self.selenium.get(self.live_server_url + reverse('autocomplete_admin:admin_views_answer_add'))
  308. elem = self.selenium.find_element_by_css_selector('.select2-selection')
  309. elem.click() # Open the autocomplete dropdown.
  310. results = self.selenium.find_element_by_css_selector('.select2-results')
  311. self.assertTrue(results.is_displayed())
  312. option = self.selenium.find_element_by_css_selector('.select2-results__option')
  313. self.assertEqual(option.text, 'No results found')
  314. elem.click() # Close the autocomplete dropdown.
  315. q1 = Question.objects.create(question='Who am I?')
  316. Question.objects.bulk_create(Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10))
  317. elem.click() # Reopen the dropdown now that some objects exist.
  318. result_container = self.selenium.find_element_by_css_selector('.select2-results')
  319. self.assertTrue(result_container.is_displayed())
  320. results = result_container.find_elements_by_css_selector('.select2-results__option')
  321. # PAGINATOR_SIZE results and "Loading more results".
  322. self.assertEqual(len(results), PAGINATOR_SIZE + 1)
  323. search = self.selenium.find_element_by_css_selector('.select2-search__field')
  324. # Load next page of results by scrolling to the bottom of the list.
  325. with self.select2_ajax_wait():
  326. for _ in range(len(results)):
  327. search.send_keys(Keys.ARROW_DOWN)
  328. results = result_container.find_elements_by_css_selector('.select2-results__option')
  329. # All objects are now loaded.
  330. self.assertEqual(len(results), PAGINATOR_SIZE + 11)
  331. # Limit the results with the search field.
  332. with self.select2_ajax_wait():
  333. search.send_keys('Who')
  334. # Ajax request is delayed.
  335. self.assertTrue(result_container.is_displayed())
  336. results = result_container.find_elements_by_css_selector('.select2-results__option')
  337. self.assertEqual(len(results), PAGINATOR_SIZE + 12)
  338. self.assertTrue(result_container.is_displayed())
  339. results = result_container.find_elements_by_css_selector('.select2-results__option')
  340. self.assertEqual(len(results), 1)
  341. # Select the result.
  342. search.send_keys(Keys.RETURN)
  343. select = Select(self.selenium.find_element_by_id('id_question'))
  344. self.assertEqual(select.first_selected_option.get_attribute('value'), str(q1.pk))
  345. def test_select_multiple(self):
  346. from selenium.webdriver.common.keys import Keys
  347. from selenium.webdriver.support.ui import Select
  348. self.selenium.get(self.live_server_url + reverse('autocomplete_admin:admin_views_question_add'))
  349. elem = self.selenium.find_element_by_css_selector('.select2-selection')
  350. elem.click() # Open the autocomplete dropdown.
  351. results = self.selenium.find_element_by_css_selector('.select2-results')
  352. self.assertTrue(results.is_displayed())
  353. option = self.selenium.find_element_by_css_selector('.select2-results__option')
  354. self.assertEqual(option.text, 'No results found')
  355. elem.click() # Close the autocomplete dropdown.
  356. Question.objects.create(question='Who am I?')
  357. Question.objects.bulk_create(Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10))
  358. elem.click() # Reopen the dropdown now that some objects exist.
  359. result_container = self.selenium.find_element_by_css_selector('.select2-results')
  360. self.assertTrue(result_container.is_displayed())
  361. results = result_container.find_elements_by_css_selector('.select2-results__option')
  362. self.assertEqual(len(results), PAGINATOR_SIZE + 1)
  363. search = self.selenium.find_element_by_css_selector('.select2-search__field')
  364. # Load next page of results by scrolling to the bottom of the list.
  365. with self.select2_ajax_wait():
  366. for _ in range(len(results)):
  367. search.send_keys(Keys.ARROW_DOWN)
  368. results = result_container.find_elements_by_css_selector('.select2-results__option')
  369. self.assertEqual(len(results), 31)
  370. # Limit the results with the search field.
  371. with self.select2_ajax_wait():
  372. search.send_keys('Who')
  373. # Ajax request is delayed.
  374. self.assertTrue(result_container.is_displayed())
  375. results = result_container.find_elements_by_css_selector('.select2-results__option')
  376. self.assertEqual(len(results), 32)
  377. self.assertTrue(result_container.is_displayed())
  378. results = result_container.find_elements_by_css_selector('.select2-results__option')
  379. self.assertEqual(len(results), 1)
  380. # Select the result.
  381. search.send_keys(Keys.RETURN)
  382. # Reopen the dropdown and add the first result to the selection.
  383. elem.click()
  384. search.send_keys(Keys.ARROW_DOWN)
  385. search.send_keys(Keys.RETURN)
  386. select = Select(self.selenium.find_element_by_id('id_related_questions'))
  387. self.assertEqual(len(select.all_selected_options), 2)
  388. def test_inline_add_another_widgets(self):
  389. def assertNoResults(row):
  390. elem = row.find_element_by_css_selector('.select2-selection')
  391. elem.click() # Open the autocomplete dropdown.
  392. results = self.selenium.find_element_by_css_selector('.select2-results')
  393. self.assertTrue(results.is_displayed())
  394. option = self.selenium.find_element_by_css_selector('.select2-results__option')
  395. self.assertEqual(option.text, 'No results found')
  396. # Autocomplete works in rows present when the page loads.
  397. self.selenium.get(self.live_server_url + reverse('autocomplete_admin:admin_views_book_add'))
  398. rows = self.selenium.find_elements_by_css_selector('.dynamic-authorship_set')
  399. self.assertEqual(len(rows), 3)
  400. assertNoResults(rows[0])
  401. # Autocomplete works in rows added using the "Add another" button.
  402. self.selenium.find_element_by_link_text('Add another Authorship').click()
  403. rows = self.selenium.find_elements_by_css_selector('.dynamic-authorship_set')
  404. self.assertEqual(len(rows), 4)
  405. assertNoResults(rows[-1])