github.com/prebid/prebid-server/v2@v2.18.0/stored_requests/caches/memory/cache_test.go (about)

     1  package memory
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"math/rand"
     7  	"strconv"
     8  	"testing"
     9  
    10  	"github.com/prebid/prebid-server/v2/stored_requests"
    11  	"github.com/prebid/prebid-server/v2/stored_requests/caches/cachestest"
    12  )
    13  
    14  func TestLRURobustness(t *testing.T) {
    15  	cachestest.AssertCacheRobustness(t, func() stored_requests.CacheJSON {
    16  		return NewCache(256*1024, -1, "TestData")
    17  	})
    18  }
    19  
    20  func TestUnboundedRobustness(t *testing.T) {
    21  	cachestest.AssertCacheRobustness(t, func() stored_requests.CacheJSON {
    22  		return NewCache(0, -1, "TestData")
    23  	})
    24  }
    25  
    26  func TestRaceLRUConcurrency(t *testing.T) {
    27  	cache := NewCache(256*1024, -1, "TestData")
    28  	doRaceTest(t, cache)
    29  }
    30  
    31  func TestRaceUnboundedConcurrency(t *testing.T) {
    32  	cache := NewCache(0, -1, "TestData")
    33  
    34  	doRaceTest(t, cache)
    35  }
    36  
    37  func doRaceTest(t *testing.T, cache stored_requests.CacheJSON) {
    38  	done := make(chan struct{})
    39  	sets := [][]int{rand.Perm(100), rand.Perm(100), rand.Perm(100)}
    40  
    41  	readOrder := rand.Perm(3)
    42  	writeOrder := rand.Perm(3)
    43  	invalidateOrder := rand.Perm(3)
    44  	for i := 0; i < 3; i++ {
    45  		go writeLots(cache, done, sets[writeOrder[i]])
    46  		go readLots(cache, done, sets[readOrder[i]])
    47  		go invalidateLots(cache, done, sets[invalidateOrder[i]])
    48  	}
    49  
    50  	for i := 0; i < 9; i++ {
    51  		<-done
    52  	}
    53  }
    54  
    55  func readLots(cache stored_requests.CacheJSON, done chan<- struct{}, reads []int) {
    56  	var s struct{}
    57  	for _, i := range reads {
    58  		cache.Get(context.Background(), sliceForVal(i))
    59  	}
    60  	done <- s
    61  }
    62  
    63  func writeLots(cache stored_requests.CacheJSON, done chan<- struct{}, writes []int) {
    64  	var s struct{}
    65  	for _, i := range writes {
    66  		cache.Save(context.Background(), mapForVal(i))
    67  	}
    68  	done <- s
    69  }
    70  
    71  func invalidateLots(cache stored_requests.CacheJSON, done chan<- struct{}, invalidates []int) {
    72  	var s struct{}
    73  	for _, i := range invalidates {
    74  		cache.Invalidate(context.Background(), sliceForVal(i))
    75  	}
    76  	done <- s
    77  }
    78  
    79  func mapForVal(val int) map[string]json.RawMessage {
    80  	return map[string]json.RawMessage{
    81  		strconv.Itoa(val): json.RawMessage(strconv.Itoa(val)),
    82  	}
    83  }
    84  
    85  func sliceForVal(val int) []string {
    86  	return []string{strconv.Itoa(val)}
    87  }