Ejemplo n.º 1
0
    def test_topsort_string_nodes(self):
        """
        Tests the toplogical sort when strings are used for node objects.
        """
        g = DAG()
        nodes = ['shirt', 'pants', 'tie', 'belt', 'shoes', 'socks', 'pants']
        for node in nodes:
            g.add_node(node)
        edges = (
            ('shirt', 'tie'),
            ('shirt', 'belt'),
            ('belt', 'tie'),
            ('pants', 'tie'),
            ('pants', 'belt'),
            ('pants', 'shoes'),
            ('pants', 'shirt'),
            ('socks', 'shoes'),
            ('socks', 'pants'),
        )
        for edge in edges:
            g.add_edge(*edge)

        topsort = list(g.topsort_nodes())
        for node in nodes:
            self.assertIn(node, topsort)
        for node1, node2 in edges:
            self.assertTrue(topsort.index(node2) > topsort.index(node1))
Ejemplo n.º 2
0
    def test_topsort_simple(self):
        """
        Tests the topological sort of the DAG class.
        """
        g = DAG()
        g.add_node(1)
        g.add_node(2)
        g.add_node(3)
        g.add_edge(1, 2)
        g.add_edge(2, 3)

        topsort = list(g.topsort_nodes())

        self.assertSequenceEqual([1, 2, 3], topsort)
Ejemplo n.º 3
0
    def test_topsort_no_dependencies(self):
        """
        Tests the toplogical sort of the DAG class when the given DAG has no
        dependencies between the nodes.
        """
        g = DAG()
        g.add_node(1)
        g.add_node(2)
        g.add_node(3)

        topsort = list(g.topsort_nodes())

        nodes = [1, 2, 3]
        # The order in this case cannot be mandated, only that all the nodes
        # are in the output
        for node in nodes:
            self.assertIn(node, topsort)
Ejemplo n.º 4
0
    def test_topsort_complex(self):
        """
        Tests the toplogical sort when a more complex graph is given.
        """
        g = DAG()
        nodes = list(range(13))
        for node in nodes:
            g.add_node(node)
        edges = (
            (0, 1),
            (0, 2),
            (0, 3),
            (0, 5),
            (0, 6),
            (2, 3),
            (3, 4),
            (3, 5),
            (4, 9),
            (6, 4),
            (6, 9),
            (7, 6),
            (8, 7),
            (9, 10),
            (9, 11),
            (9, 12),
            (11, 12),
        )
        for edge in edges:
            g.add_edge(*edge)

        topsort = list(g.topsort_nodes())
        # Make sure all nodes are found in the toplogical sort
        for node in nodes:
            self.assertIn(node, topsort)
        # Make sure that all dependent nodes are found after the nodes they
        # depend on.
        # Invariant: for each edge (n1, n2) position(n2) in the topological
        # sort must be strictly greater than the position(n1).
        for node1, node2 in edges:
            self.assertTrue(topsort.index(node2) > topsort.index(node1))