4

我刚从 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 在构建请求上下文时不会将请求传递给函数吗?我不认为是这样,social-auth 团队的某个人现在可能已经发现了这样的问题。

编辑:

我首先认为不推荐使用的 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',
)

编辑2:

好的,随着站点继续工作,这可能是我的测试代码的问题。这里是:

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 中工作了?

4

2 回答 2

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
于 2012-04-11T19:50:54.933 回答
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
于 2019-04-10T20:24:20.687 回答