14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Tests for topological sort.
18
"""Tests for topological sort."""
23
21
from bzrlib.tests import TestCase
24
from bzrlib.tsort import topo_sort
22
from bzrlib.tsort import topo_sort, TopoSorter
25
23
from bzrlib.errors import GraphCycleError
27
26
class TopoSortTests(TestCase):
28
def assertSortAndIterate(self, graph, result_list):
29
"""Check that sorting and iter_topo_order on graph works."""
30
self.assertEquals(result_list, topo_sort(graph))
31
self.assertEqual(result_list,
32
list(TopoSorter(graph).iter_topo_order()))
34
def assertSortAndIterateRaise(self, exception_type, graph):
35
"""Try both iterating and topo_sorting graph and expect an exception."""
36
self.assertRaises(exception_type, topo_sort, graph)
37
self.assertRaises(exception_type,
39
TopoSorter(graph).iter_topo_order())
29
41
def test_tsort_empty(self):
30
42
"""TopoSort empty list"""
31
self.assertEquals(topo_sort([]), [])
43
self.assertSortAndIterate([], [])
33
45
def test_tsort_easy(self):
34
46
"""TopoSort list with one node"""
35
self.assertEquals(topo_sort({0: []}.items()),
47
self.assertSortAndIterate({0: []}.items(), [0])
38
49
def test_tsort_cycle(self):
39
50
"""TopoSort traps graph with cycles"""
40
self.assertRaises(GraphCycleError,
51
self.assertSortAndIterateRaise(GraphCycleError,
45
55
def test_tsort_cycle_2(self):
46
56
"""TopoSort traps graph with longer cycle"""
47
self.assertRaises(GraphCycleError,
57
self.assertSortAndIterateRaise(GraphCycleError,
53
62
def test_tsort_1(self):
54
63
"""TopoSort simple nontrivial graph"""
55
self.assertEquals(topo_sort({0: [3],
59
4: [0, 3]}.iteritems()),
64
self.assertSortAndIterate({0: [3],
62
71
def test_tsort_partial(self):
63
72
"""Topological sort with partial ordering.
65
74
If the graph does not give an order between two nodes, they are
66
75
returned in lexicographical order.
68
self.assertEquals(topo_sort([(0, []),
76
(8, [0, 1, 4, 5, 6])]),
77
[0, 1, 2, 3, 4, 5, 6, 7, 8, ])
77
self.assertSortAndIterate(([(0, []),
85
(8, [0, 1, 4, 5, 6])]),
86
[0, 1, 2, 3, 4, 5, 6, 7, 8])