launchpad.net/~rogpeppe/juju-core/500-errgo-fix@v0.0.0-20140213181702-000000002356/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  	gc "launchpad.net/gocheck"
     8  	stdtesting "testing"
     9  	"time"
    10  
    11  	"launchpad.net/juju-core/juju/testing"
    12  	coretesting "launchpad.net/juju-core/testing"
    13  	"launchpad.net/juju-core/worker/resumer"
    14  )
    15  
    16  func TestPackage(t *stdtesting.T) {
    17  	coretesting.MgoTestPackage(t)
    18  }
    19  
    20  type ResumerSuite struct {
    21  	testing.JujuConnSuite
    22  }
    23  
    24  var _ = gc.Suite(&ResumerSuite{})
    25  
    26  func (s *ResumerSuite) TestRunStopWithState(c *gc.C) {
    27  	// Test with state ensures that state fulfills the
    28  	// TransactionResumer interface.
    29  	rr := resumer.NewResumer(s.State)
    30  
    31  	c.Assert(rr.Stop(), gc.IsNil)
    32  }
    33  
    34  func (s *ResumerSuite) TestResumerCalls(c *gc.C) {
    35  	// Shorter interval and mock help to count
    36  	// the resumer calls in a given timespan.
    37  	testInterval := 10 * time.Millisecond
    38  	resumer.SetInterval(testInterval)
    39  	defer resumer.RestoreInterval()
    40  
    41  	tr := &transactionResumerMock{[]time.Time{}}
    42  	rr := resumer.NewResumer(tr)
    43  	defer func() { c.Assert(rr.Stop(), gc.IsNil) }()
    44  
    45  	time.Sleep(10 * testInterval)
    46  
    47  	// Check that a numner of calls has happened with a time
    48  	// difference somewhere between the interval and twice the
    49  	// interval. A more precise time behavior cannot be
    50  	// specified due to the load during the test.
    51  	c.Assert(len(tr.timestamps) > 0, gc.Equals, true)
    52  	for i := 1; i < len(tr.timestamps); i++ {
    53  		diff := tr.timestamps[i].Sub(tr.timestamps[i-1])
    54  
    55  		c.Assert(diff >= testInterval, gc.Equals, true)
    56  		c.Assert(diff <= 2*testInterval, gc.Equals, true)
    57  	}
    58  }
    59  
    60  // transactionResumerMock is used to check the
    61  // calls of ResumeTransactions().
    62  type transactionResumerMock struct {
    63  	timestamps []time.Time
    64  }
    65  
    66  func (tr *transactionResumerMock) ResumeTransactions() error {
    67  	tr.timestamps = append(tr.timestamps, time.Now())
    68  	return nil
    69  }