为Django View get_context_data()方法编写测试

时间:2018-03-09 11:34:48

标签: django django-views django-testing

我正在为View编写测试,我在其中更新上下文以将其他信息传递给模板。

问题

在编写测试时,我无法从RequestFactory访问上下文。

代码

视图

class PlanListView(HasBillingRightsMixin, ListView):
    """Show the Plans for user to select."""

    headline = "Select a Plan"
    model = Plan
    template_name = "billing/plan_list.html"

    def get_context_data(self, *args, **kwargs):
        context = super(PlanListView, self).get_context_data(**kwargs)
        context.update({
            "customer": self.get_customer()
        })
        return context

测试

class TestPlanListView(BaseTestBilling):

    def setUp(self):
        super(TestPlanListView, self).setUp()
        request = self.factory.get('billing:plan_list')
        request.user = self.user
        request.company_uuid = self.user.company_uuid

        self.view = PlanListView()
        self.view.request = request
        self.response = PlanListView.as_view()(request)

    def test_get_context_data(self, **kwargs):
        context = super(self.view, self).get_context_data(**kwargs)
        context.update({"customer": self.view.get_customer()})
        self.assertEqual(
            self.view.get_context_data(),
            context
        )

问题

如何测试视图的get_context_data()方法?

2 个答案:

答案 0 :(得分:4)

使用test client可以访问您的上下文。

def test_context(self):
    # GET response using the test client.
    response = self.client.get('/list/ofitems/')
    # response.context['your_context']
    self.assertIsNone(response.context['page_obj'])
    self.assertIsNone(response.context['customer']) # or whatever assertion.
    .....

答案 1 :(得分:1)

如果您不想测试完整的浏览器行为,则可以改用RequestFactory。该工厂提供了一个请求实例,您可以将其传递给视图。对于我来说,这样做的好处是,我可以使用完全已知的输入来测试作为黑盒的单个视图函数,并测试特定的输出。就像文档中所述。

class TestView(TemplateView):
    template_name = 'base.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context = {'1': 11337}
        return context

# ...
def test_context(self):
    factory = RequestFactory()
    request = factory.get('/customer/details')
    response = TestView.as_view()(request)
    self.assertIsInstance(response.context_data, dict)
    self.assertEqual(response.context_data['1'], 1337)