您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 如何在单元测试期间在Django RequestFactory中设置消息传递和会话中间件

5b51 2022/1/14 8:22:20 python 字数 2343 阅读 555 来源 www.jb51.cc/python

我有一个我需要测试的函数,它需要一个请求作为它的参数.它不是通过URL显示为视图,因此我无法使用测试客户端进行测试. 我需要传递请求对象,并且请求对象需要启用消息传递中间件,因为在该功能中使用消息传递中间件. 我正在使用RequestFactory来创建我的请求. documentation说: It does not support middleware. Session and authent

概述

我需要传递请求对象,并且请求对象需要启用消息传递中间件,因为在该功能中使用消息传递中间件.

我正在使用RequestFactory来创建我的请求. documentation说:

It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.

如何使用RequestFactory设置邮件中间件?我想我也需要会话中间件来使消息中间件工作

这是我当前使用香草RequestFactory时测试的错误.

MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware

这是我正在测试的功能,以防它有助于理解这个问题:

from django.contrib import messages as django_messages

def store_to_request(self,request):
        """
        Place all the messages stored in this class into message storage in
        the request object supplied.
        :param request: The request object to which we should store all the messages
        :return: Does not return anything
        """
        for message in self._messages:
            django_messages.add_message(request,message.level,message.message,message.extra_tags,message.fail_silently)
from django.contrib.messages.storage.fallback import FallbackStorage
setattr(request,'session','session')
messages = FallbackStorage(request)
setattr(request,'_messages',messages)

总结

以上是编程之家为你收集整理的python – 如何在单元测试期间在Django RequestFactory中设置消息传递和会话中间件全部内容,希望文章能够帮你解决python – 如何在单元测试期间在Django RequestFactory中设置消息传递和会话中间件所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶