如何对 django 消息进行单元测试?
在我的 django 应用程序中,我尝试编写一个单元测试来执行操作,然后检查响应中的消息。
据我所知,没有什么好的方法可以做到这一点。
我正在使用 CookieStorage 存储方法,我想做类似以下的事情:
response = self.client.post('/do-something/', follow=True)
self.assertEquals(response.context['messages'][0], "fail.")
问题是,我得到的只是一个
print response.context['messages']
<django.contrib.messages.storage.cookie.CookieStorage object at 0x3c55250>
如何将其变成有用的东西,或者我做的都是错的?
谢谢, 丹尼尔
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.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我发现了一个非常简单的方法:
如果您需要检查没有上下文的响应上的消息,您可以使用以下内容:
后备存储不支持索引,但它是可迭代的。
I found a really easy approach:
If you need to check for messages on a response that has no context you can use the following:
The fallback storage doesn't support indexing, however it is an iterable.
来自 django 文档:
因此,您可以编写如下内容:
From django documentation:
So, you could write something like:
这对我有用(显示所有消息):
另外,这里还有一些我在继承自 Django 的 TestCase 的测试类中的实用方法。如果您希望将它们作为函数,请删除
self
参数并将self.fail()
替换为raise
。This works for me (displays all messages):
Also here are a couple of utility methods I have in a test class inherited from Django's TestCase. If you'd prefer to have them as functions, remove the
self
arguments and replaceself.fail()
's with araise
.更新
我原来的答案是在 django 还是 1.1 左右的时候写的。这个答案不再相关。请参阅 @daveoncode 的答案以获得更好的解决方案。
原始答案
我做了一个实验来测试这一点。我将一个项目中的
MESSAGE_STORAGE
设置更改为'django.contrib.messages.storage.cookie.CookieStorage'
并执行了我编写的用于检查消息的测试。它起作用了。与您所做的主要区别在于我检索消息的方式。请参阅下文:
这可能值得一试。
Update
My original answer was written when django was still 1.1 or so. This answer is no longer relevant. See @daveoncode's answer for a better solution.
Original Answer
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:
This may be worth a try.
我创建了一个 python 类来简化消息测试:
在测试函数中:
I created a python class to simplify messages testing :
And in test function :
僵局的更简单版本:
Simpler version of the stalemate one:
测试助手用于验证响应消息计数和内容
可以像这样使用
Test helpers for validation of response messages count and content
Can be used like this