github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/worker/statushistorypruner/worker_test.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package statushistorypruner_test
     5  
     6  import (
     7  	"time"
     8  
     9  	"github.com/juju/errors"
    10  	jc "github.com/juju/testing/checkers"
    11  	gc "gopkg.in/check.v1"
    12  
    13  	"github.com/juju/juju/state"
    14  	coretesting "github.com/juju/juju/testing"
    15  	"github.com/juju/juju/worker"
    16  	"github.com/juju/juju/worker/statushistorypruner"
    17  )
    18  
    19  type mockTimer struct {
    20  	period time.Duration
    21  	c      chan time.Time
    22  }
    23  
    24  func (t *mockTimer) Reset(d time.Duration) bool {
    25  	t.period = d
    26  	return true
    27  }
    28  
    29  func (t *mockTimer) CountDown() <-chan time.Time {
    30  	return t.c
    31  }
    32  
    33  func (t *mockTimer) fire() error {
    34  	select {
    35  	case t.c <- time.Time{}:
    36  	case <-time.After(coretesting.LongWait):
    37  		return errors.New("timed out waiting for pruner to run")
    38  	}
    39  	return nil
    40  }
    41  
    42  func newMockTimer(d time.Duration) worker.PeriodicTimer {
    43  	return &mockTimer{period: d,
    44  		c: make(chan time.Time),
    45  	}
    46  }
    47  
    48  var _ = gc.Suite(&statusHistoryPrunerSuite{})
    49  
    50  type statusHistoryPrunerSuite struct {
    51  	coretesting.BaseSuite
    52  }
    53  
    54  func (s *statusHistoryPrunerSuite) TestWorker(c *gc.C) {
    55  	var passedMaxLogs int
    56  	fakePruner := func(_ *state.State, maxLogs int) error {
    57  		passedMaxLogs = maxLogs
    58  		return nil
    59  	}
    60  	params := statushistorypruner.HistoryPrunerParams{
    61  		MaxLogsPerState: 3,
    62  		PruneInterval:   coretesting.ShortWait,
    63  	}
    64  	fakeTimer := newMockTimer(coretesting.LongWait)
    65  
    66  	fakeTimerFunc := func(d time.Duration) worker.PeriodicTimer {
    67  		// construction of timer should be with 0 because we intend it to
    68  		// run once before waiting.
    69  		c.Assert(d, gc.Equals, 0*time.Nanosecond)
    70  		return fakeTimer
    71  	}
    72  	pruner := statushistorypruner.NewPruneWorker(
    73  		&state.State{},
    74  		&params,
    75  		fakeTimerFunc,
    76  		fakePruner,
    77  	)
    78  	s.AddCleanup(func(*gc.C) {
    79  		pruner.Kill()
    80  		c.Assert(pruner.Wait(), jc.ErrorIsNil)
    81  	})
    82  	err := fakeTimer.(*mockTimer).fire()
    83  	c.Check(err, jc.ErrorIsNil)
    84  	c.Assert(passedMaxLogs, gc.Equals, 3)
    85  	// Reset will have been called with the actual PruneInterval
    86  	c.Assert(fakeTimer.(*mockTimer).period, gc.Equals, coretesting.ShortWait)
    87  }