heap_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package store
  2. import (
  3. "container/heap"
  4. "fmt"
  5. "testing"
  6. "time"
  7. )
  8. func TestHeapPushPop(t *testing.T) {
  9. h := newTTLKeyHeap()
  10. // add from older expire time to earlier expire time
  11. // the path is equal to ttl from now
  12. for i := 0; i < 10; i++ {
  13. path := fmt.Sprintf("%v", 10-i)
  14. m := time.Duration(10 - i)
  15. n := newKV(nil, path, path, 0, 0, nil, "", time.Now().Add(time.Second*m))
  16. heap.Push(h, n)
  17. }
  18. min := time.Now()
  19. for i := 0; i < 10; i++ {
  20. iNode := heap.Pop(h)
  21. node, _ := iNode.(*Node)
  22. if node.ExpireTime.Before(min) {
  23. t.Fatal("heap sort wrong!")
  24. }
  25. min = node.ExpireTime
  26. }
  27. }
  28. func TestHeapUpdate(t *testing.T) {
  29. h := &TTLKeyHeap{Map: make(map[*Node]int)}
  30. heap.Init(h)
  31. kvs := make([]*Node, 10)
  32. // add from older expire time to earlier expire time
  33. // the path is equal to ttl from now
  34. for i, n := range kvs {
  35. path := fmt.Sprintf("%v", 10-i)
  36. m := time.Duration(10 - i)
  37. n = newKV(nil, path, path, 0, 0, nil, "", time.Now().Add(time.Second*m))
  38. kvs[i] = n
  39. heap.Push(h, n)
  40. }
  41. // Path 7
  42. kvs[3].ExpireTime = time.Now().Add(time.Second * 11)
  43. // Path 5
  44. kvs[5].ExpireTime = time.Now().Add(time.Second * 12)
  45. h.update(kvs[3])
  46. h.update(kvs[5])
  47. min := time.Now()
  48. for i := 0; i < 10; i++ {
  49. iNode := heap.Pop(h)
  50. node, _ := iNode.(*Node)
  51. if node.ExpireTime.Before(min) {
  52. t.Fatal("heap sort wrong!")
  53. }
  54. min = node.ExpireTime
  55. if i == 8 {
  56. if node.Path != "7" {
  57. t.Fatal("heap sort wrong!", node.Path)
  58. }
  59. }
  60. if i == 9 {
  61. if node.Path != "5" {
  62. t.Fatal("heap sort wrong!")
  63. }
  64. }
  65. }
  66. }