heap_test.go 1.5 KB

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