【问题标题】:Django models caching? How to disable in testsDjango模型缓存?如何在测试中禁用
【发布时间】:2010-02-12 11:31:31
【问题描述】:

首先,我的tests.py的代码

def test_get_current(self):
    m = Member.objects.create(...)
    q = Question.objects.create(name="q1", text="q1", start_datetime=self.day_before, close_datetime=self.day_after, type=self.type)
    r = Response.objects.create(question=q, text='response')
    expected = q, None 
    #self.assertEquals(expected, Question.objects.get_current(m.id))

    q2 = Question.objects.create(name="q2", text="q2", start_datetime=self.day_before, close_datetime=self.day_after, type=self.type)
    #print Question.objects.all()
    #self.assertEquals(expected, Question.objects.get_current(m.id))
    MemberResponse.objects.create(member=m, response=r)
    print Question.objects.all().exclude(response__memberresponse__member=m)
    print Question.objects.all().exclude(response__memberresponse__member=m)

我在我的 get_current 函数中得到了意想不到的结果,所以,我评论了它并尝试通过打印函数内部使用的主查询集进行调试,结果也很奇怪:

...
Installing index for ... model
[<Question: q1>, <Question: q2>]
[<Question: q2>]
.....
----------------------------------------------------------------------
Ran 5 tests in 3.125s

我想知道,为什么具有相同参数的 QuerySet 返回第一个错误数据,但在下一次调用时 - 正确,我该如何避免它?

顺便说一句,django world 是否有类似于 rail 的 factory girl 的东西来创建测试数据?

【问题讨论】:

    标签: django unit-testing django-models


    【解决方案1】:

    factory_boy 是“基于 thinkbot 的 factory_girl 的固定装置替代品。”

    如果您来自 Rails,您会发现它的工作方式与 factory_girl 非常相似。推荐。

    【讨论】:

      【解决方案2】:

      django world 有没有类似于 rail 的 factory girl 的东西来创建测试数据?

      我不太了解rails,所以我真的不知道什么是“工厂女孩”。但是,Django 允许您自动加载一个夹具,用于测试。

      来自documentation,这里是您指定要加载的固定装置的方法。

      class AnimalTestCase(TestCase):
          fixtures = ['mammals.json', 'birds']
      
          def setUp(self):
          # Test definitions as before.
          call_setup_methods()
      
          def testFluffyAnimals(self):
          # A test that uses the fixtures.
          call_some_test_code()
      

      而且,哦,您可以使用 python manage.py dumpdata 创建固定装置

      至于在开发过程中禁用缓存,在不影响代码的情况下,您应该使用“Dummy Caching”作为缓存支持。

      documentation,您可以通过以下设置变量要求 django 使用此后端:

      CACHE_BACKEND = 'dummy://'
      

      这通常放在开发系统的 localsettings.py 中。

      【讨论】:

      • 灯具很难维护,这就是为什么我更喜欢动态的。实际上,缓存只是我对这个问题的猜测。也许我错了。 CACHE_BACKEND 设置没有改变任何东西,对于同一个查询,我仍然得到 2 个不同的输出。
      猜你喜欢
      • 2010-09-25
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多