github.com/grailbio/base@v0.0.11/ttlcache/ttlcache_test.go (about)

     1  // Copyright 2018 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache-2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package ttlcache_test
     6  
     7  import (
     8  	"math/rand"
     9  	"sync"
    10  	"testing"
    11  	"time"
    12  
    13  	"github.com/grailbio/base/ttlcache"
    14  )
    15  
    16  func TestCache(t *testing.T) {
    17  	for _, test := range []struct {
    18  		setKey   interface{}
    19  		setValue interface{}
    20  
    21  		getKey    interface{}
    22  		wantValue interface{}
    23  		wantFound bool
    24  	}{
    25  		{10, "10", 10, "10", true},
    26  		{10, "10", 11, nil, false},
    27  		{10, "10", nil, nil, false},
    28  	} {
    29  		c := ttlcache.New(time.Minute)
    30  		c.Set(test.setKey, test.setValue)
    31  		if gotValue, gotFound := c.Get(test.getKey); (gotFound != test.wantFound) || (gotValue != test.wantValue) {
    32  			t.Errorf("unexpected result for %+v: want (%v, %v), got (%v, %v)", test, test.wantFound, test.wantValue, gotFound, gotValue)
    33  		}
    34  	}
    35  }
    36  
    37  func TestCacheTTL(t *testing.T) {
    38  	d := 10 * time.Millisecond
    39  	c := ttlcache.New(d)
    40  	key, value := 10, "10"
    41  	c.Set(key, value)
    42  	if _, gotFound := c.Get(key); !gotFound {
    43  		t.Errorf("missing key in cache: %v", key)
    44  	}
    45  	time.Sleep(d)
    46  	if _, gotFound := c.Get(key); gotFound {
    47  		t.Errorf("unpexpected key in cache: %v", key)
    48  	}
    49  }
    50  
    51  // TestCacheConcurrent can fail implicitly by deadlocking.
    52  func TestCacheConcurrent(t *testing.T) {
    53  	c := ttlcache.New(time.Minute)
    54  	wg := sync.WaitGroup{}
    55  	deadline := time.Now().Add(100 * time.Millisecond)
    56  	key := 10
    57  	for i := 0; i < 10; i++ {
    58  		wg.Add(1)
    59  		go func(i int) {
    60  			loops := 0
    61  			for {
    62  				if time.Now().After(deadline) {
    63  					break
    64  				}
    65  				if rand.Int()%2 == 0 {
    66  					c.Get(key)
    67  				} else {
    68  					c.Set(key, i)
    69  				}
    70  				loops += 1
    71  			}
    72  			wg.Done()
    73  			t.Logf("loops %d: %d", i, loops)
    74  		}(i)
    75  	}
    76  	wg.Wait()
    77  }