So I have a test class which has a setup methiod to create a model object which can be tested against:
class UserProjectTests(TestCase):
fixtures = ['admin_test.json']
def setUp(self):
...
self.project1 = Project.objects.create(
user=self.user_profile1,
product=self.product1,
module=self.module1,
model=self.model1,
zipcode=90210
)
self.project1.save()
def test_module_created(self):
...
def test_model_created(self):
...
def test_product_created(self):
...
def test_project_created(self):
#! what happened to pk<4???
result1 = Project.objects.get(pk=4)
self.assertEquals(result1.zipcode, 90210)
def test_user_cannot_edit_project_they_dont_own(self):
...
My question is – why do I have to call pk=4 to get the only object in the test db? If I move this test up a couple of functions the pk I have to query to pass the test decreases. It seems that everytime setup runs it does not start with a virgin db because the pk is auto-incrementing.
Can anyone tell me why this is? What should I do to be able to use pk=1 regardless of in which test function it appears?
Django’s test runner flushes the database after each test, it doesn’t delete it and recreate it – that would slow down the tests considerably.
Rather than hard-coding a pk number, you could just ask for the first element:
Project.objects.all()[0]. Since you start each test run with empty tables, this is guaranteed to give you the item you want.