lease_queue_test.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2018 The etcd Authors
  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 lease
  15. import (
  16. "testing"
  17. "time"
  18. )
  19. func TestLeaseQueue(t *testing.T) {
  20. expiredRetryInterval := 100 * time.Millisecond
  21. le := &lessor{
  22. leaseExpiredNotifier: newLeaseExpiredNotifier(),
  23. leaseMap: make(map[LeaseID]*Lease),
  24. expiredLeaseRetryInterval: expiredRetryInterval,
  25. }
  26. le.leaseExpiredNotifier.Init()
  27. // insert in reverse order of expiration time
  28. for i := 50; i >= 1; i-- {
  29. exp := time.Now().Add(time.Hour).UnixNano()
  30. if i == 1 {
  31. exp = time.Now().UnixNano()
  32. }
  33. le.leaseMap[LeaseID(i)] = &Lease{ID: LeaseID(i)}
  34. le.leaseExpiredNotifier.RegisterOrUpdate(&LeaseWithTime{id: LeaseID(i), time: exp})
  35. }
  36. // first element is expired.
  37. if le.leaseExpiredNotifier.Poll().id != LeaseID(1) {
  38. t.Fatalf("first item expected lease ID %d, got %d", LeaseID(1), le.leaseExpiredNotifier.Poll().id)
  39. }
  40. existExpiredEvent := func() {
  41. l, ok, more := le.expireExists()
  42. if l.ID != 1 {
  43. t.Fatalf("first item expected lease ID %d, got %d", 1, l.ID)
  44. }
  45. if !ok {
  46. t.Fatal("expect expiry lease exists")
  47. }
  48. if more {
  49. t.Fatal("expect no more expiry lease")
  50. }
  51. if le.leaseExpiredNotifier.Len() != 50 {
  52. t.Fatalf("expected the expired lease to be pushed back to the heap, heap size got %d", le.leaseExpiredNotifier.Len())
  53. }
  54. if le.leaseExpiredNotifier.Poll().id != LeaseID(1) {
  55. t.Fatalf("first item expected lease ID %d, got %d", LeaseID(1), le.leaseExpiredNotifier.Poll().id)
  56. }
  57. }
  58. noExpiredEvent := func() {
  59. // re-acquire the expired item, nothing exists
  60. _, ok, more := le.expireExists()
  61. if ok {
  62. t.Fatal("expect no expiry lease exists")
  63. }
  64. if more {
  65. t.Fatal("expect no more expiry lease")
  66. }
  67. }
  68. existExpiredEvent() // first acquire
  69. noExpiredEvent() // second acquire
  70. time.Sleep(expiredRetryInterval)
  71. existExpiredEvent() // acquire after retry interval
  72. }