【问题标题】:Django TestCase not saving my modelsDjango TestCase 没有保存我的模型
【发布时间】:2016-02-11 04:16:11
【问题描述】:

我目前正在为 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()

在我的 TestCase 中,我这样称呼它:

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 属性仍然存在假的。

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

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

我需要做些什么才能让 TestCases 正确反映我在此函数中执行的 model.save() 操作,从而使测试涵盖此函数吗?

【问题讨论】:

  • 这与测试无关。 p 与保存在 updateLeaveCounts 中的对象根本不是同一个对象。

标签: python django unit-testing


【解决方案1】:

尝试使用refresh_from_db:

# ...
updateLeaveCounts()
p.refresh_from_db()
self.assertEqual(p.batch_processed, True)
# ...

【讨论】:

  • 谢谢弗拉基米尔!您知道在使用测试框架时是否有原因导致无法自动完成?我在 Django 文档中的任何地方都看不到这一点。
猜你喜欢
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
  • 2015-05-06
  • 2014-04-20
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
相关资源
最近更新 更多