github.com/kaituanwang/hyperledger@v2.0.1+incompatible/msp/cache/second_chance_test.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package cache
     8  
     9  import (
    10  	"fmt"
    11  	"sync"
    12  	"testing"
    13  
    14  	"github.com/stretchr/testify/assert"
    15  )
    16  
    17  func TestSecondChanceCache(t *testing.T) {
    18  	cache := newSecondChanceCache(2)
    19  	assert.NotNil(t, cache)
    20  
    21  	cache.add("a", "xyz")
    22  
    23  	obj, ok := cache.get("a")
    24  	assert.True(t, ok)
    25  	assert.Equal(t, "xyz", obj.(string))
    26  
    27  	cache.add("b", "123")
    28  
    29  	obj, ok = cache.get("b")
    30  	assert.True(t, ok)
    31  	assert.Equal(t, "123", obj.(string))
    32  
    33  	cache.add("c", "777")
    34  
    35  	obj, ok = cache.get("c")
    36  	assert.True(t, ok)
    37  	assert.Equal(t, "777", obj.(string))
    38  
    39  	_, ok = cache.get("a")
    40  	assert.False(t, ok)
    41  
    42  	_, ok = cache.get("b")
    43  	assert.True(t, ok)
    44  
    45  	cache.add("b", "456")
    46  
    47  	obj, ok = cache.get("b")
    48  	assert.True(t, ok)
    49  	assert.Equal(t, "456", obj.(string))
    50  
    51  	cache.add("d", "555")
    52  
    53  	obj, ok = cache.get("b")
    54  	_, ok = cache.get("b")
    55  	assert.False(t, ok)
    56  }
    57  
    58  func TestSecondChanceCacheConcurrent(t *testing.T) {
    59  	cache := newSecondChanceCache(25)
    60  
    61  	workers := 16
    62  	wg := sync.WaitGroup{}
    63  	wg.Add(workers)
    64  
    65  	key1 := fmt.Sprintf("key1")
    66  	val1 := key1
    67  
    68  	for i := 0; i < workers; i++ {
    69  		id := i
    70  		key2 := fmt.Sprintf("key2-%d", i)
    71  		val2 := key2
    72  
    73  		go func() {
    74  			for j := 0; j < 10000; j++ {
    75  				key3 := fmt.Sprintf("key3-%d-%d", id, j)
    76  				val3 := key3
    77  				cache.add(key3, val3)
    78  
    79  				val, ok := cache.get(key1)
    80  				if ok {
    81  					assert.Equal(t, val1, val.(string))
    82  				}
    83  				cache.add(key1, val1)
    84  
    85  				val, ok = cache.get(key2)
    86  				if ok {
    87  					assert.Equal(t, val2, val.(string))
    88  				}
    89  				cache.add(key2, val2)
    90  
    91  				key4 := fmt.Sprintf("key4-%d", j)
    92  				val4 := key4
    93  				val, ok = cache.get(key4)
    94  				if ok {
    95  					assert.Equal(t, val4, val.(string))
    96  				}
    97  				cache.add(key4, val4)
    98  
    99  				val, ok = cache.get(key3)
   100  				if ok {
   101  					assert.Equal(t, val3, val.(string))
   102  				}
   103  			}
   104  
   105  			wg.Done()
   106  		}()
   107  	}
   108  	wg.Wait()
   109  }