base.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import time
  2. import unittest
  3. from django.core.exceptions import ImproperlyConfigured
  4. from django.http import HttpResponse
  5. from django.test import TestCase, RequestFactory
  6. from django.utils import simplejson
  7. from django.views.generic import View, TemplateView, RedirectView
  8. class SimpleView(View):
  9. """
  10. A simple view with a docstring.
  11. """
  12. def get(self, request):
  13. return HttpResponse('This is a simple view')
  14. class SimplePostView(SimpleView):
  15. post = SimpleView.get
  16. class CustomizableView(SimpleView):
  17. parameter = {}
  18. def decorator(view):
  19. view.is_decorated = True
  20. return view
  21. class DecoratedDispatchView(SimpleView):
  22. @decorator
  23. def dispatch(self, request, *args, **kwargs):
  24. return super(DecoratedDispatchView, self).dispatch(request, *args, **kwargs)
  25. class AboutTemplateView(TemplateView):
  26. def get(self, request):
  27. return self.render_to_response({})
  28. def get_template_names(self):
  29. return ['generic_views/about.html']
  30. class AboutTemplateAttributeView(TemplateView):
  31. template_name = 'generic_views/about.html'
  32. def get(self, request):
  33. return self.render_to_response(context={})
  34. class InstanceView(View):
  35. def get(self, request):
  36. return self
  37. class ViewTest(unittest.TestCase):
  38. rf = RequestFactory()
  39. def _assert_simple(self, response):
  40. self.assertEqual(response.status_code, 200)
  41. self.assertEqual(response.content, 'This is a simple view')
  42. def test_no_init_kwargs(self):
  43. """
  44. Test that a view can't be accidentally instantiated before deployment
  45. """
  46. try:
  47. view = SimpleView(key='value').as_view()
  48. self.fail('Should not be able to instantiate a view')
  49. except AttributeError:
  50. pass
  51. def test_no_init_args(self):
  52. """
  53. Test that a view can't be accidentally instantiated before deployment
  54. """
  55. try:
  56. view = SimpleView.as_view('value')
  57. self.fail('Should not be able to use non-keyword arguments instantiating a view')
  58. except TypeError:
  59. pass
  60. def test_pathological_http_method(self):
  61. """
  62. The edge case of a http request that spoofs an existing method name is caught.
  63. """
  64. self.assertEqual(SimpleView.as_view()(
  65. self.rf.get('/', REQUEST_METHOD='DISPATCH')
  66. ).status_code, 405)
  67. def test_get_only(self):
  68. """
  69. Test a view which only allows GET doesn't allow other methods.
  70. """
  71. self._assert_simple(SimpleView.as_view()(self.rf.get('/')))
  72. self.assertEqual(SimpleView.as_view()(self.rf.post('/')).status_code, 405)
  73. self.assertEqual(SimpleView.as_view()(
  74. self.rf.get('/', REQUEST_METHOD='FAKE')
  75. ).status_code, 405)
  76. def test_get_and_post(self):
  77. """
  78. Test a view which only allows both GET and POST.
  79. """
  80. self._assert_simple(SimplePostView.as_view()(self.rf.get('/')))
  81. self._assert_simple(SimplePostView.as_view()(self.rf.post('/')))
  82. self.assertEqual(SimplePostView.as_view()(
  83. self.rf.get('/', REQUEST_METHOD='FAKE')
  84. ).status_code, 405)
  85. def test_invalid_keyword_argument(self):
  86. """
  87. Test that view arguments must be predefined on the class and can't
  88. be named like a HTTP method.
  89. """
  90. # Check each of the allowed method names
  91. for method in SimpleView.http_method_names:
  92. kwargs = dict(((method, "value"),))
  93. self.assertRaises(TypeError, SimpleView.as_view, **kwargs)
  94. # Check the case view argument is ok if predefined on the class...
  95. CustomizableView.as_view(parameter="value")
  96. # ...but raises errors otherwise.
  97. self.assertRaises(TypeError, CustomizableView.as_view, foobar="value")
  98. def test_calling_more_than_once(self):
  99. """
  100. Test a view can only be called once.
  101. """
  102. request = self.rf.get('/')
  103. view = InstanceView.as_view()
  104. self.assertNotEqual(view(request), view(request))
  105. def test_class_attributes(self):
  106. """
  107. Test that the callable returned from as_view() has proper
  108. docstring, name and module.
  109. """
  110. self.assertEqual(SimpleView.__doc__, SimpleView.as_view().__doc__)
  111. self.assertEqual(SimpleView.__name__, SimpleView.as_view().__name__)
  112. self.assertEqual(SimpleView.__module__, SimpleView.as_view().__module__)
  113. def test_dispatch_decoration(self):
  114. """
  115. Test that attributes set by decorators on the dispatch method
  116. are also present on the closure.
  117. """
  118. self.assertTrue(DecoratedDispatchView.as_view().is_decorated)
  119. class TemplateViewTest(TestCase):
  120. urls = 'regressiontests.generic_views.urls'
  121. rf = RequestFactory()
  122. def _assert_about(self, response):
  123. response.render()
  124. self.assertEqual(response.status_code, 200)
  125. self.assertContains(response, '<h1>About</h1>')
  126. def test_get(self):
  127. """
  128. Test a view that simply renders a template on GET
  129. """
  130. self._assert_about(AboutTemplateView.as_view()(self.rf.get('/about/')))
  131. def test_get_template_attribute(self):
  132. """
  133. Test a view that renders a template on GET with the template name as
  134. an attribute on the class.
  135. """
  136. self._assert_about(AboutTemplateAttributeView.as_view()(self.rf.get('/about/')))
  137. def test_get_generic_template(self):
  138. """
  139. Test a completely generic view that renders a template on GET
  140. with the template name as an argument at instantiation.
  141. """
  142. self._assert_about(TemplateView.as_view(template_name='generic_views/about.html')(self.rf.get('/about/')))
  143. def test_template_name_required(self):
  144. """
  145. A template view must provide a template name
  146. """
  147. self.assertRaises(ImproperlyConfigured, self.client.get, '/template/no_template/')
  148. def test_template_params(self):
  149. """
  150. A generic template view passes kwargs as context.
  151. """
  152. response = self.client.get('/template/simple/bar/')
  153. self.assertEqual(response.status_code, 200)
  154. self.assertEqual(response.context['params'], {'foo': 'bar'})
  155. def test_extra_template_params(self):
  156. """
  157. A template view can be customized to return extra context.
  158. """
  159. response = self.client.get('/template/custom/bar/')
  160. self.assertEqual(response.status_code, 200)
  161. self.assertEqual(response.context['params'], {'foo': 'bar'})
  162. self.assertEqual(response.context['key'], 'value')
  163. def test_cached_views(self):
  164. """
  165. A template view can be cached
  166. """
  167. response = self.client.get('/template/cached/bar/')
  168. self.assertEqual(response.status_code, 200)
  169. time.sleep(1.0)
  170. response2 = self.client.get('/template/cached/bar/')
  171. self.assertEqual(response2.status_code, 200)
  172. self.assertEqual(response.content, response2.content)
  173. time.sleep(2.0)
  174. # Let the cache expire and test again
  175. response2 = self.client.get('/template/cached/bar/')
  176. self.assertEqual(response2.status_code, 200)
  177. self.assertNotEqual(response.content, response2.content)
  178. class RedirectViewTest(unittest.TestCase):
  179. rf = RequestFactory()
  180. def test_no_url(self):
  181. "Without any configuration, returns HTTP 410 GONE"
  182. response = RedirectView.as_view()(self.rf.get('/foo/'))
  183. self.assertEqual(response.status_code, 410)
  184. def test_permanaent_redirect(self):
  185. "Default is a permanent redirect"
  186. response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/'))
  187. self.assertEqual(response.status_code, 301)
  188. self.assertEqual(response['Location'], '/bar/')
  189. def test_temporary_redirect(self):
  190. "Permanent redirects are an option"
  191. response = RedirectView.as_view(url='/bar/', permanent=False)(self.rf.get('/foo/'))
  192. self.assertEqual(response.status_code, 302)
  193. self.assertEqual(response['Location'], '/bar/')
  194. def test_include_args(self):
  195. "GET arguments can be included in the redirected URL"
  196. response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/'))
  197. self.assertEqual(response.status_code, 301)
  198. self.assertEqual(response['Location'], '/bar/')
  199. response = RedirectView.as_view(url='/bar/', query_string=True)(self.rf.get('/foo/?pork=spam'))
  200. self.assertEqual(response.status_code, 301)
  201. self.assertEqual(response['Location'], '/bar/?pork=spam')
  202. def test_parameter_substitution(self):
  203. "Redirection URLs can be parameterized"
  204. response = RedirectView.as_view(url='/bar/%(object_id)d/')(self.rf.get('/foo/42/'), object_id=42)
  205. self.assertEqual(response.status_code, 301)
  206. self.assertEqual(response['Location'], '/bar/42/')