-
Notifications
You must be signed in to change notification settings - Fork 0
/
lease_test.go
111 lines (80 loc) · 2.58 KB
/
lease_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
"time"
gc "gopkg.in/check.v1"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/lease"
)
const (
testCollectionName = "test collection"
testNamespace = "leadership-stub-service"
testId = "stub-unit/0"
testDuration = 30 * time.Hour
)
var (
_ = gc.Suite(&leaseSuite{})
)
//
// Stub functions for when we don't care.
//
func stubRunTransaction(ops []txn.Op) error {
return nil
}
func stubGetCollection(collectionName string) (stateCollection, func()) {
return &genericStateCollection{}, func() {}
}
type leaseSuite struct{}
func (s *leaseSuite) TestWriteToken(c *gc.C) {
tok := lease.Token{testNamespace, testId, time.Now().Add(testDuration)}
stubRunTransaction := func(ops []txn.Op) error {
c.Assert(ops, gc.HasLen, 2)
// First delete.
c.Check(ops[0].C, gc.Equals, testCollectionName)
c.Check(ops[0].Remove, gc.Equals, true)
c.Check(ops[0].Id, gc.Equals, testId)
// Then insert.
c.Check(ops[1].Assert, gc.Equals, txn.DocMissing)
c.Check(ops[1].C, gc.Equals, testCollectionName)
c.Check(ops[1].Insert.(leaseEntity).Token, gc.DeepEquals, tok)
c.Check(ops[1].Id, gc.Equals, testId)
return nil
}
persistor := NewLeasePersistor(testCollectionName, stubRunTransaction, stubGetCollection)
err := persistor.WriteToken(testId, tok)
c.Assert(err, gc.IsNil)
}
func (s *leaseSuite) TestRemoveToken(c *gc.C) {
stubRunTransaction := func(ops []txn.Op) error {
c.Assert(ops, gc.HasLen, 1)
c.Check(ops[0].C, gc.Equals, testCollectionName)
c.Check(ops[0].Remove, gc.Equals, true)
c.Check(ops[0].Id, gc.Equals, testId)
return nil
}
persistor := NewLeasePersistor(testCollectionName, stubRunTransaction, stubGetCollection)
err := persistor.RemoveToken(testId)
c.Assert(err, gc.IsNil)
}
func (s *leaseSuite) TestPersistedTokens(c *gc.C) {
closerCallCount := 0
stubGetCollection := func(collectionName string) (stateCollection, func()) {
c.Check(collectionName, gc.Equals, testCollectionName)
return &genericStateCollection{}, func() { closerCallCount++ }
}
persistor := NewLeasePersistor(testCollectionName, stubRunTransaction, stubGetCollection)
// PersistedTokens will panic when it tries to use the empty collection.
defer func() {
r := recover()
c.Assert(r, gc.NotNil)
switch closerCallCount {
case 1:
case 0:
c.Errorf("The closer for the collection was never called.")
default:
c.Errorf("The closer for the collection was called too many times (%d).", closerCallCount)
}
}()
persistor.PersistedTokens()
}