0

I am currently testing Django project using django-nose. I use PostgreSQL for my DB. The problem I am facing is:

In test setUp method I create one Emp instance and save it. Then I execute this:

Emp.objects.filter(empId=1)

but this doesn't exist. During debugging I figured that the Emp instance exists in DB but its ID is 137.

I presume that is the issue with django-nose as it flushes DB after every test, however previous empId's seem to remain.

Note: I am using:

class Emp(models.Model):
    empId = models.AutoField(primary_key=True)

My question is, how do I resolve this issue? Is there a way to restart id auto-increment routine after every setUp call?

Laurynas Tamulevičius
  • 1,479
  • 1
  • 11
  • 25
  • Maybe this could help: https://stackoverflow.com/questions/14589634/how-to-reset-the-sequence-for-ids-on-postgresql-tables – David Dahan Dec 05 '17 at 14:19
  • my app with Emp model is named employee, therefore I have already tried 'python manage.py sqlsequencereset employee' which didn't solve my issue – Laurynas Tamulevičius Dec 05 '17 at 14:21
  • Ok. However, I think it's not a good way to rely on a specific ID when running unit tests. Why not something like `Emp.objects.first()` or `Emp.objects.get()` if you're sure you have only 1 Emp object during your test? – David Dahan Dec 05 '17 at 14:27
  • That's completely true and that's how I resolved this problem in the first place, but I was wondering if anyone has encountered this issue before and know what's going on. Also, sometimes I use more than one Emp object in a test and therefore it would be very convenient to access them by the id. – Laurynas Tamulevičius Dec 05 '17 at 14:31
  • I faced something similar use factory boy package, but again, I should not have relied on ids, because it creates coupling with my database :) If you use many Emp objects in your setUp method, just name them: `self.emp_1 = Emp.objects.create() ; self.emp_2 = Emp.objects.create()`. That way it's easy to use them in assert methods :) – David Dahan Dec 05 '17 at 14:34
  • Ok, thanks for the suggestion @DavidD. :) – Laurynas Tamulevičius Dec 05 '17 at 14:35
  • You're welcome :) – David Dahan Dec 05 '17 at 14:35
  • By the way, I achieved the same effect like this: 'Emp.objects.order_by('empId')[]' – Laurynas Tamulevičius Dec 05 '17 at 15:12
  • Yep, that's another way :) – David Dahan Dec 05 '17 at 15:14

0 Answers0