You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.2 KiB

  1. package cmap
  2. import (
  3. "fmt"
  4. "strings"
  5. "sync"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. )
  9. func TestIterateKeysWithValues(t *testing.T) {
  10. cmap := NewCMap()
  11. for i := 1; i <= 10; i++ {
  12. cmap.Set(fmt.Sprintf("key%d", i), fmt.Sprintf("value%d", i))
  13. }
  14. // Testing size
  15. assert.Equal(t, 10, cmap.Size())
  16. assert.Equal(t, 10, len(cmap.Keys()))
  17. assert.Equal(t, 10, len(cmap.Values()))
  18. // Iterating Keys, checking for matching Value
  19. for _, key := range cmap.Keys() {
  20. val := strings.ReplaceAll(key, "key", "value")
  21. assert.Equal(t, val, cmap.Get(key))
  22. }
  23. // Test if all keys are within []Keys()
  24. keys := cmap.Keys()
  25. for i := 1; i <= 10; i++ {
  26. assert.Contains(t, keys, fmt.Sprintf("key%d", i), "cmap.Keys() should contain key")
  27. }
  28. // Delete 1 Key
  29. cmap.Delete("key1")
  30. assert.NotEqual(
  31. t,
  32. len(keys),
  33. len(cmap.Keys()),
  34. "[]keys and []Keys() should not be equal, they are copies, one item was removed",
  35. )
  36. }
  37. func TestContains(t *testing.T) {
  38. cmap := NewCMap()
  39. cmap.Set("key1", "value1")
  40. // Test for known values
  41. assert.True(t, cmap.Has("key1"))
  42. assert.Equal(t, "value1", cmap.Get("key1"))
  43. // Test for unknown values
  44. assert.False(t, cmap.Has("key2"))
  45. assert.Nil(t, cmap.Get("key2"))
  46. }
  47. func BenchmarkCMapHas(b *testing.B) {
  48. m := NewCMap()
  49. for i := 0; i < 1000; i++ {
  50. m.Set(string(rune(i)), i)
  51. }
  52. b.ResetTimer()
  53. for i := 0; i < b.N; i++ {
  54. m.Has(string(rune(i)))
  55. }
  56. }
  57. func TestCMap_GetOrSet_Parallel(t *testing.T) {
  58. tests := []struct {
  59. name string
  60. newValue interface{}
  61. parallelism int
  62. }{
  63. {"test1", "a", 4},
  64. {"test2", "a", 40},
  65. {"test3", "a", 1},
  66. }
  67. //nolint:scopelint
  68. for _, tt := range tests {
  69. t.Run(tt.name, func(t *testing.T) {
  70. cm := NewCMap()
  71. wg := sync.WaitGroup{}
  72. wg.Add(tt.parallelism)
  73. for i := 0; i < tt.parallelism; i++ {
  74. go func() {
  75. defer wg.Done()
  76. gotValue, _ := cm.GetOrSet(tt.name, tt.newValue)
  77. assert.EqualValues(t, tt.newValue, gotValue)
  78. }()
  79. }
  80. wg.Wait()
  81. })
  82. }
  83. }
  84. func TestCMap_GetOrSet_Exists(t *testing.T) {
  85. cm := NewCMap()
  86. gotValue, exists := cm.GetOrSet("key", 1000)
  87. assert.False(t, exists)
  88. assert.EqualValues(t, 1000, gotValue)
  89. gotValue, exists = cm.GetOrSet("key", 2000)
  90. assert.True(t, exists)
  91. assert.EqualValues(t, 1000, gotValue)
  92. }