Django测试用例无法保存我的模型

4

我目前正在为Django应用编写一些测试。我在我的应用程序的signals.py文件中有以下独立函数:

def updateLeaveCounts():
   # Setting some variables here
    todaysPeriods = Period.objects.filter(end__lte=today_end, end__gte=today_start).filter(request__leavetype="AN")
    for period in todaysPeriods:
        print period
        counter = LeaveCounter.objects.get(pk=period.request.submitter)
        # some Logic here
        period.batch_processed = True
        period.save()

在我的测试用例中,我按照以下方式进行调用:
def test_johnsPostLeaveCounters(self):
    # Some setup here
    p = Period.objects.create(request=request,start=datetime(today.year,today.month,today.day,9),end=datetime(today.year,today.month,today.day,16,30),length='whole')
    updateLeaveCounts()
    self.assertEqual(p.batch_processed,True)

updateLeaveCounts() 在 for 循环中捕获了我新创建的 Period 对象(我可以通过 print period 将其详细信息打印到控制台),但是我的 assertEqual() 测试失败了 - 告诉我 batch_processed 属性仍然为 False。

好像 period.save() 事务没有被调用。

我知道在 Django 版本 1.8 之前,你必须使用 TransactionTestCase 类,但是目前我正在运行版本为 1.8.3 的项目,所以我不认为这是问题。

是否有什么需要做才能使 TestCases 正确反映我在此函数中执行的 model.save() 操作,从而使该函数被测试覆盖?


这与测试无关。p只是与updateLeaveCounts中保存的对象不同。 - Daniel Roseman
1个回答

7
尝试使用 "refresh_from_db" 方法:点击此处了解更多。
# ...
updateLeaveCounts()
p.refresh_from_db()
self.assertEqual(p.batch_processed, True)
# ...

1
谢谢 Vladimir!您知道在使用测试框架时为什么不会自动执行此操作吗?我在 Django 文档中没有找到相关记录。 - jamesk5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接