| 1 |
// Copyright 2017-present The Hugo Authors. All rights reserved. |
| 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 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package types |
| 15 |
|
| 16 |
import ( |
| 17 |
"sync" |
| 18 |
"testing" |
| 19 |
|
| 20 |
qt "github.com/frankban/quicktest" |
| 21 |
) |
| 22 |
|
| 23 |
func TestEvictingStringQueue(t *testing.T) { |
| 24 |
c := qt.New(t) |
| 25 |
|
| 26 |
queue := NewEvictingQueue[string](3) |
| 27 |
|
| 28 |
c.Assert(queue.Peek(), qt.Equals, "") |
| 29 |
queue.Add("a") |
| 30 |
queue.Add("b") |
| 31 |
queue.Add("a") |
| 32 |
c.Assert(queue.Peek(), qt.Equals, "b") |
| 33 |
queue.Add("b") |
| 34 |
c.Assert(queue.Peek(), qt.Equals, "b") |
| 35 |
|
| 36 |
queue.Add("a") |
| 37 |
queue.Add("b") |
| 38 |
|
| 39 |
c.Assert(queue.Contains("a"), qt.Equals, true) |
| 40 |
c.Assert(queue.Contains("foo"), qt.Equals, false) |
| 41 |
|
| 42 |
c.Assert(queue.PeekAll(), qt.DeepEquals, []string{"b", "a"}) |
| 43 |
c.Assert(queue.Peek(), qt.Equals, "b") |
| 44 |
queue.Add("c") |
| 45 |
queue.Add("d") |
| 46 |
// Overflowed, a should now be removed. |
| 47 |
c.Assert(queue.PeekAll(), qt.DeepEquals, []string{"d", "c", "b"}) |
| 48 |
c.Assert(len(queue.PeekAllSet()), qt.Equals, 3) |
| 49 |
c.Assert(queue.PeekAllSet()["c"], qt.Equals, true) |
| 50 |
} |
| 51 |
|
| 52 |
func TestEvictingStringQueueConcurrent(t *testing.T) { |
| 53 |
var wg sync.WaitGroup |
| 54 |
val := "someval" |
| 55 |
|
| 56 |
queue := NewEvictingQueue[string](3) |
| 57 |
|
| 58 |
for range 100 { |
| 59 |
wg.Go(func() { |
| 60 |
queue.Add(val) |
| 61 |
v := queue.Peek() |
| 62 |
if v != val { |
| 63 |
t.Error("wrong val") |
| 64 |
} |
| 65 |
vals := queue.PeekAll() |
| 66 |
if len(vals) != 1 || vals[0] != val { |
| 67 |
t.Error("wrong val") |
| 68 |
} |
| 69 |
}) |
| 70 |
} |
| 71 |
wg.Wait() |
| 72 |
} |