github.com/jerryclinesmith/packer@v0.3.7/packer/rpc/hook_test.go (about)

     1  package rpc
     2  
     3  import (
     4  	"cgl.tideland.biz/asserts"
     5  	"github.com/mitchellh/packer/packer"
     6  	"net/rpc"
     7  	"reflect"
     8  	"sync"
     9  	"testing"
    10  	"time"
    11  )
    12  
    13  func TestHookRPC(t *testing.T) {
    14  	assert := asserts.NewTestingAsserts(t, true)
    15  
    16  	// Create the UI to test
    17  	h := new(packer.MockHook)
    18  
    19  	// Serve
    20  	server := rpc.NewServer()
    21  	RegisterHook(server, h)
    22  	address := serveSingleConn(server)
    23  
    24  	// Create the client over RPC and run some methods to verify it works
    25  	client, err := rpc.Dial("tcp", address)
    26  	assert.Nil(err, "should be able to connect")
    27  
    28  	hClient := Hook(client)
    29  
    30  	// Test Run
    31  	ui := &testUi{}
    32  	hClient.Run("foo", ui, nil, 42)
    33  	assert.True(h.RunCalled, "run should be called")
    34  
    35  	// Test Cancel
    36  	hClient.Cancel()
    37  	assert.True(h.CancelCalled, "cancel should be called")
    38  }
    39  
    40  func TestHook_Implements(t *testing.T) {
    41  	assert := asserts.NewTestingAsserts(t, true)
    42  
    43  	var r packer.Hook
    44  	h := &hook{nil}
    45  
    46  	assert.Implementor(h, &r, "should be a Hook")
    47  }
    48  
    49  func TestHook_cancelWhileRun(t *testing.T) {
    50  	var finishLock sync.Mutex
    51  	finishOrder := make([]string, 0, 2)
    52  
    53  	h := &packer.MockHook{
    54  		RunFunc: func() error {
    55  			time.Sleep(100 * time.Millisecond)
    56  
    57  			finishLock.Lock()
    58  			finishOrder = append(finishOrder, "run")
    59  			finishLock.Unlock()
    60  			return nil
    61  		},
    62  	}
    63  
    64  	// Serve
    65  	server := rpc.NewServer()
    66  	RegisterHook(server, h)
    67  	address := serveSingleConn(server)
    68  
    69  	// Create the client over RPC and run some methods to verify it works
    70  	client, err := rpc.Dial("tcp", address)
    71  	if err != nil {
    72  		t.Fatalf("err: %s", err)
    73  	}
    74  
    75  	hClient := Hook(client)
    76  
    77  	// Start the run
    78  	finished := make(chan struct{})
    79  	go func() {
    80  		hClient.Run("foo", nil, nil, nil)
    81  		close(finished)
    82  	}()
    83  
    84  	// Cancel it pretty quickly.
    85  	time.Sleep(10 * time.Millisecond)
    86  	hClient.Cancel()
    87  
    88  	finishLock.Lock()
    89  	finishOrder = append(finishOrder, "cancel")
    90  	finishLock.Unlock()
    91  
    92  	// Verify things are good
    93  	<-finished
    94  
    95  	// Check the results
    96  	expected := []string{"cancel", "run"}
    97  	if !reflect.DeepEqual(finishOrder, expected) {
    98  		t.Fatalf("bad: %#v", finishOrder)
    99  	}
   100  }