| 1 |
// Copyright 2026 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package graph |
| 6 |
|
| 7 |
import ( |
| 8 |
"slices" |
| 9 |
"testing" |
| 10 |
) |
| 11 |
|
| 12 |
func TestCompact(t *testing.T) { |
| 13 |
g := stringGraph{ |
| 14 |
"A": {"B"}, |
| 15 |
"B": {"C"}, |
| 16 |
"C": {"A"}, |
| 17 |
} |
| 18 |
|
| 19 |
cg, m := Compact(g) |
| 20 |
|
| 21 |
if n := cg.NumNodes(); n != 3 { |
| 22 |
t.Errorf("NumNodes() = %d, want 3", n) |
| 23 |
} |
| 24 |
|
| 25 |
// Check mapping |
| 26 |
for i := range cg.NumNodes() { |
| 27 |
j := m.Index(m.Value(i)) |
| 28 |
if j != i { |
| 29 |
t.Errorf("Compact(NodeID(%d)) = %d, want %d", i, j, i) |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
// Check edges in compacted graph |
| 34 |
for u := range cg.Nodes() { |
| 35 |
var got []string |
| 36 |
for v := range cg.Out(u) { |
| 37 |
got = append(got, m.Value(v)) |
| 38 |
} |
| 39 |
|
| 40 |
want := slices.Sorted(slices.Values(g[m.Value(u)])) |
| 41 |
if !slices.Equal(got, want) { |
| 42 |
t.Errorf("Out(%d) = %v, want %v", u, got, want) |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
cg2, _ := Compact(cg) |
| 47 |
if cg != cg2 { |
| 48 |
t.Errorf("Compact(Compact(g)) returned a new graph, want Compact(g)") |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
func TestCompact_AlreadyCompact(t *testing.T) { |
| 53 |
g := newTestGraph(3, map[int][]int{ |
| 54 |
0: {1}, |
| 55 |
1: {2}, |
| 56 |
2: {0}, |
| 57 |
}) |
| 58 |
|
| 59 |
cg, m := Compact(g) |
| 60 |
|
| 61 |
if cg != g { |
| 62 |
t.Errorf("Compact(g) returned new graph, want original graph") |
| 63 |
} |
| 64 |
|
| 65 |
if m.Index(0) != 0 { |
| 66 |
t.Errorf("Identity map Compact(0) = %d, want 0", m.Index(0)) |
| 67 |
} |
| 68 |
if m.Value(0) != 0 { |
| 69 |
t.Errorf("Identity map NodeID(0) = %d, want 0", m.Value(0)) |
| 70 |
} |
| 71 |
} |