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