Esempio n. 1
0
    def test_topological_sort(self):
        dg = DirectedGraph()
        dg.extend_vertexes("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "D")

        assert dg.topological_sort() == [vt("A"), vt("B"), vt("C"), vt("D")]

        dg = DirectedGraph("A", "B", "C")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "A")

        with pytest.raises(RuntimeError, match="存在环"):
            dg.topological_sort()

        dg = DirectedGraph("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("A", "D")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("D", "C")

        result = dg.topological_sort()
        assert result == [
            vt("A"), vt("B"), vt("D"), vt("C")
        ] or result == [vt("A"), vt("D"), vt("B"),
                        vt("C")]
Esempio n. 2
0
    def test_create(self):
        dg = DirectedGraph()
        dg.extend_vertexes("A", "B", "C", "D")
        dg.add_new_edge("A", "B")
        dg.add_new_edge("B", "C")
        dg.add_new_edge("C", "D")
        assert [v.name for v in dg.vertexes] == ["A", "B", "C", "D"]
        assert dg.adjacency_dict == {
            vt("A"): [vt("B")],
            vt("B"): [vt("C")],
            vt("C"): [vt("D")],
            vt("D"): [],
        }

        with pytest.raises(exceptions.VertexNotExistError):
            dg.get_vertex_by_name("E")

        with pytest.raises(exceptions.VertexNotExistError):
            dg.add_new_edge("E", "B")