github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/worker/uniter/hook/hooktesting/source.go (about)

     1  // Copyright 2014 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package hooktesting
     5  
     6  import (
     7  	"gopkg.in/juju/charm.v6-unstable/hooks"
     8  	"gopkg.in/tomb.v1"
     9  
    10  	"github.com/juju/juju/worker/uniter/hook"
    11  )
    12  
    13  func HookList(kinds ...hooks.Kind) []hook.Info {
    14  	result := make([]hook.Info, len(kinds))
    15  	for i, kind := range kinds {
    16  		result[i].Kind = kind
    17  	}
    18  	return result
    19  }
    20  
    21  type UpdateSource struct {
    22  	Tomb     tomb.Tomb
    23  	empty    bool
    24  	ChangesC chan hook.SourceChange
    25  	UpdatesC chan interface{}
    26  }
    27  
    28  func NewEmptySource() *UpdateSource {
    29  	return newUpdateSource(true, false)
    30  }
    31  
    32  func NewFullBufferedSource() *UpdateSource {
    33  	return newUpdateSource(false, true)
    34  }
    35  
    36  func NewFullUnbufferedSource() *UpdateSource {
    37  	return newUpdateSource(false, false)
    38  }
    39  
    40  func newUpdateSource(empty, buffered bool) *UpdateSource {
    41  	var bufferSize int
    42  	if buffered {
    43  		bufferSize = 1000
    44  	}
    45  	source := &UpdateSource{
    46  		empty:    empty,
    47  		ChangesC: make(chan hook.SourceChange),
    48  		UpdatesC: make(chan interface{}, bufferSize),
    49  	}
    50  	go func() {
    51  		defer source.Tomb.Done()
    52  		defer close(source.ChangesC)
    53  		<-source.Tomb.Dying()
    54  	}()
    55  	return source
    56  }
    57  
    58  func (source *UpdateSource) Stop() error {
    59  	source.Tomb.Kill(nil)
    60  	return source.Tomb.Wait()
    61  }
    62  
    63  func (source *UpdateSource) Changes() <-chan hook.SourceChange {
    64  	return source.ChangesC
    65  }
    66  
    67  func (source *UpdateSource) NewChange(v interface{}) hook.SourceChange {
    68  	return func() error {
    69  		select {
    70  		case <-source.Tomb.Dying():
    71  			return tomb.ErrDying
    72  		case source.UpdatesC <- v:
    73  		}
    74  		return nil
    75  	}
    76  }
    77  
    78  func (source *UpdateSource) Empty() bool {
    79  	return source.empty
    80  }
    81  
    82  func (source *UpdateSource) Next() hook.Info {
    83  	if source.empty {
    84  		panic(nil)
    85  	}
    86  	return hook.Info{Kind: hooks.Install}
    87  }
    88  
    89  func (source *UpdateSource) Pop() {
    90  	if source.empty {
    91  		panic(nil)
    92  	}
    93  }