heap_test.go 1.4 KB

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