如何在测试时访问request.user?

时间:2012-04-10 18:56:14

标签: django django-testing django-socialauth

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

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'

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

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}

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()
    # 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)

然后最后一行引发了错误。因为它在我的TestCase的setUp()函数中,它开始在我的测试中引发异常。为什么这不再适用于Django 1.4?

2 个答案:

答案 0 :(得分:2)

如果有人发现这一点:使用RequestFactory创建的请求似乎在对它们使用RequestContext(request)时不返回request.user,即使安装了“django.contrib.auth.context_processors.auth”也是如此。但在使用RequestContext(request)之前将用户自己传递给请求可以正常工作:

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

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

编辑:请求可以通过,

使用
from django.test.client import RequestFactory 

# code suppressed 
def setUp(self):
    self.factory = RequestFactory()

并用于

def test_only_a_sample(self):
    request = self.factory.get('/')        # or any other methods
    request.user = User.objects.get(pk=1)
# code follows

答案 1 :(得分:0)

我需要一个经过身份验证的用户来测试特权视图。我需要在响应中返回上下文。 RequestFactory可以工作,但它会获得一个不包含上下文的HttpReponse。

这就是我所做的并且有效。

class MyTestCase(TestCase):
    def setUp(self):
        self.client.login(username='user@myorg.com', password='Secret')

    def test_create_event(self):
        print("Testing create...")
        response = self.client.post('/event/new_event/', form_data_dict)
        self.assertEqual(response.status_code, 200)
        event_id = response.context['event'].event_id