| 1 |
// Copyright 2021 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 navigation |
| 15 |
|
| 16 |
import ( |
| 17 |
"slices" |
| 18 |
"sync" |
| 19 |
"sync/atomic" |
| 20 |
"testing" |
| 21 |
|
| 22 |
qt "github.com/frankban/quicktest" |
| 23 |
) |
| 24 |
|
| 25 |
func createSortTestMenu(num int) Menu { |
| 26 |
menu := make(Menu, num) |
| 27 |
for i := range num { |
| 28 |
m := &MenuEntry{} |
| 29 |
menu[i] = m |
| 30 |
} |
| 31 |
return menu |
| 32 |
} |
| 33 |
|
| 34 |
func TestMenuCache(t *testing.T) { |
| 35 |
t.Parallel() |
| 36 |
c := qt.New(t) |
| 37 |
c1 := newMenuCache() |
| 38 |
|
| 39 |
changeFirst := func(m Menu) { |
| 40 |
m[0].MenuConfig.Title = "changed" |
| 41 |
} |
| 42 |
|
| 43 |
var o1 uint64 |
| 44 |
var o2 uint64 |
| 45 |
|
| 46 |
var wg sync.WaitGroup |
| 47 |
|
| 48 |
var l1 sync.Mutex |
| 49 |
var l2 sync.Mutex |
| 50 |
|
| 51 |
var testMenuSets []Menu |
| 52 |
|
| 53 |
for i := range 50 { |
| 54 |
testMenuSets = append(testMenuSets, createSortTestMenu(i+1)) |
| 55 |
} |
| 56 |
|
| 57 |
for range 100 { |
| 58 |
wg.Go(func() { |
| 59 |
for k, menu := range testMenuSets { |
| 60 |
l1.Lock() |
| 61 |
m, ca := c1.get("k1", nil, menu) |
| 62 |
c.Assert(ca, qt.Equals, !atomic.CompareAndSwapUint64(&o1, uint64(k), uint64(k+1))) |
| 63 |
l1.Unlock() |
| 64 |
m2, c2 := c1.get("k1", nil, m) |
| 65 |
c.Assert(c2, qt.Equals, true) |
| 66 |
c.Assert(slices.Equal(m, m2), qt.Equals, true) |
| 67 |
c.Assert(slices.Equal(m, menu), qt.Equals, true) |
| 68 |
c.Assert(m, qt.Not(qt.IsNil)) |
| 69 |
|
| 70 |
l2.Lock() |
| 71 |
m3, c3 := c1.get("k2", changeFirst, menu) |
| 72 |
c.Assert(c3, qt.Equals, !atomic.CompareAndSwapUint64(&o2, uint64(k), uint64(k+1))) |
| 73 |
l2.Unlock() |
| 74 |
c.Assert(m3, qt.Not(qt.IsNil)) |
| 75 |
c.Assert("changed", qt.Equals, m3[0].Title) |
| 76 |
} |
| 77 |
}) |
| 78 |
} |
| 79 |
wg.Wait() |
| 80 |
} |