相关疑难解决方法(0)

django - 让用户登录测试客户端

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

例如,这是我想写的测试:

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
Run Code Online (Sandbox Code Playgroud)

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

self.assertEqual(object.author, self.client.user)
Run Code Online (Sandbox Code Playgroud)

(但我不能)

我此刻编码的方式是这样的:

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

这依赖于request.user与特定用户对象相同的假设.我想这没关系,但看起来有点笨重.

反正有没有避免这个假设?

testing django

23
推荐指数
4
解决办法
2万
查看次数

标签 统计

django ×1

testing ×1