heap_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package store
  14. import (
  15. "fmt"
  16. "testing"
  17. "time"
  18. )
  19. func TestHeapPushPop(t *testing.T) {
  20. h := newTtlKeyHeap()
  21. // add from older expire time to earlier expire time
  22. // the path is equal to ttl from now
  23. for i := 0; i < 10; i++ {
  24. path := fmt.Sprintf("%v", 10-i)
  25. m := time.Duration(10 - i)
  26. n := newKV(nil, path, path, 0, nil, "", time.Now().Add(time.Second*m))
  27. h.push(n)
  28. }
  29. min := time.Now()
  30. for i := 0; i < 10; i++ {
  31. node := h.pop()
  32. if node.ExpireTime.Before(min) {
  33. t.Fatal("heap sort wrong!")
  34. }
  35. min = node.ExpireTime
  36. }
  37. }
  38. func TestHeapUpdate(t *testing.T) {
  39. h := newTtlKeyHeap()
  40. kvs := make([]*node, 10)
  41. // add from older expire time to earlier expire time
  42. // the path is equal to ttl from now
  43. for i, n := range kvs {
  44. path := fmt.Sprintf("%v", 10-i)
  45. m := time.Duration(10 - i)
  46. n = newKV(nil, path, path, 0, nil, "", time.Now().Add(time.Second*m))
  47. kvs[i] = n
  48. h.push(n)
  49. }
  50. // Path 7
  51. kvs[3].ExpireTime = time.Now().Add(time.Second * 11)
  52. // Path 5
  53. kvs[5].ExpireTime = time.Now().Add(time.Second * 12)
  54. h.update(kvs[3])
  55. h.update(kvs[5])
  56. min := time.Now()
  57. for i := 0; i < 10; i++ {
  58. node := h.pop()
  59. if node.ExpireTime.Before(min) {
  60. t.Fatal("heap sort wrong!")
  61. }
  62. min = node.ExpireTime
  63. if i == 8 {
  64. if node.Path != "7" {
  65. t.Fatal("heap sort wrong!", node.Path)
  66. }
  67. }
  68. if i == 9 {
  69. if node.Path != "5" {
  70. t.Fatal("heap sort wrong!")
  71. }
  72. }
  73. }
  74. }