测试Django时访问request.user对象 [英] Accessing the request.user object when testing Django

查看:483
本文介绍了测试Django时访问request.user对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用django的客户端类测试我的应用时,我试图访问request.user对象.

I'm trying to access the request.user object when testing my app using django's client class.

from django.test import TestCase
from django.test.client import Client

class SomeTestCase(TestCase):

    def setUp(self):
        self.client = Client()
        self.client.login( username="foo", password="bar")

    def test_one(self):
        response = self.client.get("/my_profile/")
        self.fail( response.request.user )

这显然会失败,但是会失败,因为response.request没有用户属性.

This will obviously fail, but it fails because response.request doesn't have a user attribute.

AttributeError: 'dict' object has no attribute 'user'

有什么方法可以从客户端实例访问用户对象?我要这样做是为了检查某些测试用户的数据是否正确呈现.我可以尝试通过在设置过程中设置所有必要的信息来解决此问题,但是在执行此操作之前,我想检查一下我是否不仅缺少某些内容.

Is there any way to access the user object from the client instance? I want to do this in order to check if some test user's data is properly rendered. I can try to tackle this by setting up all the necessary info during setUp, but before I do that I wanted to check if I'm not just missing something.

推荐答案

使用response.context['user'].

用户在模板上下文中自动可用.请参阅模板中的身份验证数据文档.

User is automatically available in the template context if you use RequestContext. See auth data in templates doc.

否则,我相信您应该查询它:

Otherwise i believe you should just query it:

 def test_one(self):
    response = self.client.get("/my_profile/")
    user = User.objects.get(username="foo")
    self.fail( user.some_field == False )

这篇关于测试Django时访问request.user对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆