github.com/qiniu/x@v1.11.9/objcache/objcache_test.go (about)

     1  package objcache
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  	"testing"
     7  )
     8  
     9  var (
    10  	once        sync.Once
    11  	stringGroup *Group
    12  	cacheFills  int64
    13  )
    14  
    15  const (
    16  	stringGroupName = "string-group"
    17  )
    18  
    19  type stringVal string
    20  
    21  func (p stringVal) Dispose() error {
    22  	return nil
    23  }
    24  
    25  func testSetup() {
    26  	stringGroup = NewGroup(stringGroupName, 0, func(ctx Context, key Key) (val Value, err error) {
    27  		atomic.AddInt64(&cacheFills, 1)
    28  		return stringVal("ECHO:" + key.(string)), nil
    29  	})
    30  }
    31  
    32  func countFills(f func()) int64 {
    33  	fills0 := atomic.LoadInt64(&cacheFills)
    34  	f()
    35  	return atomic.LoadInt64(&cacheFills) - fills0
    36  }
    37  
    38  func TestCaching(t *testing.T) {
    39  	once.Do(testSetup)
    40  	fills := countFills(func() {
    41  		for i := 0; i < 10; i++ {
    42  			_, err := stringGroup.Get(nil, "TestCaching-key")
    43  			if err != nil {
    44  				t.Fatal(err)
    45  			}
    46  		}
    47  	})
    48  	if fills != 1 {
    49  		t.Errorf("expected 1 cache fill; got %d", fills)
    50  	}
    51  }
    52  
    53  func TestGetVal(t *testing.T) {
    54  	val, err := stringGroup.Get(nil, "short")
    55  	if err != nil {
    56  		t.Fatal(err)
    57  	}
    58  	if want := "ECHO:short"; string(val.(stringVal)) != want {
    59  		t.Errorf("key got %q; want %q", val, want)
    60  	}
    61  }