github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/state/lease/util_test.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package lease_test
     5  
     6  import (
     7  	"time"
     8  
     9  	jujutxn "github.com/juju/txn"
    10  	"github.com/juju/utils/clock"
    11  	"gopkg.in/mgo.v2"
    12  
    13  	"github.com/juju/juju/mongo"
    14  )
    15  
    16  // Clock exposes time via Now, and can be controlled via Reset and Advance. It
    17  // can be configured to Advance automatically whenever Now is called. Attempts
    18  // to call Alarm will panic: they're not useful to a clock.Client itself, but
    19  // are extremely helpful when driving one.
    20  type Clock struct {
    21  	clock.Clock
    22  	now  time.Time
    23  	step time.Duration
    24  }
    25  
    26  // NewClock returns a *Clock, set to now, that advances by step whenever Now()
    27  // is called.
    28  func NewClock(now time.Time, step time.Duration) *Clock {
    29  	return &Clock{now: now, step: step}
    30  }
    31  
    32  // Now is part of the clock.Clock interface.
    33  func (clock *Clock) Now() time.Time {
    34  	defer clock.Advance(clock.step)
    35  	return clock.now
    36  }
    37  
    38  // Reset causes the clock to act as though it had just been created with
    39  // NewClock(now, step).
    40  func (clock *Clock) Reset(now time.Time, step time.Duration) {
    41  	clock.now = now
    42  }
    43  
    44  // Advance advances the clock by the supplied time.
    45  func (clock *Clock) Advance(duration time.Duration) {
    46  	clock.now = clock.now.Add(duration)
    47  }
    48  
    49  // Mongo exposes database operations. It uses a real database -- we can't mock
    50  // mongo out, we need to check it really actually works -- but it's good to
    51  // have the runner accessible for adversarial transaction tests.
    52  type Mongo struct {
    53  	database *mgo.Database
    54  	runner   jujutxn.Runner
    55  }
    56  
    57  // NewMongo returns a *Mongo backed by the supplied database.
    58  func NewMongo(database *mgo.Database) *Mongo {
    59  	return &Mongo{
    60  		database: database,
    61  		runner: jujutxn.NewRunner(jujutxn.RunnerParams{
    62  			Database: database,
    63  		}),
    64  	}
    65  }
    66  
    67  // GetCollection is part of the lease.Mongo interface.
    68  func (m *Mongo) GetCollection(name string) (mongo.Collection, func()) {
    69  	return mongo.CollectionFromName(m.database, name)
    70  }
    71  
    72  // RunTransaction is part of the lease.Mongo interface.
    73  func (m *Mongo) RunTransaction(getTxn jujutxn.TransactionSource) error {
    74  	return m.runner.Run(getTxn)
    75  }