diff --git a/common/cmap.go b/common/cmap.go index e2a140dd0..c65c27d4c 100644 --- a/common/cmap.go +++ b/common/cmap.go @@ -51,6 +51,17 @@ func (cm *CMap) Clear() { cm.m = make(map[string]interface{}) } +func (cm *CMap) Keys() []string { + cm.l.Lock() + defer cm.l.Unlock() + + keys := []string{} + for k := range cm.m { + keys = append(keys, k) + } + return keys +} + func (cm *CMap) Values() []interface{} { cm.l.Lock() defer cm.l.Unlock() diff --git a/common/cmap_test.go b/common/cmap_test.go new file mode 100644 index 000000000..a04f0a7d2 --- /dev/null +++ b/common/cmap_test.go @@ -0,0 +1,63 @@ +package common + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIterateKeysWithValues(t *testing.T) { + cmap := NewCMap() + + for i := 1; i <= 10; i++ { + cmap.Set(fmt.Sprintf("key%d", i), fmt.Sprintf("value%d", i)) + } + + // Testing size + assert.Equal(t, cmap.Size(), 10, "overall size should be 10") + assert.Equal(t, len(cmap.Keys()), 10, "should be 10 keys") + assert.Equal(t, len(cmap.Values()), 10, "should be 10 values") + + // Iterating Keys, checking for matching Value + for _, key := range cmap.Keys() { + val := strings.Replace(key, "key", "value", -1) + assert.Equal(t, cmap.Get(key), val) + } + + // Test if all keys are within []Keys() + keys := cmap.Keys() + for i := 1; i <= 10; i++ { + assert.True(t, contains(keys, fmt.Sprintf("key%d", i)), "cmap.Keys() should contain key") + } + + // Delete 1 Key + cmap.Delete("key1") + + assert.NotEqual(t, len(keys), len(cmap.Keys()), "[]keys and []Keys() should not be equal, they are copies, one item was removed") + +} + +func TestContains(t *testing.T) { + cmap := NewCMap() + + cmap.Set("key1", "value1") + + // Test for known values + assert.True(t, cmap.Has("key1"), "should contain key1") + assert.Equal(t, cmap.Get("key1"), "value1", "key1.value() should be value1") + + // Test for unknown values + assert.False(t, cmap.Has("key2"), "should not contain key2") + assert.Nil(t, cmap.Get("key2"), "does not contain key2") +} + +func contains(array []string, value string) (bool) { + for _, val := range array { + if val == value { + return true + } + } + return false +}