github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/state/leadership/fixture_test.go (about) 1 // Copyright 2015 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package leadership_test 5 6 import ( 7 "time" 8 9 jc "github.com/juju/testing/checkers" 10 gc "gopkg.in/check.v1" 11 12 "github.com/juju/juju/state/leadership" 13 "github.com/juju/juju/state/lease" 14 "github.com/juju/juju/testing" 15 ) 16 17 var ( 18 defaultClockStart time.Time 19 almostOneSecond = time.Second - time.Nanosecond 20 ) 21 22 func init() { 23 // We pick a time with a comfortable h:m:s component but: 24 // (1) past the int32 unix epoch limit; 25 // (2) at a 5ns offset to make sure we're not discarding precision; 26 // (3) in a weird time zone. 27 value := "2073-03-03T01:00:00.000000005-08:40" 28 var err error 29 defaultClockStart, err = time.Parse(time.RFC3339Nano, value) 30 if err != nil { 31 panic(err) 32 } 33 } 34 35 // offset returns the result of defaultClockStart.Add(d); it exists to make 36 // exppiry tests easier to write. 37 func offset(d time.Duration) time.Time { 38 return defaultClockStart.Add(d) 39 } 40 41 // almostSeconds returns a duration smaller than the supplied number of 42 // seconds by one nanosecond. 43 func almostSeconds(seconds int) time.Duration { 44 if seconds < 1 { 45 panic("unexpected") 46 } 47 return (time.Second * time.Duration(seconds)) - time.Nanosecond 48 } 49 50 // Fixture allows us to test a leadership.ManagerWorker with a usefully-mocked 51 // clock.Clock and lease.Client. 52 type Fixture struct { 53 54 // leases contains the leases the lease.Client should report when the 55 // test starts up. 56 leases map[string]lease.Info 57 58 // expectCalls contains the calls that should be made to the lease.Client 59 // in the course of a test. By specifying a callback you can cause the 60 // reported leases to change. 61 expectCalls []call 62 63 // expectDirty should be set for tests that purposefully abuse the manager 64 // to the extent that it returns an error on Wait(); tests that don't set 65 // this flag will check that the manager's shutdown error is nil. 66 expectDirty bool 67 } 68 69 // RunTest sets up a Manager and a Clock and passes them into the supplied 70 // test function. The manager will be cleaned up afterwards. 71 func (fix *Fixture) RunTest(c *gc.C, test func(leadership.ManagerWorker, *testing.Clock)) { 72 clock := testing.NewClock(defaultClockStart) 73 client := NewClient(fix.leases, fix.expectCalls) 74 manager, err := leadership.NewManager(leadership.ManagerConfig{ 75 Clock: clock, 76 Client: client, 77 }) 78 c.Assert(err, jc.ErrorIsNil) 79 defer func() { 80 // Dirty tests will probably have stopped the manager anyway, but no 81 // sense leaving them around if things aren't exactly as we expect. 82 manager.Kill() 83 err := manager.Wait() 84 if !fix.expectDirty { 85 c.Check(err, jc.ErrorIsNil) 86 } 87 }() 88 defer client.Wait(c) 89 test(manager, clock) 90 }