github.com/rothwerx/packer@v0.9.0/packer/hook_test.go (about)

     1  package packer
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  // A helper Hook implementation for testing cancels.
    10  type CancelHook struct {
    11  	sync.Mutex
    12  	cancelCh chan struct{}
    13  	doneCh   chan struct{}
    14  
    15  	Cancelled bool
    16  }
    17  
    18  func (h *CancelHook) Run(string, Ui, Communicator, interface{}) error {
    19  	h.Lock()
    20  	h.cancelCh = make(chan struct{})
    21  	h.doneCh = make(chan struct{})
    22  	h.Unlock()
    23  
    24  	defer close(h.doneCh)
    25  
    26  	select {
    27  	case <-h.cancelCh:
    28  		h.Cancelled = true
    29  	case <-time.After(1 * time.Second):
    30  	}
    31  
    32  	return nil
    33  }
    34  
    35  func (h *CancelHook) Cancel() {
    36  	h.Lock()
    37  	close(h.cancelCh)
    38  	h.Unlock()
    39  
    40  	<-h.doneCh
    41  }
    42  
    43  func TestDispatchHook_Implements(t *testing.T) {
    44  	var _ Hook = new(DispatchHook)
    45  }
    46  
    47  func TestDispatchHook_Run_NoHooks(t *testing.T) {
    48  	// Just make sure nothing blows up
    49  	dh := &DispatchHook{}
    50  	dh.Run("foo", nil, nil, nil)
    51  }
    52  
    53  func TestDispatchHook_Run(t *testing.T) {
    54  	hook := &MockHook{}
    55  
    56  	mapping := make(map[string][]Hook)
    57  	mapping["foo"] = []Hook{hook}
    58  	dh := &DispatchHook{Mapping: mapping}
    59  	dh.Run("foo", nil, nil, 42)
    60  
    61  	if !hook.RunCalled {
    62  		t.Fatal("should be called")
    63  	}
    64  	if hook.RunName != "foo" {
    65  		t.Fatalf("bad: %s", hook.RunName)
    66  	}
    67  	if hook.RunData != 42 {
    68  		t.Fatalf("bad: %#v", hook.RunData)
    69  	}
    70  }
    71  
    72  func TestDispatchHook_cancel(t *testing.T) {
    73  	hook := new(CancelHook)
    74  
    75  	dh := &DispatchHook{
    76  		Mapping: map[string][]Hook{
    77  			"foo": []Hook{hook},
    78  		},
    79  	}
    80  
    81  	go dh.Run("foo", nil, nil, 42)
    82  	time.Sleep(100 * time.Millisecond)
    83  	dh.Cancel()
    84  
    85  	if !hook.Cancelled {
    86  		t.Fatal("hook should've cancelled")
    87  	}
    88  }