测试时如何访问request.user? [英] How to access request.user while testing?

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

问题描述

我刚刚从Django 1.3.1迁移到Django 1.4。在这样做之后,真正大量的测试开始引发这些错误:

 追溯(最近的最后一次呼叫): 
文件/Volumes/Data/ADay/Website/Backend/(trunk)/project/tests/templatetags.py,第406行,setUp
self.context = template.RequestContext(self.request )
文件/Library/Python/2.6/site-packages/django/template/context.py,第176行,__init__
self.update(processor(request))
文件/Volumes/Data/ADay/Website/Backend/(trunk)/project/social_auth/context_processors.py,第21行,在social_auth_by_type_backends
data = backends_data(request.user)
AttributeError:'WSGIRequest '对象没有属性'user'

所有这些错误都是指django-social-auth上下文处理器,它尝试获取request.user来构建请求上下文:

  def social_auth_by_type_backends(request):
将Social Auth当前用户数据加载到上下文。
将在social_auth键下添加一个backends_data的输出到上下文,其中
每个条目将按后端类型(openid,oauth,oauth2)进行分组。

data = backends_data(request.user)
data ['backends'] = group_backend_by_type(data ['backends'])
data ['not_associated'] = group_backend_by_type(data ['not_associated'])
data ['associated'] = group_backend_by_type(data ['associated'],
key = lambda assoc:assoc.provider)
return {'social_auth ':data}

Django在构建请求上下文时是否将请求传递给函数?不要这么认为,现在社会认证团队的某个人可能会发现这样一个问题。



编辑:



我第一次以为这是一个不推荐使用的context_processor的问题,但是我检查过,他们应该是最新的:

  TEMPLATE_CONTEXT_PROCESSORS =(
'django.contrib.messages.context_processors.messages',
django.contrib.auth.context_processors.auth,
django .core.context_processors.debug,
django.core.context_processors.i18n,
django.core.context_processors.static,
django.contrib.messages.context_processors.messages ,
'django.core.context_processors.request',
'pages.context_processors.media',
'social_auth.context_processors.social_auth_by_type_backends',


MIDDLEWARE_CLASSES =(
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',

edit2:



好的,当网站继续工作时,可能是我的测试代码的问题。这里是:

  def setUp(self):
self.factory = RequestFactory()
#创建初始请求,包括会话数据
self.response = self.client.get('/')
self.request = self.factory.get(/)#any有效的url会做,我只需要一个请求
self.request.session = self.client.session

self.context = template.RequestContext(self.request)

最后一行然后引发错误。正如我在TestCase的setUp()函数中一样,它开始在我的测试中引发异常。为什么这不能在Django 1.4中工作?

解决方案

如果有人发现这一点:使用RequestFactory创建的请求似乎不返回当使用RequestContext(请求)时,即使安装了django.contrib.auth.context_processors.auth,request.user也是一个request.user。但是,在使用RequestContext(请求)之前,请自己传递一个用户请求。

 类SampleTestCase(TestCase):
fixtures = ['user_fixture.json']

def test_only_a_sample(self):
request.user = User.objects.get(pk = 1)
self.context = RequestContext(request)
#some tests here

这是最终为我工作的代码。


I just moved from Django 1.3.1 to Django 1.4. Right after doing so, a real big number of my tests started to raise these errors:

Traceback (most recent call last):
  File "/Volumes/Data/ADay/Website/Backend/(trunk)/project/tests/templatetags.py", line 406, in setUp
    self.context = template.RequestContext(self.request)
  File "/Library/Python/2.6/site-packages/django/template/context.py", line 176, in __init__
    self.update(processor(request))
  File "/Volumes/Data/ADay/Website/Backend/(trunk)/project/social_auth/context_processors.py", line 21, in social_auth_by_type_backends
    data = backends_data(request.user)
AttributeError: 'WSGIRequest' object has no attribute 'user'

All those errors refer to django-social-auth context processors, which tries to get request.user to build the request context:

def social_auth_by_type_backends(request):
    """Load Social Auth current user data to context.
    Will add a output from backends_data to context under social_auth key where
    each entry will be grouped by backend type (openid, oauth, oauth2).
    """
    data = backends_data(request.user)
    data['backends'] = group_backend_by_type(data['backends'])
    data['not_associated'] = group_backend_by_type(data['not_associated'])
    data['associated'] = group_backend_by_type(data['associated'],
    key=lambda assoc: assoc.provider)
    return {'social_auth': data}

Doesn't Django pass the request to the functions while building the request context? I don't think that's it, somebody of the social-auth team would probably have found such an issue by now.

edit:

I first thought it would be some issue with a deprecated context_processor, but i checked and they should all be up to date:

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.messages.context_processors.messages',
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.static",
    "django.contrib.messages.context_processors.messages",
    'django.core.context_processors.request',
    'pages.context_processors.media',
    'social_auth.context_processors.social_auth_by_type_backends',
    )

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

edit2:

Ok, as the site continues to work, this probably is a problem with my test code. Here it is:

def setUp(self):
    self.factory = RequestFactory()
    # create an initial request including session data        
    self.response = self.client.get('/')
    self.request = self.factory.get("/") #any valid url will do, i just need a request
    self.request.session = self.client.session

    self.context = template.RequestContext(self.request)

The last line is then provoking the error. As it is in the setUp() function of my TestCase, it starts to raise that exceptions all over my tests. Why is this not working in Django 1.4 anymore?

解决方案

In case somebody finds this: requests created with the RequestFactory appear not to return a request.user when using RequestContext(request) on them, even when "django.contrib.auth.context_processors.auth" is installed. But passing a user to the request yourself before using RequestContext(request) works fine:

class SampleTestCase(TestCase):
    fixtures = ['user_fixture.json']

    def test_only_a_sample(self):
        request.user = User.objects.get(pk=1)
        self.context = RequestContext(request)
        # some tests here

This is the code that finally worked for me.

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

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