github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/container/concurrent_map/concurrent_map_test.go (about)

     1  package concurrent_map
     2  
     3  import (
     4  	"math/rand"
     5  	"strconv"
     6  	"testing"
     7  )
     8  
     9  func TestStringKeyOPs(t *testing.T) {
    10  	for i := 0; i < 10; i++ {
    11  		testV := rand.Intn(1000)
    12  		m := CreateConcurrentMap(99)
    13  		v, ok := m.Get(StrKey("Hello"))
    14  		if v != nil || ok != false {
    15  			t.Error("init/get failed")
    16  		}
    17  		m.Set(StrKey("Hello"), testV)
    18  		v, ok = m.Get(StrKey("Hello"))
    19  		if v.(int) != testV || ok != true {
    20  			t.Error("set/get failed.")
    21  		}
    22  		m.Del(StrKey("Hello"))
    23  		v, ok = m.Get(StrKey("Hello"))
    24  		if v != nil || ok != false {
    25  			t.Error("del failed")
    26  		}
    27  
    28  	}
    29  }
    30  
    31  func TestInt64KeyBasicOPs(t *testing.T) {
    32  	for i := 0; i < 10; i++ {
    33  		testV := rand.Int63n(1024)
    34  		cm := CreateConcurrentMap(99)
    35  		var key int64 = 1023
    36  		v, ok := cm.Get(I64Key(key))
    37  		if v != nil || ok != false {
    38  			t.Error("init/get failed")
    39  		}
    40  		cm.Set(I64Key(key), testV)
    41  		v, ok = cm.Get(I64Key(key))
    42  		if v.(int64) != testV || ok != true {
    43  			t.Error("set/get failed.")
    44  		}
    45  		cm.Del(I64Key(key))
    46  		v, ok = cm.Get(I64Key(key))
    47  		if v != nil || ok != false {
    48  			t.Error("del failed")
    49  		}
    50  	}
    51  }
    52  
    53  func TestConcurrentMap_IterBuffFromSnapshot(t *testing.T) {
    54  	m := CreateConcurrentMap(99)
    55  
    56  	cn := 100
    57  	for i := 0; i < cn; i++ {
    58  		m.Set(StrKey("Hello"+strconv.Itoa(i)), i)
    59  	}
    60  
    61  	counter := 0
    62  	for item := range m.IterBuffFromSnapshot() {
    63  		val := item.Val
    64  		if val == nil {
    65  			t.Error("Expecting an object.")
    66  		}
    67  		//t.Log("iter val", val)
    68  		counter++
    69  	}
    70  
    71  	if counter != cn {
    72  		t.Error("IterBuff fail counter != cn", counter, cn)
    73  	}
    74  }
    75  
    76  func GetCurrentMap(cn int) (m *ConcurrentMap) {
    77  	m = CreateConcurrentMap(99)
    78  
    79  	for i := 0; i < cn; i++ {
    80  		m.Set(StrKey("Hello"+strconv.Itoa(i)), i)
    81  	}
    82  
    83  	return
    84  }
    85  
    86  func TestConcurrentMap_Clear(t *testing.T) {
    87  	m := GetCurrentMap(100)
    88  	cn := m.Count()
    89  	if cn != 100 {
    90  		t.Error("count err cn!=100")
    91  	}
    92  
    93  	m.Clear()
    94  
    95  	cn = m.Count()
    96  	if cn != 0 {
    97  		t.Error("after clear count err cn!=0")
    98  	}
    99  }