github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/watcher/watchertest/notify.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package watchertest
     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/testing"
    13  	"github.com/juju/juju/watcher"
    14  )
    15  
    16  func NewNotifyWatcherC(c *gc.C, watcher watcher.NotifyWatcher, preAssert func()) NotifyWatcherC {
    17  	if preAssert == nil {
    18  		preAssert = func() {}
    19  	}
    20  	return NotifyWatcherC{
    21  		C:         c,
    22  		Watcher:   watcher,
    23  		PreAssert: preAssert,
    24  	}
    25  }
    26  
    27  type NotifyWatcherC struct {
    28  	*gc.C
    29  	Watcher   watcher.NotifyWatcher
    30  	PreAssert func()
    31  }
    32  
    33  // AssertOneChange fails if no change is sent before a long time has passed; or
    34  // if, subsequent to that, any further change is sent before a short time has
    35  // passed.
    36  func (c NotifyWatcherC) AssertOneChange() {
    37  	c.PreAssert()
    38  	select {
    39  	case _, ok := <-c.Watcher.Changes():
    40  		c.Assert(ok, jc.IsTrue)
    41  	case <-time.After(testing.LongWait):
    42  		c.Fatalf("watcher did not send change")
    43  	}
    44  	c.AssertNoChange()
    45  }
    46  
    47  // AssertNoChange fails if it manages to read a value from Changes before a
    48  // short time has passed.
    49  func (c NotifyWatcherC) AssertNoChange() {
    50  	c.PreAssert()
    51  	select {
    52  	case _, ok := <-c.Watcher.Changes():
    53  		c.Fatalf("watcher sent unexpected change: (_, %v)", ok)
    54  	case <-time.After(testing.ShortWait):
    55  	}
    56  }
    57  
    58  // AssertStops Kills the watcher and asserts (1) that Wait completes without
    59  // error before a long time has passed; and (2) that Changes remains open but
    60  // no values are being sent.
    61  func (c NotifyWatcherC) AssertStops() {
    62  	c.Watcher.Kill()
    63  	wait := make(chan error)
    64  	go func() {
    65  		c.PreAssert()
    66  		wait <- c.Watcher.Wait()
    67  	}()
    68  	select {
    69  	case <-time.After(testing.LongWait):
    70  		c.Fatalf("watcher never stopped")
    71  	case err := <-wait:
    72  		c.Assert(err, jc.ErrorIsNil)
    73  	}
    74  
    75  	c.PreAssert()
    76  	select {
    77  	case _, ok := <-c.Watcher.Changes():
    78  		c.Fatalf("watcher sent unexpected change: (_, %v)", ok)
    79  	default:
    80  	}
    81  }