简体   繁体   English

运行测试用例时,Django的user_logged_in信号不起作用

[英]Django's user_logged_in signal not working when running a test case

I have this signal: 我有这个信号:

@receiver(user_logged_in)
def on_user_login(sender, request, **kwargs):
    if request.user.is_superuser:

It all works when running the app. 运行该应用程序时,所有方法均有效。 But when testing, this piece of code fails: 但是在测试时,这段代码失败了:

self.client.force_login(...)

The test fails with: 测试失败并显示:

AttributeError: HttpRequest object has no attribute user AttributeError: HttpRequest对象没有属性用户

If I remove the signal, that test case runs just fine. 如果我删除信号,则该测试用例运行良好。

I have Django 1.10 我有Django 1.10

In my test I was testing one of the admin views. 在测试中,我正在测试其中一个管理员视图。 I wanted to login the user first before doing this change. 我想先进行登录,然后再进行更改。 What I did not realize was that I really wanted to test just the admin view, not logging in. 我没有意识到的是,我真的只想测试管理员视图,而不是登录。

So instead of using client for testing, I used RequestFactory and passed the user in it. 因此,我没有使用客户端进行测试,而是使用RequestFactory并在其中传递了用户。 No logging in necessary. 无需登录。

The original error was due to the fact that client in django tests does not add the user to the request. 原始错误是由于django测试中的client未将用户添加到请求中这一事实造成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM