Why don't my Django unittests know that MessageMiddleware is installed?

前端 未结 9 724
傲寒
傲寒 2020-12-14 05:54

I\'m working on a Django project and am writing unittests for it. However, in a test, when I try and log a user in, I get this error:

MessageFailure: You can         


        
9条回答
  •  旧时难觅i
    2020-12-14 06:28

    In my case (django 1.8) this problem occurs in when unit-test calls signal handler for user_logged_in signal, looks like messages app has not been called, i.e. request._messages is not yet set. This fails:

    from django.contrib.auth.signals import user_logged_in
    ...
    
    @receiver(user_logged_in)
    def user_logged_in_handler(sender, user, request, **kwargs):
    
        ...
        messages.warning(request, "user has logged in")
    

    the same call to messages.warning in normal view function (that is called after) works without any issues.

    A workaround I based on one of the suggestions from https://code.djangoproject.com/ticket/17971, use fail_silently argument only in signal handler function, i.e. this solved my problem:

    messages.warning(request, "user has logged in",
                     fail_silently=True )
    

提交回复
热议问题