heap_test.go 2.0 KB

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