github.com/anakojm/hugo-katex@v0.0.0-20231023141351-42d6f5de9c0b/cache/namedmemcache/named_cache_test.go (about)

     1  // Copyright 2018 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 namedmemcache
    15  
    16  import (
    17  	"fmt"
    18  	"sync"
    19  	"testing"
    20  
    21  	qt "github.com/frankban/quicktest"
    22  )
    23  
    24  func TestNamedCache(t *testing.T) {
    25  	t.Parallel()
    26  	c := qt.New(t)
    27  
    28  	cache := New()
    29  
    30  	counter := 0
    31  	create := func() (any, error) {
    32  		counter++
    33  		return counter, nil
    34  	}
    35  
    36  	for i := 0; i < 5; i++ {
    37  		v1, err := cache.GetOrCreate("a1", create)
    38  		c.Assert(err, qt.IsNil)
    39  		c.Assert(v1, qt.Equals, 1)
    40  		v2, err := cache.GetOrCreate("a2", create)
    41  		c.Assert(err, qt.IsNil)
    42  		c.Assert(v2, qt.Equals, 2)
    43  	}
    44  
    45  	cache.Clear()
    46  
    47  	v3, err := cache.GetOrCreate("a2", create)
    48  	c.Assert(err, qt.IsNil)
    49  	c.Assert(v3, qt.Equals, 3)
    50  }
    51  
    52  func TestNamedCacheConcurrent(t *testing.T) {
    53  	t.Parallel()
    54  
    55  	c := qt.New(t)
    56  
    57  	var wg sync.WaitGroup
    58  
    59  	cache := New()
    60  
    61  	create := func(i int) func() (any, error) {
    62  		return func() (any, error) {
    63  			return i, nil
    64  		}
    65  	}
    66  
    67  	for i := 0; i < 10; i++ {
    68  		wg.Add(1)
    69  		go func() {
    70  			defer wg.Done()
    71  			for j := 0; j < 100; j++ {
    72  				id := fmt.Sprintf("id%d", j)
    73  				v, err := cache.GetOrCreate(id, create(j))
    74  				c.Assert(err, qt.IsNil)
    75  				c.Assert(v, qt.Equals, j)
    76  			}
    77  		}()
    78  	}
    79  	wg.Wait()
    80  }