lessor_test.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 lease
  15. import (
  16. "reflect"
  17. "testing"
  18. "time"
  19. )
  20. // TestLessorGrant ensures Lessor can grant wanted lease.
  21. // The granted lease should have a unique ID with a term
  22. // that is greater than minLeaseTerm.
  23. func TestLessorGrant(t *testing.T) {
  24. le := NewLessor(1)
  25. l := le.Grant(time.Now().Add(time.Second))
  26. gl := le.get(l.id)
  27. if !reflect.DeepEqual(gl, l) {
  28. t.Errorf("lease = %v, want %v", gl, l)
  29. }
  30. if l.expiry.Sub(time.Now()) < minLeaseTerm-time.Second {
  31. t.Errorf("term = %v, want at least %v", l.expiry.Sub(time.Now()), minLeaseTerm-time.Second)
  32. }
  33. nl := le.Grant(time.Now().Add(time.Second))
  34. if nl.id == l.id {
  35. t.Errorf("new lease.id = %x, want != %x", nl.id, l.id)
  36. }
  37. }
  38. // TestLessorRevoke ensures Lessor can revoke a lease.
  39. // The revoked lease cannot be got from Lessor again.
  40. func TestLessorRevoke(t *testing.T) {
  41. le := NewLessor(1)
  42. // grant a lease with long term (100 seconds) to
  43. // avoid early termination during the test.
  44. l := le.Grant(time.Now().Add(100 * time.Second))
  45. err := le.Revoke(l.id)
  46. if err != nil {
  47. t.Fatal("failed to revoke lease:", err)
  48. }
  49. if le.get(l.id) != nil {
  50. t.Errorf("got revoked lease %x", l.id)
  51. }
  52. }
  53. // TestLessorRenew ensures Lessor can renew an existing lease.
  54. func TestLessorRenew(t *testing.T) {
  55. le := NewLessor(1)
  56. l := le.Grant(time.Now().Add(5 * time.Second))
  57. le.Renew(l.id, time.Now().Add(100*time.Second))
  58. l = le.get(l.id)
  59. if l.expiry.Sub(time.Now()) < 95*time.Second {
  60. t.Errorf("failed to renew the lease for 100 seconds")
  61. }
  62. }