22

I have a Django project that uses local PostgreSQL server. I'm using a debugger to debug some weird bugs that I have. While the debugger is stopped on one of the tests, I tried to look at the test database. I see this new database (test_project1) and all the schemes are defined as they should be. But all tables are empty.

I know that the tables are not empty:

  • I used a fixture and some tests already ran and returned data.
  • A post test created a new user and returned 201 status code.

And yet, I see no data when I try to access the database with pgAdmin3 or psql.

Any idea what is going on here? Is there some kind of sophisticated cache mechanism that Django uses?

Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
Uzi
  • 271
  • 2
  • 4

2 Answers2

21

Django's TestCase is wrapping every test in its own transaction. So your database is not being used any time you do a request through ORM.

ilvar
  • 5,718
  • 1
  • 20
  • 17
  • Thanks. Just wanted to make sure that I'm not loosing it... :-) – Uzi Apr 29 '12 at 10:08
  • 14
    If you want to disable the transaction you can temporarily inherit from TransactionTestCase rather than TestCase. It's a bit confusing: TestCase inherits from TransactionTestCase, but "but surrounds every test with a transaction, monkey-patches the real transaction management routines to do nothing...". This does work though, and is very useful for debugging. Yes, I had the same, "am I losing it?" moment. The reason you would want to use TestCase rather than TransactionTestCase, is that rolling back a transaction is faster than truncating tables. – Michael Bylstra Dec 01 '14 at 22:35
3

The database transaction that is being used by django.test.TestCase can be avoided by inheriting from django.test.TransactionTestCase instead of TestCase. Then the data will be visible in the database.

You might want to just do this temporarily while debugging, so that you get the performance benefits of django.test.TestCase the rest of the time.

Django docs:
django.test.TransactionTestCase
django.test.TestCase

Rob Bednark
  • 25,981
  • 23
  • 80
  • 125