'can't see records inserted by django test case

I'm trying to provide integration to my django application from subversion through the post commit hook.

I have a django test case (a subclass of unittest.TestCase) that (a) inserts a couple of records into a table, (b) spawns an svn commit, (c) svn commit runs a hook that uses my django model to look up info.

I'm using an sqlite3 db. The test is not using the :memory: db, it is using a real file. I have modified the django test code (for debugging this issue) to avoid deleting the test db when it is finished so I can inspect it.

The test code dumps model.MyModel.objects.all() and the records are there between (a) and (b).

When the hook fires at (c) it also dumps the model and there are no records. When I inspect the db manually after the test runs, there are no records.

Is there something going on in the django test framework that isn't commiting the records to the db file?

To clarify: (d) end the test case. Thus the svn commit hook is run before the test case terminates, and before any django db cleanup code should be run.

Extra info: I added a 15 second delay between (b) and (b) so that I could examine the db file manually in the middle of the test. The records aren't in the file.



Solution 1:[1]

The test framework is not saving the data to the database, the data is cleaned once the tests have finished.

Solution 2:[2]

I'm very late to the party on this, but I saw similar behavior in 2022 using Django 3.2 and Python 3.8 and lost hours trying to debug.

If you're seeing it too: check to see if you've installed and configured django-moderation. If so, you may need to approve any records you add in your setUp functions:

from django.test import TestCase
from myapp.models import MyModel

class ArbitraryTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        new_record = MyModel.objects.create(my_field="New Record")
        new_record.save()
        MyModel.moderated_object.fget(new_record).approve()

    def test_function(self):
        self.assertTrue(MyModel.objects.filter(my_field="New Record").count() > 0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joshua Partogi
Solution 2 Ryan