Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #14799 -- Provided a full solution for test database creation o…

…rder problems.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@14822 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit b11c21d69a2d16aa104cb1313691aa5c5efc2468 1 parent 111ed01
Russell Keith-Magee authored December 05, 2010
66  django/test/simple.py
@@ -2,12 +2,21 @@
2 2
 import signal
3 3
 
4 4
 from django.conf import settings
  5
+from django.core.exceptions import ImproperlyConfigured
5 6
 from django.db.models import get_app, get_apps
6 7
 from django.test import _doctest as doctest
7 8
 from django.test.utils import setup_test_environment, teardown_test_environment
8 9
 from django.test.testcases import OutputChecker, DocTestRunner, TestCase
9 10
 from django.utils import unittest
10 11
 
  12
+try:
  13
+    all
  14
+except NameError:
  15
+    from django.utils.itercompat import all
  16
+
  17
+
  18
+__all__ = ('DjangoTestRunner', 'DjangoTestSuiteRunner', 'run_tests')
  19
+
11 20
 # The module name for tests outside models.py
12 21
 TEST_MODULE = 'tests'
13 22
 
@@ -183,6 +192,40 @@ def reorder_suite(suite, classes):
183 192
         bins[0].addTests(bins[i+1])
184 193
     return bins[0]
185 194
 
  195
+def dependency_ordered(test_databases, dependencies):
  196
+    """Reorder test_databases into an order that honors the dependencies
  197
+    described in TEST_DEPENDENCIES.
  198
+    """
  199
+    ordered_test_databases = []
  200
+    resolved_databases = set()
  201
+    while test_databases:
  202
+        changed = False
  203
+        deferred = []
  204
+
  205
+        while test_databases:
  206
+            signature, aliases = test_databases.pop()
  207
+            dependencies_satisfied = True
  208
+            for alias in aliases:
  209
+                if alias in dependencies:
  210
+                    if all(a in resolved_databases for a in dependencies[alias]):
  211
+                        # all dependencies for this alias are satisfied
  212
+                        dependencies.pop(alias)
  213
+                        resolved_databases.add(alias)
  214
+                    else:
  215
+                        dependencies_satisfied = False
  216
+                else:
  217
+                    resolved_databases.add(alias)
  218
+
  219
+            if dependencies_satisfied:
  220
+                ordered_test_databases.append((signature, aliases))
  221
+                changed = True
  222
+            else:
  223
+                deferred.append((signature, aliases))
  224
+
  225
+        if not changed:
  226
+            raise ImproperlyConfigured("Circular dependency in TEST_DEPENDENCIES")
  227
+        test_databases = deferred
  228
+    return ordered_test_databases
186 229
 
187 230
 class DjangoTestSuiteRunner(object):
188 231
     def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs):
@@ -222,6 +265,7 @@ def setup_databases(self, **kwargs):
222 265
         # and which ones are test mirrors or duplicate entries in DATABASES
223 266
         mirrored_aliases = {}
224 267
         test_databases = {}
  268
+        dependencies = {}
225 269
         for alias in connections:
226 270
             connection = connections[alias]
227 271
             if connection.settings_dict['TEST_MIRROR']:
@@ -238,21 +282,17 @@ def setup_databases(self, **kwargs):
238 282
                         connection.settings_dict['ENGINE'],
239 283
                         connection.settings_dict['NAME'],
240 284
                     ), []).append(alias)
241  
-        
242  
-        # Re-order the list of databases to create, making sure the default
243  
-        # database is first. Otherwise, creation order is semi-random (i.e. 
244  
-        # dict ordering dependent).
245  
-        dbs_to_create = []
246  
-        for dbinfo, aliases in test_databases.items():
247  
-            if DEFAULT_DB_ALIAS in aliases:
248  
-                dbs_to_create.insert(0, (dbinfo, aliases))
249  
-            else:
250  
-                dbs_to_create.append((dbinfo, aliases))
251  
-                
252  
-        # Final pass -- actually create the databases.
  285
+
  286
+                if 'TEST_DEPENDENCIES' in connection.settings_dict:
  287
+                    dependencies[alias] = connection.settings_dict['TEST_DEPENDENCIES']
  288
+                else:
  289
+                    if alias != 'default':
  290
+                        dependencies[alias] = connection.settings_dict.get('TEST_DEPENDENCIES', ['default'])
  291
+
  292
+        # Second pass -- actually create the databases.
253 293
         old_names = []
254 294
         mirrors = []
255  
-        for (host, port, engine, db_name), aliases in dbs_to_create:
  295
+        for (host, port, engine, db_name), aliases in dependency_ordered(test_databases.items(), dependencies):
256 296
             # Actually create the database for the first connection
257 297
             connection = connections[aliases[0]]
258 298
             old_names.append((connection, db_name, True))
47  docs/topics/testing.txt
@@ -454,6 +454,53 @@ will be redirected to point at ``default``. As a result, writes to
454 454
 the same database, not because there is data replication between the
455 455
 two databases.
456 456
 
  457
+.. _topics-testing-creation-dependencies:
  458
+
  459
+Controlling creation order for test databases
  460
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  461
+
  462
+.. versionadded:: 1.3
  463
+
  464
+By default, Django will always create the ``default`` database first.
  465
+However, no guarantees are made on the creation order of any other
  466
+databases in your test setup.
  467
+
  468
+If your database configuration requires a specific creation order, you
  469
+can specify the dependencies that exist using the
  470
+:setting:`TEST_DEPENDENCIES` setting. Consider the following
  471
+(simplified) example database configuration::
  472
+
  473
+    DATABASES = {
  474
+        'default': {
  475
+             # ... db settings
  476
+             TEST_DEPENDENCIES = ['diamonds']
  477
+        },
  478
+        'diamonds': {
  479
+            # ... db settings
  480
+        }
  481
+        'clubs': {
  482
+            # ... db settings
  483
+            TEST_DEPENDENCIES = ['diamonds']
  484
+        }
  485
+        'spades': {
  486
+            # ... db settings
  487
+            TEST_DEPENDENCIES = ['diamonds','hearts']
  488
+        }
  489
+        'hearts': {
  490
+            # ... db settings
  491
+            TEST_DEPENDENCIES = ['diamonds','clubs']
  492
+        }
  493
+    }
  494
+
  495
+Under this configuration, the ``diamonds`` database will be created first,
  496
+as it is the only database alias without dependencies. The ``default``` and
  497
+``clubs`` alias will be created next (although the order of creation of this
  498
+pair is not guaranteed); then ``hearts``; and finally ``spades``.
  499
+
  500
+If there are any circular dependencies in the
  501
+:setting:`TEST_DEPENDENCIES` definition, an ``ImproperlyConfigured``
  502
+exception will be raised.
  503
+
457 504
 Other test conditions
458 505
 ---------------------
459 506
 
91  tests/regressiontests/test_runner/tests.py
@@ -3,6 +3,7 @@
3 3
 """
4 4
 import StringIO
5 5
 
  6
+from django.core.exceptions import ImproperlyConfigured
6 7
 from django.test import simple
7 8
 from django.utils import unittest
8 9
 
@@ -27,3 +28,93 @@ def runTest(self):
27 28
         result = dtr.run(suite)
28 29
         self.assertEqual(1, result.testsRun)
29 30
         self.assertEqual(1, len(result.failures))
  31
+
  32
+class DependencyOrderingTests(unittest.TestCase):
  33
+
  34
+    def test_simple_dependencies(self):
  35
+        raw = [
  36
+            ('s1', ['alpha']),
  37
+            ('s2', ['bravo']),
  38
+            ('s3', ['charlie']),
  39
+        ]
  40
+        dependencies = {
  41
+            'alpha': ['charlie'],
  42
+            'bravo': ['charlie'],
  43
+        }
  44
+
  45
+        ordered = simple.dependency_ordered(raw, dependencies=dependencies)
  46
+        ordered_sigs = [sig for sig,aliases in ordered]
  47
+
  48
+        self.assertIn('s1', ordered_sigs)
  49
+        self.assertIn('s2', ordered_sigs)
  50
+        self.assertIn('s3', ordered_sigs)
  51
+        self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1'))
  52
+        self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2'))
  53
+
  54
+    def test_chained_dependencies(self):
  55
+        raw = [
  56
+            ('s1', ['alpha']),
  57
+            ('s2', ['bravo']),
  58
+            ('s3', ['charlie']),
  59
+        ]
  60
+        dependencies = {
  61
+            'alpha': ['bravo'],
  62
+            'bravo': ['charlie'],
  63
+        }
  64
+
  65
+        ordered = simple.dependency_ordered(raw, dependencies=dependencies)
  66
+        ordered_sigs = [sig for sig,aliases in ordered]
  67
+
  68
+        self.assertIn('s1', ordered_sigs)
  69
+        self.assertIn('s2', ordered_sigs)
  70
+        self.assertIn('s3', ordered_sigs)
  71
+
  72
+        # Explicit dependencies
  73
+        self.assertLess(ordered_sigs.index('s2'), ordered_sigs.index('s1'))
  74
+        self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2'))
  75
+
  76
+        # Implied dependencies
  77
+        self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1'))
  78
+
  79
+    def test_multiple_dependencies(self):
  80
+        raw = [
  81
+            ('s1', ['alpha']),
  82
+            ('s2', ['bravo']),
  83
+            ('s3', ['charlie']),
  84
+            ('s4', ['delta']),
  85
+        ]
  86
+        dependencies = {
  87
+            'alpha': ['bravo','delta'],
  88
+            'bravo': ['charlie'],
  89
+            'delta': ['charlie'],
  90
+        }
  91
+
  92
+        ordered = simple.dependency_ordered(raw, dependencies=dependencies)
  93
+        ordered_sigs = [sig for sig,aliases in ordered]
  94
+
  95
+        self.assertIn('s1', ordered_sigs)
  96
+        self.assertIn('s2', ordered_sigs)
  97
+        self.assertIn('s3', ordered_sigs)
  98
+        self.assertIn('s4', ordered_sigs)
  99
+
  100
+        # Explicit dependencies
  101
+        self.assertLess(ordered_sigs.index('s2'), ordered_sigs.index('s1'))
  102
+        self.assertLess(ordered_sigs.index('s4'), ordered_sigs.index('s1'))
  103
+        self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s2'))
  104
+        self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s4'))
  105
+
  106
+        # Implicit dependencies
  107
+        self.assertLess(ordered_sigs.index('s3'), ordered_sigs.index('s1'))
  108
+
  109
+    def test_circular_dependencies(self):
  110
+        raw = [
  111
+            ('s1', ['alpha']),
  112
+            ('s2', ['bravo']),
  113
+        ]
  114
+        dependencies = {
  115
+            'bravo': ['alpha'],
  116
+            'alpha': ['bravo'],
  117
+        }
  118
+
  119
+        self.assertRaises(ImproperlyConfigured, simple.dependency_ordered, raw, dependencies=dependencies)
  120
+

0 notes on commit b11c21d

Please sign in to comment.
Something went wrong with that request. Please try again.