test_edit.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. from __future__ import unicode_literals
  2. import warnings
  3. from django import forms
  4. from django.core.exceptions import ImproperlyConfigured
  5. from django.core.urlresolvers import reverse
  6. from django.test import (
  7. SimpleTestCase, TestCase, ignore_warnings, override_settings,
  8. )
  9. from django.test.client import RequestFactory
  10. from django.utils.deprecation import RemovedInDjango110Warning
  11. from django.views.generic.base import View
  12. from django.views.generic.edit import CreateView, FormMixin, ModelFormMixin
  13. from . import views
  14. from .models import Artist, Author
  15. from .test_forms import AuthorForm
  16. class FormMixinTests(SimpleTestCase):
  17. def test_initial_data(self):
  18. """ Test instance independence of initial data dict (see #16138) """
  19. initial_1 = FormMixin().get_initial()
  20. initial_1['foo'] = 'bar'
  21. initial_2 = FormMixin().get_initial()
  22. self.assertNotEqual(initial_1, initial_2)
  23. def test_get_prefix(self):
  24. """ Test prefix can be set (see #18872) """
  25. test_string = 'test'
  26. rf = RequestFactory()
  27. get_request = rf.get('/')
  28. class TestFormMixin(FormMixin):
  29. request = get_request
  30. default_kwargs = TestFormMixin().get_form_kwargs()
  31. self.assertIsNone(default_kwargs.get('prefix'))
  32. set_mixin = TestFormMixin()
  33. set_mixin.prefix = test_string
  34. set_kwargs = set_mixin.get_form_kwargs()
  35. self.assertEqual(test_string, set_kwargs.get('prefix'))
  36. def test_get_form(self):
  37. class TestFormMixin(FormMixin):
  38. request = RequestFactory().get('/')
  39. self.assertIsInstance(
  40. TestFormMixin().get_form(forms.Form), forms.Form,
  41. 'get_form() should use provided form class.'
  42. )
  43. class FormClassTestFormMixin(TestFormMixin):
  44. form_class = forms.Form
  45. self.assertIsInstance(
  46. FormClassTestFormMixin().get_form(), forms.Form,
  47. 'get_form() should fallback to get_form_class() if none is provided.'
  48. )
  49. def test_get_form_missing_form_class_default_value(self):
  50. with warnings.catch_warnings(record=True) as w:
  51. warnings.filterwarnings('always')
  52. class MissingDefaultValue(FormMixin):
  53. request = RequestFactory().get('/')
  54. form_class = forms.Form
  55. def get_form(self, form_class):
  56. return form_class(**self.get_form_kwargs())
  57. self.assertEqual(len(w), 1)
  58. self.assertEqual(w[0].category, RemovedInDjango110Warning)
  59. self.assertEqual(
  60. str(w[0].message),
  61. '`generic_views.test_edit.MissingDefaultValue.get_form` method '
  62. 'must define a default value for its `form_class` argument.'
  63. )
  64. self.assertIsInstance(
  65. MissingDefaultValue().get_form(), forms.Form,
  66. )
  67. def test_get_context_data(self):
  68. class FormContext(FormMixin):
  69. request = RequestFactory().get('/')
  70. form_class = forms.Form
  71. self.assertIsInstance(FormContext().get_context_data()['form'], forms.Form)
  72. @override_settings(ROOT_URLCONF='generic_views.urls')
  73. class BasicFormTests(TestCase):
  74. def test_post_data(self):
  75. res = self.client.post('/contact/', {'name': "Me", 'message': "Hello"})
  76. self.assertRedirects(res, '/list/authors/')
  77. class ModelFormMixinTests(SimpleTestCase):
  78. def test_get_form(self):
  79. form_class = views.AuthorGetQuerySetFormView().get_form_class()
  80. self.assertEqual(form_class._meta.model, Author)
  81. def test_get_form_checks_for_object(self):
  82. mixin = ModelFormMixin()
  83. mixin.request = RequestFactory().get('/')
  84. self.assertEqual({'initial': {}, 'prefix': None},
  85. mixin.get_form_kwargs())
  86. @override_settings(ROOT_URLCONF='generic_views.urls')
  87. class CreateViewTests(TestCase):
  88. def test_create(self):
  89. res = self.client.get('/edit/authors/create/')
  90. self.assertEqual(res.status_code, 200)
  91. self.assertIsInstance(res.context['form'], forms.ModelForm)
  92. self.assertIsInstance(res.context['view'], View)
  93. self.assertNotIn('object', res.context)
  94. self.assertNotIn('author', res.context)
  95. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  96. res = self.client.post('/edit/authors/create/',
  97. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  98. self.assertEqual(res.status_code, 302)
  99. self.assertRedirects(res, '/list/authors/')
  100. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  101. def test_create_invalid(self):
  102. res = self.client.post('/edit/authors/create/',
  103. {'name': 'A' * 101, 'slug': 'randall-munroe'})
  104. self.assertEqual(res.status_code, 200)
  105. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  106. self.assertEqual(len(res.context['form'].errors), 1)
  107. self.assertEqual(Author.objects.count(), 0)
  108. def test_create_with_object_url(self):
  109. res = self.client.post('/edit/artists/create/',
  110. {'name': 'Rene Magritte'})
  111. self.assertEqual(res.status_code, 302)
  112. artist = Artist.objects.get(name='Rene Magritte')
  113. self.assertRedirects(res, '/detail/artist/%d/' % artist.pk)
  114. self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>'])
  115. def test_create_with_redirect(self):
  116. res = self.client.post('/edit/authors/create/redirect/',
  117. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  118. self.assertEqual(res.status_code, 302)
  119. self.assertRedirects(res, '/edit/authors/create/')
  120. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  121. @ignore_warnings(category=RemovedInDjango110Warning)
  122. def test_create_with_interpolated_redirect(self):
  123. res = self.client.post(
  124. '/edit/authors/create/interpolate_redirect/',
  125. {'name': 'Randall Munroe', 'slug': 'randall-munroe'}
  126. )
  127. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  128. self.assertEqual(res.status_code, 302)
  129. pk = Author.objects.first().pk
  130. self.assertRedirects(res, '/edit/author/%d/update/' % pk)
  131. # Also test with escaped chars in URL
  132. res = self.client.post(
  133. '/edit/authors/create/interpolate_redirect_nonascii/',
  134. {'name': 'John Doe', 'slug': 'john-doe'}
  135. )
  136. self.assertEqual(res.status_code, 302)
  137. pk = Author.objects.get(name='John Doe').pk
  138. self.assertRedirects(res, '/%C3%A9dit/author/{}/update/'.format(pk))
  139. def test_create_with_special_properties(self):
  140. res = self.client.get('/edit/authors/create/special/')
  141. self.assertEqual(res.status_code, 200)
  142. self.assertIsInstance(res.context['form'], views.AuthorForm)
  143. self.assertNotIn('object', res.context)
  144. self.assertNotIn('author', res.context)
  145. self.assertTemplateUsed(res, 'generic_views/form.html')
  146. res = self.client.post('/edit/authors/create/special/',
  147. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  148. self.assertEqual(res.status_code, 302)
  149. obj = Author.objects.get(slug='randall-munroe')
  150. self.assertRedirects(res, reverse('author_detail', kwargs={'pk': obj.pk}))
  151. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  152. def test_create_without_redirect(self):
  153. try:
  154. self.client.post('/edit/authors/create/naive/',
  155. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  156. self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided')
  157. except ImproperlyConfigured:
  158. pass
  159. def test_create_restricted(self):
  160. res = self.client.post('/edit/authors/create/restricted/',
  161. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  162. self.assertEqual(res.status_code, 302)
  163. self.assertRedirects(res, '/accounts/login/?next=/edit/authors/create/restricted/')
  164. def test_create_view_with_restricted_fields(self):
  165. class MyCreateView(CreateView):
  166. model = Author
  167. fields = ['name']
  168. self.assertEqual(list(MyCreateView().get_form_class().base_fields),
  169. ['name'])
  170. def test_create_view_all_fields(self):
  171. class MyCreateView(CreateView):
  172. model = Author
  173. fields = '__all__'
  174. self.assertEqual(list(MyCreateView().get_form_class().base_fields),
  175. ['name', 'slug'])
  176. def test_create_view_without_explicit_fields(self):
  177. class MyCreateView(CreateView):
  178. model = Author
  179. message = (
  180. "Using ModelFormMixin (base class of MyCreateView) without the "
  181. "'fields' attribute is prohibited."
  182. )
  183. with self.assertRaisesMessage(ImproperlyConfigured, message):
  184. MyCreateView().get_form_class()
  185. def test_define_both_fields_and_form_class(self):
  186. class MyCreateView(CreateView):
  187. model = Author
  188. form_class = AuthorForm
  189. fields = ['name']
  190. message = "Specifying both 'fields' and 'form_class' is not permitted."
  191. with self.assertRaisesMessage(ImproperlyConfigured, message):
  192. MyCreateView().get_form_class()
  193. @override_settings(ROOT_URLCONF='generic_views.urls')
  194. class UpdateViewTests(TestCase):
  195. def test_update_post(self):
  196. a = Author.objects.create(
  197. name='Randall Munroe',
  198. slug='randall-munroe',
  199. )
  200. res = self.client.get('/edit/author/%d/update/' % a.pk)
  201. self.assertEqual(res.status_code, 200)
  202. self.assertIsInstance(res.context['form'], forms.ModelForm)
  203. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  204. self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
  205. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  206. # Modification with both POST and PUT (browser compatible)
  207. res = self.client.post('/edit/author/%d/update/' % a.pk,
  208. {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
  209. self.assertEqual(res.status_code, 302)
  210. self.assertRedirects(res, '/list/authors/')
  211. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])
  212. def test_update_invalid(self):
  213. a = Author.objects.create(
  214. name='Randall Munroe',
  215. slug='randall-munroe',
  216. )
  217. res = self.client.post('/edit/author/%d/update/' % a.pk,
  218. {'name': 'A' * 101, 'slug': 'randall-munroe'})
  219. self.assertEqual(res.status_code, 200)
  220. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  221. self.assertEqual(len(res.context['form'].errors), 1)
  222. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  223. def test_update_with_object_url(self):
  224. a = Artist.objects.create(name='Rene Magritte')
  225. res = self.client.post('/edit/artists/%d/update/' % a.pk,
  226. {'name': 'Rene Magritte'})
  227. self.assertEqual(res.status_code, 302)
  228. self.assertRedirects(res, '/detail/artist/%d/' % a.pk)
  229. self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>'])
  230. def test_update_with_redirect(self):
  231. a = Author.objects.create(
  232. name='Randall Munroe',
  233. slug='randall-munroe',
  234. )
  235. res = self.client.post('/edit/author/%d/update/redirect/' % a.pk,
  236. {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
  237. self.assertEqual(res.status_code, 302)
  238. self.assertRedirects(res, '/edit/authors/create/')
  239. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
  240. @ignore_warnings(category=RemovedInDjango110Warning)
  241. def test_update_with_interpolated_redirect(self):
  242. a = Author.objects.create(
  243. name='Randall Munroe',
  244. slug='randall-munroe',
  245. )
  246. res = self.client.post(
  247. '/edit/author/%d/update/interpolate_redirect/' % a.pk,
  248. {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}
  249. )
  250. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
  251. self.assertEqual(res.status_code, 302)
  252. pk = Author.objects.first().pk
  253. self.assertRedirects(res, '/edit/author/%d/update/' % pk)
  254. # Also test with escaped chars in URL
  255. res = self.client.post(
  256. '/edit/author/%d/update/interpolate_redirect_nonascii/' % a.pk,
  257. {'name': 'John Doe', 'slug': 'john-doe'}
  258. )
  259. self.assertEqual(res.status_code, 302)
  260. pk = Author.objects.get(name='John Doe').pk
  261. self.assertRedirects(res, '/%C3%A9dit/author/{}/update/'.format(pk))
  262. def test_update_with_special_properties(self):
  263. a = Author.objects.create(
  264. name='Randall Munroe',
  265. slug='randall-munroe',
  266. )
  267. res = self.client.get('/edit/author/%d/update/special/' % a.pk)
  268. self.assertEqual(res.status_code, 200)
  269. self.assertIsInstance(res.context['form'], views.AuthorForm)
  270. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  271. self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
  272. self.assertNotIn('author', res.context)
  273. self.assertTemplateUsed(res, 'generic_views/form.html')
  274. res = self.client.post('/edit/author/%d/update/special/' % a.pk,
  275. {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
  276. self.assertEqual(res.status_code, 302)
  277. self.assertRedirects(res, '/detail/author/%d/' % a.pk)
  278. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
  279. def test_update_without_redirect(self):
  280. a = Author.objects.create(
  281. name='Randall Munroe',
  282. slug='randall-munroe',
  283. )
  284. # Should raise exception -- No redirect URL provided, and no
  285. # get_absolute_url provided
  286. with self.assertRaises(ImproperlyConfigured):
  287. self.client.post('/edit/author/%d/update/naive/' % a.pk,
  288. {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
  289. def test_update_get_object(self):
  290. a = Author.objects.create(
  291. pk=1,
  292. name='Randall Munroe',
  293. slug='randall-munroe',
  294. )
  295. res = self.client.get('/edit/author/update/')
  296. self.assertEqual(res.status_code, 200)
  297. self.assertIsInstance(res.context['form'], forms.ModelForm)
  298. self.assertIsInstance(res.context['view'], View)
  299. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  300. self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
  301. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  302. # Modification with both POST and PUT (browser compatible)
  303. res = self.client.post('/edit/author/update/',
  304. {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
  305. self.assertEqual(res.status_code, 302)
  306. self.assertRedirects(res, '/list/authors/')
  307. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])
  308. @override_settings(ROOT_URLCONF='generic_views.urls')
  309. class DeleteViewTests(TestCase):
  310. def test_delete_by_post(self):
  311. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  312. res = self.client.get('/edit/author/%d/delete/' % a.pk)
  313. self.assertEqual(res.status_code, 200)
  314. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  315. self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
  316. self.assertTemplateUsed(res, 'generic_views/author_confirm_delete.html')
  317. # Deletion with POST
  318. res = self.client.post('/edit/author/%d/delete/' % a.pk)
  319. self.assertEqual(res.status_code, 302)
  320. self.assertRedirects(res, '/list/authors/')
  321. self.assertQuerysetEqual(Author.objects.all(), [])
  322. def test_delete_by_delete(self):
  323. # Deletion with browser compatible DELETE method
  324. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  325. res = self.client.delete('/edit/author/%d/delete/' % a.pk)
  326. self.assertEqual(res.status_code, 302)
  327. self.assertRedirects(res, '/list/authors/')
  328. self.assertQuerysetEqual(Author.objects.all(), [])
  329. def test_delete_with_redirect(self):
  330. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  331. res = self.client.post('/edit/author/%d/delete/redirect/' % a.pk)
  332. self.assertEqual(res.status_code, 302)
  333. self.assertRedirects(res, '/edit/authors/create/')
  334. self.assertQuerysetEqual(Author.objects.all(), [])
  335. @ignore_warnings(category=RemovedInDjango110Warning)
  336. def test_delete_with_interpolated_redirect(self):
  337. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  338. res = self.client.post('/edit/author/%d/delete/interpolate_redirect/' % a.pk)
  339. self.assertEqual(res.status_code, 302)
  340. self.assertRedirects(res, '/edit/authors/create/?deleted=%d' % a.pk)
  341. self.assertQuerysetEqual(Author.objects.all(), [])
  342. # Also test with escaped chars in URL
  343. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  344. res = self.client.post('/edit/author/{}/delete/interpolate_redirect_nonascii/'.format(a.pk))
  345. self.assertEqual(res.status_code, 302)
  346. self.assertRedirects(res, '/%C3%A9dit/authors/create/?deleted={}'.format(a.pk))
  347. def test_delete_with_special_properties(self):
  348. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  349. res = self.client.get('/edit/author/%d/delete/special/' % a.pk)
  350. self.assertEqual(res.status_code, 200)
  351. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  352. self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
  353. self.assertNotIn('author', res.context)
  354. self.assertTemplateUsed(res, 'generic_views/confirm_delete.html')
  355. res = self.client.post('/edit/author/%d/delete/special/' % a.pk)
  356. self.assertEqual(res.status_code, 302)
  357. self.assertRedirects(res, '/list/authors/')
  358. self.assertQuerysetEqual(Author.objects.all(), [])
  359. def test_delete_without_redirect(self):
  360. a = Author.objects.create(
  361. name='Randall Munroe',
  362. slug='randall-munroe',
  363. )
  364. # Should raise exception -- No redirect URL provided, and no
  365. # get_absolute_url provided
  366. with self.assertRaises(ImproperlyConfigured):
  367. self.client.post('/edit/author/%d/delete/naive/' % a.pk)