[Fixed]-How can I reset a Django test database id's after each test?

6👍

If you need a test to reset the primary key sequence, you can issue a RawSQL query doing that. How to do that exactly is answered in this StackOverflow question.

An easier option is available if you’re using pytest. We’re using pytest and pytest-django in all our Django projects and it makes testing a breeze. pytest-django provdes a database fixture that can take a boolean parameter to reset the sequences. Use it like so:

@pytest.mark.django_db(transaction=True, reset_sequences=True)
def mytest():
    [...]
👤jnns

6👍

I got this to work by replacing TestCase with TransactionTestCase and set reset_sequences=True. However the tests are running slower.

from django.test import TransactionTestCase

class ViewTest(TransactionTestCase):
    reset_sequences = True

    def test_view_redirects(self):
       ...

Here’s the doc

1👍

You are using a fixtures file – put whatever data you want in there; then edit it in your test as needed.

Although, that is harder to maintain. In my opinion – there are far better options that may work much more like what you intend.

You’re better off using something like factory_boy and generating the models (and related foreign keys) at instantiation with dummy data you provide.

That way you know exactly what is being tested and it’s completely independent of everything else. The nice part is that with factory_boy you will have a factories.py file you can keep up to date much easier than working with some fixture.

There are other options like Mixer or model_mommy, although I only have experience with factory_boy and mixer.

With factory_boy it might look something like this:

   def test_model_test1(self):
       factory.ModelFactory(
       some_specific_attribute='some_specific_value'
       )
       model = Model.objects.all().first()
       # Test against your model
👤Hanny

Leave a comment