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