Refs #30179 -- Moved topological sort functions to django.utils.
This commit is contained in:
parent
50f09264ae
commit
e04209e181
|
@ -12,8 +12,7 @@ from django.db.migrations.questioner import MigrationQuestioner
|
||||||
from django.db.migrations.utils import (
|
from django.db.migrations.utils import (
|
||||||
COMPILED_REGEX_TYPE, RegexObject, get_migration_name_timestamp,
|
COMPILED_REGEX_TYPE, RegexObject, get_migration_name_timestamp,
|
||||||
)
|
)
|
||||||
|
from django.utils.topological_sort import stable_topological_sort
|
||||||
from .topological_sort import stable_topological_sort
|
|
||||||
|
|
||||||
|
|
||||||
class MigrationAutodetector:
|
class MigrationAutodetector:
|
||||||
|
|
|
@ -1,3 +1,7 @@
|
||||||
|
class CyclicDependencyError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def topological_sort_as_sets(dependency_graph):
|
def topological_sort_as_sets(dependency_graph):
|
||||||
"""
|
"""
|
||||||
Variation of Kahn's algorithm (1962) that returns sets.
|
Variation of Kahn's algorithm (1962) that returns sets.
|
||||||
|
@ -13,7 +17,7 @@ def topological_sort_as_sets(dependency_graph):
|
||||||
current = {node for node, deps in todo.items() if not deps}
|
current = {node for node, deps in todo.items() if not deps}
|
||||||
|
|
||||||
if not current:
|
if not current:
|
||||||
raise ValueError('Cyclic dependency in graph: {}'.format(
|
raise CyclicDependencyError('Cyclic dependency in graph: {}'.format(
|
||||||
', '.join(repr(x) for x in todo.items())))
|
', '.join(repr(x) for x in todo.items())))
|
||||||
|
|
||||||
yield current
|
yield current
|
|
@ -0,0 +1,24 @@
|
||||||
|
from django.test import SimpleTestCase
|
||||||
|
from django.utils.topological_sort import (
|
||||||
|
CyclicDependencyError, stable_topological_sort, topological_sort_as_sets,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TopologicalSortTests(SimpleTestCase):
|
||||||
|
|
||||||
|
def test_basic(self):
|
||||||
|
dependency_graph = {
|
||||||
|
1: {2, 3},
|
||||||
|
2: set(),
|
||||||
|
3: set(),
|
||||||
|
4: {5, 6},
|
||||||
|
5: set(),
|
||||||
|
6: {5},
|
||||||
|
}
|
||||||
|
self.assertEqual(list(topological_sort_as_sets(dependency_graph)), [{2, 3, 5}, {1, 6}, {4}])
|
||||||
|
self.assertEqual(stable_topological_sort([1, 2, 3, 4, 5, 6], dependency_graph), [2, 3, 5, 1, 6, 4])
|
||||||
|
|
||||||
|
def test_cyclic_dependency(self):
|
||||||
|
msg = 'Cyclic dependency in graph: (1, {2}), (2, {1})'
|
||||||
|
with self.assertRaisesMessage(CyclicDependencyError, msg):
|
||||||
|
list(topological_sort_as_sets({1: {2}, 2: {1}}))
|
Loading…
Reference in New Issue