在单元测试中将kwargs传递给基于类的视图

时间:2017-06-02 10:36:32

标签: python django unit-testing testing

我有这样的测试:

def test_getting_delete_view_invokes_point_changes_and_returns_status_200(self, point_changes):
        request = RequestFactory().get(reverse('questions:delete-help', kwargs={'pk': 1}))
        view = DeleteHelp.as_view()
        view.kwargs['pk'] = 1
        response = view(request)

我的观点功能:

class DeleteHelp(DeleteView, LoginRequiredMixin):

    model = Help
    template_name = 'confirm_deletion.html'

    def get_object(self, queryset=None):
        return get_object_or_404(Help, pk=self.kwargs['pk'], author=self.request.user)

    def get_success_url(self):
        point_pk = self.object.answer_to.plan_point.point_of.id
        point_changes(point_obj=self.object.answer_to.plan_point)
        return reverse('plans:display-public', args=[point_pk])

问题是,我该如何通过' pk'那里?我在get_object方法中不断收到错误KeywordError 'pk'。如果我使用self.client访问此视图然后它可以工作(为什么?),但我想使用RequestFactory。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

调用视图时传递它。

view = DeleteHelp.as_view()
response = view(request, pk=1)