Browse Source

Make iterating over keys possible (#63)

* Make iterating over keys possible

* add test for cmap
- test Keys() and Values() respectively

* one cmap per test-case
pull/1842/head
Wolf 7 years ago
committed by Anton Kaliaev
parent
commit
88481fc363
2 changed files with 74 additions and 0 deletions
  1. +11
    -0
      common/cmap.go
  2. +63
    -0
      common/cmap_test.go

+ 11
- 0
common/cmap.go View File

@ -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()


+ 63
- 0
common/cmap_test.go View File

@ -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
}

Loading…
Cancel
Save