Rails有一个断言,用于在执行块后测试值的差异。来自here:
assert_difference 'Article.count', 1 do
post :create, article: {...}
end
此断言将执行创建后命令,并在执行块后测试Article.count
增加1。
Python或Django中是否有类似的断言?如果没有,那么最有效的实现只是存储数字,然后再次获取它吗?
答案 0 :(得分:2)
这基本上是一回事。
pre_count = Article.objects.count()
# Your Logic
post_count = Article.objects.count()
self.assertEqual(post_count-pre_count, 1)
OR ,对于额外的红宝石调味品,
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",
})