Rails 有一个断言,可以在执行块后测试值的差异。从这里:
assert_difference 'Article.count', 1 do
post :create, article: {...}
end
该断言将执行创建后命令,并测试Article.count
在执行该块后是否增加了 1。
Python 或 Django 中是否有类似的断言?如果不是,最有效的实现是否只是存储数字,然后再获取它?
Rails 有一个断言,可以在执行块后测试值的差异。从这里:
assert_difference 'Article.count', 1 do
post :create, article: {...}
end
该断言将执行创建后命令,并测试Article.count
在执行该块后是否增加了 1。
Python 或 Django 中是否有类似的断言?如果不是,最有效的实现是否只是存储数字,然后再获取它?
这基本上做同样的事情。
pre_count = Article.objects.count()
# Your Logic
post_count = Article.objects.count()
self.assertEqual(post_count-pre_count, 1)
或者,对于那种额外的红宝石调味剂,
from django.utils.decorators import method_decorator
from contextlib import contextmanager
def ExtendedTestCase(TestCase):
@method_decorator(context_manager)
def assertDifference(self, func, diff, message=None):
" A Context Manager that performs an assert. "
old_value = func()
yield # `with` statement runs here. Roughly equivalent to ruby's blocks
new_value = func()
self.assertEqual(new_value-old_value, diff, message)
def ArticleTestCase(ExtendedTestCase):
def test_article_creation(self):
" Test that new articles can be created "
with self.assertDifference(Article.count, 1):
self.client.post("/article/new/", {
"title": "My First Django Article",
"content": "Boring Technical Content",
})