| 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 | "maps" |
| 9 | "slices" |
| 10 | "testing" |
| 11 | ) |
| 12 | |
| 13 | func TestAllPaths(t *testing.T) { |
| 14 | g := stringGraph{ |
| 15 | "A": {"B", "C"}, |
| 16 | "B": {"D"}, |
| 17 | "C": {"D", "E"}, |
| 18 | "D": {"F"}, |
| 19 | "E": {}, |
| 20 | "F": {}, |
| 21 | } |
| 22 | |
| 23 | // Paths in g: |
| 24 | // |
| 25 | // A->B->D->F |
| 26 | // A->C->D->F |
| 27 | // A->C->E |
| 28 | |
| 29 | // AllPaths(A, F) should include A, B, C, D, F. E is not on path to F. |
| 30 | got := slices.Sorted(maps.Keys(AllPaths(g, "A", "F"))) |
| 31 | want := []string{"A", "B", "C", "D", "F"} |
| 32 | if !slices.Equal(got, want) { |
| 33 | t.Errorf("AllPaths(A, F) = %v, want %v", got, want) |
| 34 | } |
| 35 | |
| 36 | // AllPaths(A, E) -> A, C, E. B is not on path. |
| 37 | got = slices.Sorted(maps.Keys(AllPaths(g, "A", "E"))) |
| 38 | want = []string{"A", "C", "E"} |
| 39 | if !slices.Equal(got, want) { |
| 40 | t.Errorf("AllPaths(A, E) = %v, want %v", got, want) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | func TestAllPaths_74842(t *testing.T) { |
| 45 | tests := []struct { |
| 46 | name string |
| 47 | g stringGraph |
| 48 | src, dst string |
| 49 | want []string |
| 50 | }{ |
| 51 | { |
| 52 | // C <--> B --> A --> D <--> E |
| 53 | // ⋃ |
| 54 | name: "non-regression test for #74842", |
| 55 | g: stringGraph{ |
| 56 | "A": {"D"}, |
| 57 | "B": {"A", "B", "C"}, |
| 58 | "C": {"B"}, |
| 59 | "D": {"E"}, |
| 60 | "E": {"D"}, |
| 61 | }, |
| 62 | src: "A", dst: "D", |
| 63 | want: []string{"A", "D", "E"}, |
| 64 | }, |
| 65 | { |
| 66 | // A --> B --> D |
| 67 | // ^ |
| 68 | // v |
| 69 | // C[123] |
| 70 | name: "regression test for #74842", |
| 71 | g: stringGraph{ |
| 72 | "A": {"B"}, |
| 73 | "B": {"C1", "C2", "C3", "D"}, |
| 74 | "C1": {"B"}, |
| 75 | "C2": {"B"}, |
| 76 | "C3": {"B"}, |
| 77 | }, |
| 78 | src: "A", dst: "D", |
| 79 | want: []string{"A", "B", "C1", "C2", "C3", "D"}, |
| 80 | }, |
| 81 | { |
| 82 | // A -------> B --> D |
| 83 | // \--> C ---^ | |
| 84 | // ^----------+ |
| 85 | name: "another regression test for #74842", |
| 86 | g: stringGraph{ |
| 87 | "A": {"B", "C"}, |
| 88 | "B": {"D"}, |
| 89 | "C": {"B"}, |
| 90 | "D": {"C"}, |
| 91 | }, |
| 92 | src: "A", dst: "D", |
| 93 | want: []string{"A", "B", "C", "D"}, |
| 94 | }, |
| 95 | } |
| 96 | |
| 97 | for _, tt := range tests { |
| 98 | t.Run(tt.name, func(t *testing.T) { |
| 99 | allPaths := AllPaths(tt.g, tt.src, tt.dst) |
| 100 | got := slices.Sorted(maps.Keys(allPaths)) |
| 101 | if !slices.Equal(got, tt.want) { |
| 102 | t.Errorf("got %v, want %v", got, tt.want) |
| 103 | } |
| 104 | }) |
| 105 | } |
| 106 | } |