github.com/unionj-cloud/go-doudou/v2@v2.3.5/toolkit/cache/local_test.go (about)

     1  package cache_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"math/rand"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/unionj-cloud/go-doudou/v2/toolkit/cache"
    11  )
    12  
    13  func TestTinyLFU_Get_CorruptionOnExpiry(t *testing.T) {
    14  	strFor := func(i int) string {
    15  		return fmt.Sprintf("a string %d", i)
    16  	}
    17  	keyName := func(i int) string {
    18  		return fmt.Sprintf("key-%00000d", i)
    19  	}
    20  
    21  	mycache := cache.NewTinyLFU(1000, 1*time.Second)
    22  	size := 50000
    23  	// Put a bunch of stuff in the cache with a TTL of 1 second
    24  	for i := 0; i < size; i++ {
    25  		key := keyName(i)
    26  		mycache.Set(key, []byte(strFor(i)))
    27  	}
    28  
    29  	// Read stuff for a bit longer than the TTL - that's when the corruption occurs
    30  	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    31  	defer cancel()
    32  
    33  	done := ctx.Done()
    34  loop:
    35  	for {
    36  		select {
    37  		case <-done:
    38  			// this is expected
    39  			break loop
    40  		default:
    41  			i := rand.Intn(size)
    42  			key := keyName(i)
    43  
    44  			b, ok := mycache.Get(key)
    45  			if !ok {
    46  				continue loop
    47  			}
    48  
    49  			got := string(b)
    50  			expected := strFor(i)
    51  			if got != expected {
    52  				t.Fatalf("expected=%q got=%q key=%q", expected, got, key)
    53  			}
    54  		}
    55  	}
    56  }