How to create initial revision for test objects when using django-reversion in test case
Asked Answered
F

2

7

I'm creating some initial tests as I play with django-revisions. I'd like to be able to test that some of my api and view code correctly saves revisions. However, I can't get even a basic test to save a deleted version.

import reversion
from django.db import transaction
from django import test
from myapp import models

class TestRevisioning(test.TestCase):
    fixtures = ['MyModel']
    def testDelete(self):
        object1 = models.MyModel.objects.first()
        with transaction.atomic():
             with reversion.create_revision():
                 object1.delete()
        self.assertEquals(reversion.get_deleted(models.MyModel).count(), 1)

This fails when checking the length of the deleted QuerySet with:

AssertionError: 0 != 1

My hypothesis is that I need to create the initial revisions of my model (do the equivalent of ./manage.py createinitialrevisions). If this is the issue, how do I create the initial revisions in my test? If that isn't the issue, what else can I try?

Flytrap answered 16/9, 2014 at 8:48 Comment(0)
F
4

So, the solution is pretty simple. I saved my object under revision control.

# imports same as question

class TestRevisioning(test.TestCase):
    fixtures = ['MyModel']

    def testDelete(self):
        object1 = models.MyModel.objects.first()
        # set up initial revision
        with reversion.create_revision():
            object1.save()
        # continue with remainder of the test as per the question.
        # ... etc.

I tried to override _fixture_setup(), but that didn't work. Another option would be to loop over the MyModel objects in the __init__(), saving them under reversion control.

Flytrap answered 23/9, 2014 at 23:51 Comment(0)
P
0

'MyModel' is the name of the file with your fixtures? If not, what you probably is missing is the data creation.

You can use fixtures (but a file, not the name of your model) or factories.

There's a whole chapter in Django documentation related to providing initial data in database for models: https://docs.djangoproject.com/en/1.7/howto/initial-data/

Hope it helps

Perigordian answered 16/9, 2014 at 9:34 Comment(1)
The MyModel object is correctly loaded from its fixture (MyModel.json). If it were not, models.MyModel.objects.first() would return None, and object1.delete() would raise an AttributeError.Flytrap

© 2022 - 2024 — McMap. All rights reserved.