我可以在没有测试客户端的情况下访问测试视图的响应上下文吗?

mar*_*rue 9 django django-views django-testing

我有一个函数,我从unittest调用.从设置一些调试跟踪,我知道该功能像魅力一样工作,并具有正确准备返回的所有值.

这就是我的testcode的样子(请参阅我的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')
Run Code Online (Sandbox Code Playgroud)

根据我从Django文档的这一部分所知,当我使用测试客户端时,我将能够访问response.context.但是当我尝试访问response.context就像我做的那样,我得到了这个:

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

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

jlo*_*son 10

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

如果要测试上下文,则应使用测试客户端.您仍然可以使用模拟操作在测试客户端中构建请求,或者只是在测试中提前保存会话,例如:

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

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


F.T*_*amy 5

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

  • 你被否决了,但这是正确的。`response.context` 是一个 `ContextList` 对象,而 `response.context_data` 是一个结构类似于传递给模板的 `Context` 实例的字典。 (2认同)

sta*_*nka -6

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

response = client.get('/fobarbaz/')
response.context
Run Code Online (Sandbox Code Playgroud)

  • 不,这不对。会话是存储在服务器端的某个用户的信息,请求是客户端向服务器发送请求服务器响应的信息。响应上下文(我要求的)仅用于测试,并包含有关服务器如何创建响应的信息(即使用了哪些模板)。它与请求上下文不同,与会话不同。 (2认同)