Refs #20456 -- Moved initialization of HEAD method based on GET to the View.setup() for generic views.

This will ease unit testing of views since setup will essentially do
everything needed to set the view instance up (other than instantiating
it). Credit for idea goes to Vincent Prouillet.
This commit is contained in:
Felipe Lee 2019-10-10 00:22:43 -05:00 committed by Mariusz Felisiak
parent 31d1822532
commit c2c27867ef
4 changed files with 12 additions and 7 deletions

View File

@ -286,6 +286,7 @@ answer newbie questions, and generally made Django that much better:
favo@exoweb.net
fdr <drfarina@gmail.com>
Federico Capoano <nemesis@ninux.org>
Felipe Lee <felipe.lee.garcia@gmail.com>
Filip Noetzel <http://filip.noetzel.co.uk/>
Filip Wasilewski <filip.wasilewski@gmail.com>
Finn Gruwier Larsen <finn@gruwier.dk>

View File

@ -60,8 +60,6 @@ class View:
def view(request, *args, **kwargs):
self = cls(**initkwargs)
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.setup(request, *args, **kwargs)
if not hasattr(self, 'request'):
raise AttributeError(
@ -82,6 +80,8 @@ class View:
def setup(self, request, *args, **kwargs):
"""Initialize attributes shared by all view methods."""
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs

View File

@ -79,12 +79,9 @@ MRO is an acronym for Method Resolution Order.
.. method:: setup(request, *args, **kwargs)
Initializes view instance attributes: ``self.request``, ``self.args``,
and ``self.kwargs`` prior to :meth:`dispatch`.
Performs key view initialization prior to :meth:`dispatch`.
Overriding this method allows mixins to setup instance attributes for
reuse in child classes. When overriding this method, you must call
``super()``.
If overriding this method, you must call ``super()``.
.. method:: dispatch(request, *args, **kwargs)

View File

@ -113,6 +113,13 @@ class ViewTest(SimpleTestCase):
response = SimpleView.as_view()(self.rf.head('/'))
self.assertEqual(response.status_code, 200)
def test_setup_get_and_head(self):
view_instance = SimpleView()
self.assertFalse(hasattr(view_instance, 'head'))
view_instance.setup(self.rf.get('/'))
self.assertTrue(hasattr(view_instance, 'head'))
self.assertEqual(view_instance.head, view_instance.get)
def test_head_no_get(self):
"""
Test a view which supplies no GET method responds to HEAD with HTTP 405.