github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/worker/resumer/resumer_test.go (about) 1 // Copyright 2013 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package resumer_test 5 6 import ( 7 "sync" 8 stdtesting "testing" 9 "time" 10 11 jc "github.com/juju/testing/checkers" 12 gc "gopkg.in/check.v1" 13 14 "github.com/juju/juju/juju/testing" 15 coretesting "github.com/juju/juju/testing" 16 "github.com/juju/juju/worker/resumer" 17 ) 18 19 func TestPackage(t *stdtesting.T) { 20 coretesting.MgoTestPackage(t) 21 } 22 23 type ResumerSuite struct { 24 testing.JujuConnSuite 25 } 26 27 var _ = gc.Suite(&ResumerSuite{}) 28 29 func (s *ResumerSuite) TestRunStopWithState(c *gc.C) { 30 // Test with state ensures that state fulfills the 31 // TransactionResumer interface. 32 rr := resumer.NewResumer(s.State) 33 34 c.Assert(rr.Stop(), gc.IsNil) 35 } 36 37 func (s *ResumerSuite) TestResumerCalls(c *gc.C) { 38 // Shorter interval and mock help to count 39 // the resumer calls in a given timespan. 40 testInterval := 10 * time.Millisecond 41 resumer.SetInterval(testInterval) 42 defer resumer.RestoreInterval() 43 44 var tr transactionResumerMock 45 rr := resumer.NewResumer(&tr) 46 defer func() { c.Assert(rr.Stop(), gc.IsNil) }() 47 48 time.Sleep(10 * testInterval) 49 50 // Check that a number of calls has happened with a time 51 // difference somewhere between the interval and twice the 52 // interval. A more precise time behavior cannot be 53 // specified due to the load during the test. 54 tr.mu.Lock() 55 defer tr.mu.Unlock() 56 c.Assert(len(tr.timestamps) > 0, jc.IsTrue) 57 for i := 1; i < len(tr.timestamps); i++ { 58 diff := tr.timestamps[i].Sub(tr.timestamps[i-1]) 59 60 c.Assert(diff >= testInterval, jc.IsTrue) 61 c.Assert(diff <= 4*testInterval, jc.IsTrue) 62 } 63 } 64 65 // transactionResumerMock is used to check the 66 // calls of ResumeTransactions(). 67 type transactionResumerMock struct { 68 mu sync.Mutex 69 timestamps []time.Time 70 } 71 72 func (tr *transactionResumerMock) ResumeTransactions() error { 73 tr.mu.Lock() 74 tr.timestamps = append(tr.timestamps, time.Now()) 75 tr.mu.Unlock() 76 return nil 77 }