github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/core/cache/notifywatcher_test.go (about)

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