github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/graph_test.go (about) 1 // Copyright 2023 LiveKit, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package utils 16 17 import ( 18 "testing" 19 20 "github.com/stretchr/testify/require" 21 "golang.org/x/exp/maps" 22 ) 23 24 type testNode struct { 25 id string 26 } 27 28 func (n *testNode) ID() string { 29 return n.id 30 } 31 32 type testEdge int 33 34 func (e testEdge) Length() int64 { 35 return int64(e) 36 } 37 38 func testNodeIDs[K comparable, N GraphNodeProps[K]](path []N) []K { 39 var names []K 40 for _, p := range path { 41 names = append(names, p.ID()) 42 } 43 return names 44 } 45 46 func TestGraph(t *testing.T) { 47 t.Run("graph mutation", func(t *testing.T) { 48 g := NewGraph[string, *testNode, testEdge]() 49 g.InsertNode(&testNode{"a"}) 50 g.InsertNode(&testNode{"b"}) 51 g.InsertNode(&testNode{"c"}) 52 53 require.EqualValues(t, &testNode{"a"}, g.Node("a")) 54 55 g.InsertEdge("a", "b", 1) 56 g.InsertEdge("b", "c", 1) 57 g.InsertEdge("c", "a", 1) 58 59 require.Equal(t, []string{"b"}, maps.Keys(g.OutEdges("a"))) 60 require.Equal(t, []string{"c"}, maps.Keys(g.InEdges("a"))) 61 62 require.EqualValues(t, 1, g.Edge("a", "b")) 63 64 g.DeleteEdge("a", "b") 65 require.False(t, g.HasEdge("a", "b")) 66 }) 67 68 t.Run("topological sort", func(t *testing.T) { 69 g := NewGraph[string, *testNode, testEdge]() 70 g.InsertNode(&testNode{"a"}) 71 g.InsertNode(&testNode{"b"}) 72 g.InsertNode(&testNode{"c"}) 73 g.InsertNode(&testNode{"d"}) 74 g.InsertNode(&testNode{"e"}) 75 76 g.InsertEdge("a", "b", 1) 77 g.InsertEdge("b", "c", 1) 78 g.InsertEdge("c", "d", 1) 79 g.InsertEdge("d", "e", 1) 80 81 require.Equal(t, []string{"a", "b", "c", "d", "e"}, testNodeIDs[string](g.TopologicalSort())) 82 }) 83 84 t.Run("shortest path", func(t *testing.T) { 85 g := NewGraph[string, *testNode, testEdge]() 86 g.InsertNode(&testNode{"a"}) 87 g.InsertNode(&testNode{"b"}) 88 g.InsertNode(&testNode{"c"}) 89 g.InsertNode(&testNode{"d"}) 90 91 g.InsertEdge("a", "b", 1) 92 g.InsertEdge("a", "c", 3) 93 g.InsertEdge("b", "d", 2) 94 g.InsertEdge("c", "d", 1) 95 96 p, n := g.ShortestPath("a", "d") 97 require.Equal(t, []string{"a", "b", "d"}, testNodeIDs[string](p)) 98 require.EqualValues(t, 3, n) 99 }) 100 }