map_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package treemap
  2. import (
  3. "github.com/stretchr/testify/assert"
  4. "testing"
  5. )
  6. func TestMap(t *testing.T) {
  7. m := New()
  8. assert.Equal(t, 0, m.Size())
  9. assert.False(t, m.Contains(5))
  10. assert.Equal(t, nil, m.Get(3))
  11. for i := 9; i >= 0; i-- {
  12. m.Insert(i, i+1000)
  13. }
  14. assert.Equal(t, 10, m.Size())
  15. assert.True(t, m.Contains(5))
  16. assert.Equal(t, 3+1000, m.Get(3))
  17. m.Erase(3)
  18. assert.Equal(t, nil, m.Get(3))
  19. m.Clear()
  20. assert.False(t, m.Contains(50))
  21. assert.Equal(t, 0, m.Size())
  22. }
  23. func TestMapIterator(t *testing.T) {
  24. m := New(WithGoroutineSafe())
  25. for i := 1; i <= 10; i++ {
  26. m.Insert(i, i)
  27. }
  28. i := 1
  29. for iter := m.First(); iter.IsValid(); iter.Next() {
  30. assert.Equal(t, i, iter.Value().(int))
  31. i++
  32. }
  33. i = 10
  34. for iter := m.Last().Clone().(*MapIterator); iter.IsValid(); iter.Prev() {
  35. assert.Equal(t, i, iter.Value().(int))
  36. i--
  37. }
  38. assert.True(t, m.Begin().Equal(m.First()))
  39. iter := m.Find(8)
  40. assert.Equal(t, 8, iter.Key().(int))
  41. assert.Equal(t, 8, iter.Value().(int))
  42. iter = m.LowerBound(8)
  43. assert.Equal(t, 8, iter.Value().(int))
  44. iter = m.UpperBound(6)
  45. assert.Equal(t, 7, iter.Value().(int))
  46. m.EraseIter(iter)
  47. assert.False(t, m.Contains(7))
  48. }
  49. func TestMapIteratorSetValue(t *testing.T) {
  50. m := New(WithGoroutineSafe())
  51. m.Insert(1, "aaa")
  52. m.Insert(2, "bbb")
  53. m.Insert(3, "hhh")
  54. assert.Equal(t, "aaa", m.Get(1))
  55. iter := m.Find(1)
  56. assert.Equal(t, "aaa", iter.Value())
  57. iter.SetValue("ccc")
  58. assert.Equal(t, "ccc", m.Get(1))
  59. }
  60. func TestMap_Traversal(t *testing.T) {
  61. m := New()
  62. for i := 1; i <= 5; i++ {
  63. m.Insert(i, i+1000)
  64. }
  65. i := 1
  66. m.Traversal(func(key, value interface{}) bool {
  67. assert.Equal(t, i, key)
  68. assert.Equal(t, i+1000, value)
  69. i++
  70. return true
  71. })
  72. }