0

我试图弄清楚如何在 django 中测试中间件。我正在编写的中间件在特定条件下(如果电子邮件中发送的密钥有效)登录用户。所以很明显我依赖于django.contrib.authand django.contrib.sessions

我在测试登录部分时遇到问题。我正在提出这样的请求:

user = User.objects.create_user('user', 'user@example.org', 'password')
key = LoginKey.objects.create(user=user)
request = self.factory.get('/', data={'auth_key': key.hash}) # self.factory is a RequestFactory()
self.middleware.process_request(request) # self.middleware is MyMiddleware()

由于未设置会话而失败。所以接下来,我在我的测试类中写了一个小片段:

def make_session(self, request):
    SessionMiddleware().process_request(request)

并且由于'User' object has no attribute 'backend'. 我不确定这意味着什么,但我怀疑我需要运行我安装的所有中间件。

我真的不想为了运行中间件而为此制作一个假视图,但此时我看不到另一个选项。

所以我只想知道,在我不得不一直追着这只兔子之前,有没有一种不需要那么多胶带的方法?

4

1 回答 1

1

You should use the test client for this. That will ensure that the middleware is run and the session keys created.

response = self.client.get('/?auth_key=%s' % key.hash)
self.assertTrue(response.context['user'].is_authenticated()) # for example
于 2011-06-22T19:36:05.623 回答