Alexey
Alexey

Reputation: 158

Django models caching? How to disable in tests

First, the code of my 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)

I've got unexpected results in my get_current function, so, I commented it and tried to debug by printing main queryset used inside function and got also strange results:

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

I'm wondering, why QuerySet with the same arguments returns first wrong data, but by the next call - correct and how can I avoid it?

Btw, does django world have something similar to rail's factory girl for creating test data?

Upvotes: 3

Views: 3343

Answers (2)

lprsd
lprsd

Reputation: 87215

does django world have something similar to rail's factory girl for creating test data?

I don't know rails well, so I don't really know what a "factory girl" is. But, Django lets you have a fixture loaded automatically, for testing.

From the documentation here is how you specify what fixtures to load.

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()

And, oh, you can create fixtures using python manage.py dumpdata

And as for disabling cache during development, without affecting the code, you should use "Dummy Caching" as the cache backed.

From the documentation you can ask django to use this backend, by the following settings variable:

CACHE_BACKEND = 'dummy://'

Typically this is put in the localsettings.py of your development system.

Upvotes: 1

Brent
Brent

Reputation: 1149

factory_boy is "a fixtures replacement based on thoughtbot's factory_girl."

If you're coming from Rails, you'll find it works quite similarly to factory_girl. Recommended.

Upvotes: 2

Related Questions