safemap_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package collection
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. "github.com/tal-tech/go-zero/core/stringx"
  6. )
  7. func TestSafeMap(t *testing.T) {
  8. tests := []struct {
  9. size int
  10. exception int
  11. }{
  12. {
  13. 100000,
  14. 2000,
  15. },
  16. {
  17. 100000,
  18. 50,
  19. },
  20. }
  21. for _, test := range tests {
  22. t.Run(stringx.Rand(), func(t *testing.T) {
  23. testSafeMapWithParameters(t, test.size, test.exception)
  24. })
  25. }
  26. }
  27. func TestSafeMap_CopyNew(t *testing.T) {
  28. const (
  29. size = 100000
  30. exception1 = 5
  31. exception2 = 500
  32. )
  33. m := NewSafeMap()
  34. for i := 0; i < size; i++ {
  35. m.Set(i, i)
  36. }
  37. for i := 0; i < size; i++ {
  38. if i%exception1 == 0 {
  39. m.Del(i)
  40. }
  41. }
  42. for i := size; i < size<<1; i++ {
  43. m.Set(i, i)
  44. }
  45. for i := size; i < size<<1; i++ {
  46. if i%exception2 != 0 {
  47. m.Del(i)
  48. }
  49. }
  50. for i := 0; i < size; i++ {
  51. val, ok := m.Get(i)
  52. if i%exception1 != 0 {
  53. assert.True(t, ok)
  54. assert.Equal(t, i, val.(int))
  55. } else {
  56. assert.False(t, ok)
  57. }
  58. }
  59. for i := size; i < size<<1; i++ {
  60. val, ok := m.Get(i)
  61. if i%exception2 == 0 {
  62. assert.True(t, ok)
  63. assert.Equal(t, i, val.(int))
  64. } else {
  65. assert.False(t, ok)
  66. }
  67. }
  68. }
  69. func testSafeMapWithParameters(t *testing.T, size, exception int) {
  70. m := NewSafeMap()
  71. for i := 0; i < size; i++ {
  72. m.Set(i, i)
  73. }
  74. for i := 0; i < size; i++ {
  75. if i%exception != 0 {
  76. m.Del(i)
  77. }
  78. }
  79. assert.Equal(t, size/exception, m.Size())
  80. for i := size; i < size<<1; i++ {
  81. m.Set(i, i)
  82. }
  83. for i := size; i < size<<1; i++ {
  84. if i%exception != 0 {
  85. m.Del(i)
  86. }
  87. }
  88. for i := 0; i < size<<1; i++ {
  89. val, ok := m.Get(i)
  90. if i%exception == 0 {
  91. assert.True(t, ok)
  92. assert.Equal(t, i, val.(int))
  93. } else {
  94. assert.False(t, ok)
  95. }
  96. }
  97. }