github.com/askholme/packer@v0.7.2-0.20140924152349-70d9566a6852/packer/rpc/hook_test.go (about)

     1  package rpc
     2  
     3  import (
     4  	"github.com/mitchellh/packer/packer"
     5  	"reflect"
     6  	"sync"
     7  	"testing"
     8  	"time"
     9  )
    10  
    11  func TestHookRPC(t *testing.T) {
    12  	// Create the UI to test
    13  	h := new(packer.MockHook)
    14  
    15  	// Serve
    16  	client, server := testClientServer(t)
    17  	defer client.Close()
    18  	defer server.Close()
    19  	server.RegisterHook(h)
    20  	hClient := client.Hook()
    21  
    22  	// Test Run
    23  	ui := &testUi{}
    24  	hClient.Run("foo", ui, nil, 42)
    25  	if !h.RunCalled {
    26  		t.Fatal("should be called")
    27  	}
    28  
    29  	// Test Cancel
    30  	hClient.Cancel()
    31  	if !h.CancelCalled {
    32  		t.Fatal("should be called")
    33  	}
    34  }
    35  
    36  func TestHook_Implements(t *testing.T) {
    37  	var _ packer.Hook = new(hook)
    38  }
    39  
    40  func TestHook_cancelWhileRun(t *testing.T) {
    41  	var finishLock sync.Mutex
    42  	finishOrder := make([]string, 0, 2)
    43  
    44  	h := &packer.MockHook{
    45  		RunFunc: func() error {
    46  			time.Sleep(100 * time.Millisecond)
    47  
    48  			finishLock.Lock()
    49  			finishOrder = append(finishOrder, "run")
    50  			finishLock.Unlock()
    51  			return nil
    52  		},
    53  	}
    54  
    55  	// Serve
    56  	client, server := testClientServer(t)
    57  	defer client.Close()
    58  	defer server.Close()
    59  	server.RegisterHook(h)
    60  	hClient := client.Hook()
    61  
    62  	// Start the run
    63  	finished := make(chan struct{})
    64  	go func() {
    65  		hClient.Run("foo", nil, nil, nil)
    66  		close(finished)
    67  	}()
    68  
    69  	// Cancel it pretty quickly.
    70  	time.Sleep(10 * time.Millisecond)
    71  	hClient.Cancel()
    72  
    73  	finishLock.Lock()
    74  	finishOrder = append(finishOrder, "cancel")
    75  	finishLock.Unlock()
    76  
    77  	// Verify things are good
    78  	<-finished
    79  
    80  	// Check the results
    81  	expected := []string{"cancel", "run"}
    82  	if !reflect.DeepEqual(finishOrder, expected) {
    83  		t.Fatalf("bad: %#v", finishOrder)
    84  	}
    85  }