How TDD can be applied to Django Class based Generic Views?

前端 未结 3 1794
误落风尘
误落风尘 2021-02-02 10:13

Since Class based Generic Views in Django involve some work by the framework I find very hard to work with them in a TDD style. Now I use the TestClient to access the view from

3条回答
  •  醉酒成梦
    2021-02-02 10:57

    I was looking for a simple solution for the same issue today and found this really great blog-post by Benoît Bryon (thanks!).

    He suggested the following function:

    def setup_view(view, request, *args, **kwargs):
        """Mimic as_view() returned callable, but returns view instance.
    
        args and kwargs are the same you would pass to ``reverse()``
    
        """
        view.request = request
        view.args = args
        view.kwargs = kwargs
        return view
    

    Example

    I wanted to test the following CBV:

    class CreateList(CreateView):
        model = Item
        form_class = NewListForm
        template_name = 'lists/home_page.html'
    
        def form_valid(self, form):
            list_ = form.save(owner=self.request.user)
            return redirect(list_)
    

    The necessary tests are for the form.save method arguments and for the redirect arguments, which should be the return value of the former. These tests will look something like:

        class CreateListTest(unittest.TestCase):
    
            def setUp(self):
                self.request = HttpRequest()
                self.request.user = Mock()
                self.form = Mock()
                self.view = setup_view(views.CreateList(), self.request)
    
            def test_form_dot_save_called_with_user(self):
                self.view.form_valid(self.form)
                self.form.save.assert_called_once_with(owner=self.request.user)
    
            @patch('lists.views.redirect')
            def test_redirect(self, mock_redirect):
                self.view.form_valid(self.form)
                mock_redirect.assert_called_once_with(self.form.save.return_value)
    

提交回复
热议问题