John Paulett committed 21a6352

Avoid flushing the database during create_test_db to preserve data migrations.

Django 1.3-rc-1 introduced a backwards incompatible change (#14661) that runs flush
after syncdb during testing, thus clearing out all South data migrations.

This fix no-ops the flush command during create_test_db, but allows flush in
test teardowns.

Comments (0)

Files changed (2)


 from django.conf import settings
 from django.db import models
+from django.db.backends.creation import BaseDatabaseCreation
 from django.db.models.loading import AppCache, cache
+from django.core import management
+from import Command as FlushCommand
 from django.utils.datastructures import SortedDict
+class SkipFlushCommand(FlushCommand):
+    def handle_noargs(self, **options):
+        # no-op to avoid calling flush
+        return
 class Hacks:
     def set_installed_apps(self, apps):
         Rebuilds AppCache with the real model definitions.
+    def patch_flush_during_test_db_creation(self):
+        """
+        Patches BaseDatabaseCreation.create_test_db to not flush database
+        """
+        def patch(f):
+            def wrapper(*args, **kwargs):
+                # hold onto the original and replace flush command with a no-op
+                original_flush_command = management._commands['flush']
+                try:
+                    management._commands['flush'] = SkipFlushCommand()
+                    # run create_test_db
+                    f(*args, **kwargs)
+                finally:
+                    # unpatch flush back to the original
+                    management._commands['flush'] = original_flush_command
+            return wrapper
+        BaseDatabaseCreation.create_test_db = patch(BaseDatabaseCreation.create_test_db)


 # Make sure the template loader cache is fixed _now_ (#448)
 import django.template.loaders.app_directories
+from south.hacks import hacks
 from import Command as SyncCommand
 class MigrateAndSyncCommand(SyncCommand):
         # tests should always be up to date with the most recent model structure
         management._commands['syncdb'] = 'django.core'
-        management._commands['syncdb'] = MigrateAndSyncCommand()
+        management._commands['syncdb'] = MigrateAndSyncCommand()
+        # Avoid flushing data migrations.
+        # introduced change that flushed custom
+        # sql during the test database creation (thus flushing the data migrations).
+        # we patch flush to be no-op during create_test_db, but still allow flushing
+        # after each test for non-transactional backends.
+        hacks.patch_flush_during_test_db_creation()