【问题标题】:Can i access the response context of a view tested without the test client?我可以在没有测试客户端的情况下访问测试视图的响应上下文吗?
【发布时间】:2012-04-26 05:52:55
【问题描述】:

我有一个从单元测试调用的函数。通过设置一些调试跟踪,我知道该函数像一个魅力一样工作,并且所有值都正确准备好返回。

这就是我的测试代码的样子(看看我的 ipdb.set_trace() 在哪里):

@override_settings(REGISTRATION_OPEN=True)
def test_confirm_account(self):
    """ view that let's a user confirm account creation and username
        when loggin in with social_auth """    
    request = self.factory.get('')
    request.user = AnonymousUser()
    request.session={}
    request.session.update({self.pipename:{'backend':'facebook',
                                           'kwargs':{'username':'Chuck Norris','response':{'id':1}}}})

    # this is the function of which i need the context:
    response = confirm_account(request)
    self.assertEqual(response.context['keytotest'],'valuetotest')

据我从this part of the Django docs 了解到的,当我使用测试客户端时,我将能够访问 response.context。但是当我尝试像我那样访问 response.context 时,我得到了这个:

AttributeError: 'HttpResponse' 对象没有属性 'context'

有没有办法在不使用客户端的情况下获取客户端的特殊HttpResponse对象?

【问题讨论】:

    标签: django django-views django-testing


    【解决方案1】:

    RequestFactory 不涉及 Django 中间件,因此,您不会生成上下文(即没有 ContextManager 中间件)。

    如果你想测试上下文,你应该使用测试客户端。您仍然可以在测试客户端中使用 mock 或简单地在测试中提前保存会话来操纵请求的构造,例如:

    from django.test import Client
    c = Client()
    session = c.session
    session['backend'] = 'facebook'
    session['kwargs'] = {'username':'Chuck Norris','response':{'id':1}}
    session.save()
    

    现在,当您使用测试客户端加载视图时,您将使用您设置的会话,当您使用 response = c.get('/yourURL/') 时,您可以根据需要使用 response.context 引用响应上下文。

    【讨论】:

      【解决方案2】:

      “response.context”对于新的 django 版本不正确,但您可以使用 response.context_data 来获取传递给 TemplateResponse 的相同上下文。

      【讨论】:

      • 你被否决了,但这是正确的。 response.context 是一个 ContextList 对象,而 response.context_data 是一个字典,其结构类似于传递给模板的 Context 实例。
      【解决方案3】:

      虽然这是一篇旧帖子,但我想这个提示可能会有所帮助。你可以考虑使用TemplateResponse(或SimpleTemplateResponse),它可以代替render或render_to_response。

      Django docs 对此有更多了解

      【讨论】:

        【解决方案4】:

        是的,你可以。你必须修补渲染。

        我正在使用 pytest-django

        class Test:
            def context(self, call_args):
                args, kwargs = call_args
                request_mock, template, context = args
                return context
        
            @patch('myapplication.views.render')
            def test_(self, mock_render, rf):
                request = rf.get('fake-url')
                view(request)
                context = self.context(mock_render.call_args)
        
                keytotest = 'crch'
                assert keytotest == context['keytotest']
        

        【讨论】:

          【解决方案5】:

          context(原文如此!)可以在 Response 类中找到。如您所见,它是 HTTP您从视图函数返回的响应。发生这种情况是因为您直接调用了它。通过测试客户端调用这个函数就可以了。

          response = client.get('/fobarbaz/')
          response.context
          

          【讨论】:

          • 通过测试客户端调用它并不能让我完全控制请求的构建。我明确询问是否有可能没有客户。
          • 我在测试中使用内置客户端操作会话(查看 client.session)。这就是你所说的请求构造控制吗?如果是这样,请重新考虑您的反对意见。
          • 不,不是。会话是存储在服务器端的某个用户的信息,请求是客户端发送到服务器以请求服务器响应的内容。响应上下文(我要求的)仅用于测试并包含有关服务器如何创建响应的信息(即已使用哪些模板)。它与请求上下文不同,与会话不同。
          猜你喜欢
          • 2019-12-17
          • 1970-01-01
          • 2011-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-01
          • 1970-01-01
          相关资源
          最近更新 更多