-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph_test.go
107 lines (90 loc) · 2.31 KB
/
graph_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package goraph
import (
"reflect"
"testing"
)
// newDirectedAdjacencyListFromMap is a convenience function to create
// a DirectedAdjacencyList from a map.
func newDirectedAdjacencyListFromMap(edges map[Vertex][]Vertex) *DirectedAdjacencyList {
g := NewDirectedAdjacencyList()
var id Vertex
for k, v := range edges {
if id < k {
id = k
}
for _, vertex := range v {
if id < vertex {
id = vertex
}
g.AddEdge(k, vertex)
}
}
g.nextVertex = id + 1
return g
}
func TestAdjacencyList(t *testing.T) {
g := NewAdjacencyList()
testGraph(t, g)
}
func TestDirectedAdjacencyList(t *testing.T) {
g := NewDirectedAdjacencyList()
testGraph(t, g)
}
func testGraph(t *testing.T, g Graph) {
vertices := make(VertexSlice, 100)
for i := 0; i < 100; i++ {
vertices[i] = g.AddVertex()
}
v1 := vertices[0]
v2 := vertices[1]
v3 := vertices[2]
v4 := vertices[3]
v5 := vertices[4]
v6 := vertices[5]
gverts := VertexSlice(g.Vertices())
vertices.Sort()
gverts.Sort()
if !reflect.DeepEqual(vertices, gverts) {
t.Errorf("bad Vertices. got %v, want %v", gverts, vertices)
}
expectedEdges := EdgeSlice{{v1, v2}, {v1, v3}, {v2, v4}, {v2, v5}, {v3, v6}}
expectedEdges.Sort()
for _, e := range expectedEdges {
g.AddEdge(e.U, e.V)
}
edges := EdgeSlice(g.Edges())
edges.Sort()
if !reflect.DeepEqual(edges, expectedEdges) {
t.Errorf("bad graph edges: got %v, want %v", edges, expectedEdges)
}
g.RemoveEdge(v3, v6)
edges = EdgeSlice(g.Edges())
edges.Sort()
expectedEdges = EdgeSlice{{v1, v2}, {v1, v3}, {v2, v4}, {v2, v5}}
if !reflect.DeepEqual(edges, expectedEdges) {
t.Errorf("bad graph edges: got %v, want %v", edges, expectedEdges)
}
g.RemoveVertex(v2)
edges = EdgeSlice(g.Edges())
edges.Sort()
expectedEdges = EdgeSlice{{v1, v3}}
if !reflect.DeepEqual(edges, expectedEdges) {
t.Errorf("bad graph edges: got %v, want %v", edges, expectedEdges)
}
}
func TestPredecessors(t *testing.T) {
g := NewDirectedAdjacencyList()
vertices := make(VertexSlice, 10)
for i := range vertices {
vertices[i] = g.AddVertex()
if i > 0 {
g.AddEdge(vertices[i], vertices[0])
}
}
preds := VertexSlice(g.Predecessors(vertices[0]))
preds.Sort()
expected := VertexSlice{1, 2, 3, 4, 5, 6, 7, 8, 9}
if !reflect.DeepEqual(preds, expected) {
t.Errorf("bad predecessors: got %v, want %v", preds, expected)
}
}