加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何在单元测试期间在Django RequestFactory中设置消

发布时间:2020-12-16 23:04:13 所属栏目:Python 来源:网络整理
导读:我有一个我需要测试的函数,它需要一个请求作为它的参数.它不是通过URL显示为视图,因此我无法使用测试客户端进行测试. 我需要传递请求对象,并且请求对象需要启用消息传递中间件,因为在该功能中使用消息传递中间件. 我正在使用RequestFactory来创建我的请求. d
我有一个我需要测试的函数,它需要一个请求作为它的参数.它不是通过URL显示为视图,因此我无法使用测试客户端进行测试.

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

我正在使用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)

解决方法

这个问题 was raised,就这样说,你可以使用该代码修复你的单元测试:
from django.contrib.messages.storage.fallback import FallbackStorage
setattr(request,'session','session')
messages = FallbackStorage(request)
setattr(request,'_messages',messages)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读