| 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 | "sort" |
| 10 | "testing" |
| 11 | ) |
| 12 | |
| 13 | func TestSCCs(t *testing.T) { |
| 14 | tests := []struct { |
| 15 | g stringGraph |
| 16 | want [][]string |
| 17 | }{ |
| 18 | { |
| 19 | g: stringGraph{ |
| 20 | "A": {"B"}, |
| 21 | "B": {"C"}, |
| 22 | "C": {"A"}, |
| 23 | }, |
| 24 | want: [][]string{{"A", "B", "C"}}, |
| 25 | }, |
| 26 | { |
| 27 | g: stringGraph{ |
| 28 | "A": {"B"}, |
| 29 | "B": {}, |
| 30 | }, |
| 31 | want: [][]string{{"A"}, {"B"}}, |
| 32 | }, |
| 33 | { |
| 34 | g: stringGraph{ |
| 35 | "A": {"A"}, |
| 36 | }, |
| 37 | want: [][]string{{"A"}}, |
| 38 | }, |
| 39 | { |
| 40 | g: stringGraph{ |
| 41 | "A": {"B"}, |
| 42 | "B": {"A"}, |
| 43 | "C": {"D"}, |
| 44 | "D": {"C"}, |
| 45 | }, |
| 46 | want: [][]string{{"A", "B"}, {"C", "D"}}, |
| 47 | }, |
| 48 | } |
| 49 | |
| 50 | for _, test := range tests { |
| 51 | got := SCCs(test.g) |
| 52 | |
| 53 | // Normalize for comparison: sort components, sort within components |
| 54 | for _, c := range got { |
| 55 | sort.Strings(c) |
| 56 | } |
| 57 | slices.SortFunc(got, slices.Compare) |
| 58 | |
| 59 | if !slices.EqualFunc(got, test.want, slices.Equal) { |
| 60 | t.Errorf("SCCs(%v) = %v, want %v", test.g, got, test.want) |
| 61 | } |
| 62 | } |
| 63 | } |