Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 385
bstpierre Avatar asked Jul 29 '09 21:07

bstpierre


3 Answers

Are you using Django trunk? Recent changes (Changeset 9756) run tests in a transaction which is then rolled back. Here's the check-in comment:

Fixed #8138 -- Changed django.test.TestCase to rollback tests (when the database supports it) instead of flushing and reloading the database. This can substantially reduce the time it takes to run large test suites.

like image 157
Vinay Sajip Avatar answered Sep 28 '22 07:09

Vinay Sajip


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

like image 28
Joshua Partogi Avatar answered Sep 28 '22 06:09

Joshua Partogi


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)
like image 25
Ryan Avatar answered Sep 28 '22 07:09

Ryan