django-让用户登录到测试客户端 [英] django - get user logged into test client

查看:79
本文介绍了django-让用户登录到测试客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django书面测试中,如何获得当前登录用户?

In a written django test, how can I get the current logged in user?

例如,这是我要编写的测试:

For example this is the test I want to write:

def test_author_set_once(self):
    self.client.login(username='Adam', password='password')
    #create an object and test the author is adam
    self.client.login(username='Barry', password='password')
    #modify the first object and test that the author has not changed

所以我希望能够说类似...

So I want to be able to say something like...

self.assertEqual(object.author, self.client.user)

(但是我不能)

我目前的编码方式是这样的:

The way I've coded it at the moment is like this:

self.client.login(username='Adam', password='password')
self.user = User.objects.get(username='Adam')
#create an object 
self.assertEqual(object.author, self.user)

这取决于假设在request.user处与特定的用户对象相同。我想这还可以,但似乎有点笨拙。

This relies on the assumption that the request.user is the same as a particular user object. I guess it's OK but it seems a bit clunky.

是否有避免该假设的方法?

Is there anyway to avoid the assumption?

推荐答案

测试客户端与请求无关。它并不会固有地保留有关用户登录信息的信息。(出于明显的原因,您的实际Web服务器或Django开发服务器也都没有)。

The test client is request-agnostic. It doesn't inherently hold information about what users are logged in. (Neither does your actual webserver or the Django dev server, either, for obvious reasons, and those same reasons apply here).

login 只是测试客户端上的一种便捷方法,实际上是使用定义的用户模拟POST到 / login / 证书。

login is simply a convenience method on the test client to essentially mimic a POST to /login/ with the defined user credentials. Nothing more.

实际的用户可以在请求上使用,就像在视图中一样。但是,由于您没有直接访问视图的权限,因此Django会在视图的响应中提供请求。在实际使用测试客户端加载视图之后,可以存储结果,然后通过以下方式获取用户:

The actual user is available on the request just like in a view. However, since you don't have direct access to the view, Django makes request available on the view's response. After you actually use the test client to load a view, you can store the result and then get the user via:

response.request.user

最新版本的Django将使用:

More recent versions of Django will use:

response.wsgi_request.user

这篇关于django-让用户登录到测试客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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