github.com/jmooring/hugo@v0.47.1/hugolib/pageCache_test.go (about)

     1  // Copyright 2015 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 hugolib
    15  
    16  import (
    17  	"strconv"
    18  	"sync"
    19  	"sync/atomic"
    20  	"testing"
    21  
    22  	"github.com/stretchr/testify/assert"
    23  )
    24  
    25  func TestPageCache(t *testing.T) {
    26  	t.Parallel()
    27  	c1 := newPageCache()
    28  
    29  	changeFirst := func(p Pages) {
    30  		p[0].Description = "changed"
    31  	}
    32  
    33  	var o1 uint64
    34  	var o2 uint64
    35  
    36  	var wg sync.WaitGroup
    37  
    38  	var l1 sync.Mutex
    39  	var l2 sync.Mutex
    40  
    41  	var testPageSets []Pages
    42  
    43  	s := newTestSite(t)
    44  
    45  	for i := 0; i < 50; i++ {
    46  		testPageSets = append(testPageSets, createSortTestPages(s, i+1))
    47  	}
    48  
    49  	for j := 0; j < 100; j++ {
    50  		wg.Add(1)
    51  		go func() {
    52  			defer wg.Done()
    53  			for k, pages := range testPageSets {
    54  				l1.Lock()
    55  				p, c := c1.get("k1", nil, pages)
    56  				assert.Equal(t, !atomic.CompareAndSwapUint64(&o1, uint64(k), uint64(k+1)), c)
    57  				l1.Unlock()
    58  				p2, c2 := c1.get("k1", nil, p)
    59  				assert.True(t, c2)
    60  				assert.True(t, fastEqualPages(p, p2))
    61  				assert.True(t, fastEqualPages(p, pages))
    62  				assert.NotNil(t, p)
    63  
    64  				l2.Lock()
    65  				p3, c3 := c1.get("k2", changeFirst, pages)
    66  				assert.Equal(t, !atomic.CompareAndSwapUint64(&o2, uint64(k), uint64(k+1)), c3)
    67  				l2.Unlock()
    68  				assert.NotNil(t, p3)
    69  				assert.Equal(t, p3[0].Description, "changed")
    70  			}
    71  		}()
    72  	}
    73  	wg.Wait()
    74  }
    75  
    76  func BenchmarkPageCache(b *testing.B) {
    77  	cache := newPageCache()
    78  	pages := make(Pages, 30)
    79  	for i := 0; i < 30; i++ {
    80  		pages[i] = &Page{title: "p" + strconv.Itoa(i)}
    81  	}
    82  	key := "key"
    83  
    84  	b.ResetTimer()
    85  	for i := 0; i < b.N; i++ {
    86  		cache.getP(key, nil, pages)
    87  	}
    88  }