github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/timeoutqueue_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 "time" 20 21 "github.com/stretchr/testify/require" 22 ) 23 24 func debugTimeoutQueueItems[T any](q *TimeoutQueue[T]) []T { 25 var items []T 26 for i := q.head; i != nil; i = i.next { 27 items = append(items, i.Value) 28 } 29 return items 30 } 31 32 func TestTimeoutQueue(t *testing.T) { 33 t.Run("queue order matches insert order", func(t *testing.T) { 34 t.Parallel() 35 var q TimeoutQueue[int] 36 for i := 0; i < 5; i++ { 37 q.Reset(&TimeoutQueueItem[int]{Value: i}) 38 } 39 require.EqualValues(t, []int{0, 1, 2, 3, 4}, debugTimeoutQueueItems(&q)) 40 }) 41 42 t.Run("reset items do not affect order of other entries", func(t *testing.T) { 43 t.Parallel() 44 var q TimeoutQueue[int] 45 var its []*TimeoutQueueItem[int] 46 for i := 0; i < 5; i++ { 47 it := &TimeoutQueueItem[int]{Value: i} 48 its = append(its, it) 49 q.Reset(it) 50 } 51 52 q.Reset(its[1]) 53 require.EqualValues(t, []int{0, 2, 3, 4, 1}, debugTimeoutQueueItems(&q)) 54 q.Reset(its[3]) 55 require.EqualValues(t, []int{0, 2, 4, 1, 3}, debugTimeoutQueueItems(&q)) 56 q.Reset(its[2]) 57 require.EqualValues(t, []int{0, 4, 1, 3, 2}, debugTimeoutQueueItems(&q)) 58 }) 59 60 t.Run("popBefore removes items", func(t *testing.T) { 61 t.Parallel() 62 var q TimeoutQueue[int] 63 for i := 0; i < 5; i++ { 64 it := &TimeoutQueueItem[int]{Value: i} 65 q.Reset(it) 66 } 67 68 ts := time.Now() 69 q.popBefore(ts, true) 70 require.EqualValues(t, []int{1, 2, 3, 4}, debugTimeoutQueueItems(&q)) 71 q.popBefore(ts, true) 72 require.EqualValues(t, []int{2, 3, 4}, debugTimeoutQueueItems(&q)) 73 }) 74 }