我如何单元测试django消息? [英] How can I unit test django messages?

查看:140
本文介绍了我如何单元测试django消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django应用程序中,我正在尝试编写一个单元测试,执行一个操作,然后检查响应中的消息。

In my django application, I'm trying to write a unit test that performs an action and then checks the messages in the response.

据我所知,没有什么好办法。

As far as I can tell, there is no nice way of doing this.

我正在使用CookieStorage存储方法,我想做以下类似的操作:

I'm using the CookieStorage storage method, and I'd like to do something similar to the following:

    response = self.client.post('/do-something/', follow=True)
    self.assertEquals(response.context['messages'][0], "fail.")

问题是,我回来的是一个

The problem is, all I get back is a

print response.context['messages']
<django.contrib.messages.storage.cookie.CookieStorage object at 0x3c55250>

如何将其变成有用的东西,或者我做错了?

How can I turn this into something useful, or am I doing it all wrong?

谢谢,
丹尼尔

Thanks, Daniel

推荐答案

我做了一个实验来测试。我将我的一个项目中的 MESSAGE_STORAGE 设置更改为'django.contrib.messages.storage.cookie.CookieStorage'并执行了我已经写的检查消息的测试。有效。

I did an experiment to test this. I changed the MESSAGE_STORAGE setting in one of my projects to 'django.contrib.messages.storage.cookie.CookieStorage' and executed a test that I had written to check for messages. It worked.

与您正在进行的主要区别是我检索邮件的方式。见下文:

The key difference from what you were doing is the way I retrieved messages. See below:

def test_message_sending(self):
    data = dict(...)
    response = self.client.post(reverse('my_view'), data)
    messages = self.user.get_and_delete_messages()

    self.assertTrue(messages)
    self.assertEqual('Hey there!', messages[0])

这个可能值得一试。

这篇关于我如何单元测试django消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆