Debian Codegraph @

resources/page/pages_cache_test.go

raw
1 // Copyright 2019 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 page
15
16 import (
17 "strconv"
18 "sync"
19 "sync/atomic"
20 "testing"
21
22 qt "github.com/frankban/quicktest"
23 )
24
25 func TestPageCache(t *testing.T) {
26 t.Parallel()
27 c := qt.New(t)
28 c1 := newPageCache()
29
30 changeFirst := func(p Pages) {
31 p[0].(*testPage).description = "changed"
32 }
33
34 var o1 atomic.Uint64
35 var o2 atomic.Uint64
36
37 var wg sync.WaitGroup
38
39 var l1 sync.Mutex
40 var l2 sync.Mutex
41
42 var testPageSets []Pages
43
44 for i := range 50 {
45 testPageSets = append(testPageSets, createSortTestPages(i+1))
46 }
47
48 for range 100 {
49 wg.Go(func() {
50 for k, pages := range testPageSets {
51 l1.Lock()
52 p, ca := c1.get("k1", nil, pages)
53 c.Assert(ca, qt.Equals, !o1.CompareAndSwap(uint64(k), uint64(k+1)))
54 l1.Unlock()
55 p2, c2 := c1.get("k1", nil, p)
56 c.Assert(c2, qt.Equals, true)
57 c.Assert(pagesEqual(p, p2), qt.Equals, true)
58 c.Assert(pagesEqual(p, pages), qt.Equals, true)
59 c.Assert(p, qt.Not(qt.IsNil))
60
61 l2.Lock()
62 p3, c3 := c1.get("k2", changeFirst, pages)
63 c.Assert(c3, qt.Equals, !o2.CompareAndSwap(uint64(k), uint64(k+1)))
64 l2.Unlock()
65 c.Assert(p3, qt.Not(qt.IsNil))
66 c.Assert("changed", qt.Equals, p3[0].(*testPage).description)
67 }
68 })
69 }
70 wg.Wait()
71 }
72
73 func BenchmarkPageCache(b *testing.B) {
74 cache := newPageCache()
75 pages := make(Pages, 30)
76 for i := range 30 {
77 pages[i] = &testPage{title: "p" + strconv.Itoa(i)}
78 }
79 key := "key"
80
81 for b.Loop() {
82 cache.getP(key, nil, pages)
83 }
84 }