2013-05-11 12:51:49 -04:00
|
|
|
package rpc
|
|
|
|
|
|
|
|
import (
|
2013-08-31 02:10:16 -04:00
|
|
|
"reflect"
|
|
|
|
"sync"
|
2013-05-11 12:51:49 -04:00
|
|
|
"testing"
|
2013-08-31 02:10:16 -04:00
|
|
|
"time"
|
2018-01-22 20:21:10 -05:00
|
|
|
|
|
|
|
"github.com/hashicorp/packer/packer"
|
2013-05-11 12:51:49 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestHookRPC(t *testing.T) {
|
|
|
|
// Create the UI to test
|
2013-08-30 20:03:55 -04:00
|
|
|
h := new(packer.MockHook)
|
2013-05-11 12:51:49 -04:00
|
|
|
|
|
|
|
// Serve
|
2013-12-10 14:50:30 -05:00
|
|
|
client, server := testClientServer(t)
|
|
|
|
defer client.Close()
|
|
|
|
defer server.Close()
|
|
|
|
server.RegisterHook(h)
|
|
|
|
hClient := client.Hook()
|
2013-05-11 12:51:49 -04:00
|
|
|
|
|
|
|
// Test Run
|
|
|
|
ui := &testUi{}
|
2013-05-12 20:30:30 -04:00
|
|
|
hClient.Run("foo", ui, nil, 42)
|
2013-10-16 23:04:57 -04:00
|
|
|
if !h.RunCalled {
|
|
|
|
t.Fatal("should be called")
|
|
|
|
}
|
2013-08-31 02:03:43 -04:00
|
|
|
|
|
|
|
// Test Cancel
|
|
|
|
hClient.Cancel()
|
2013-10-16 23:04:57 -04:00
|
|
|
if !h.CancelCalled {
|
|
|
|
t.Fatal("should be called")
|
|
|
|
}
|
2013-05-11 12:51:49 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestHook_Implements(t *testing.T) {
|
2013-10-16 23:04:57 -04:00
|
|
|
var _ packer.Hook = new(hook)
|
2013-05-11 12:51:49 -04:00
|
|
|
}
|
2013-08-31 02:10:16 -04:00
|
|
|
|
|
|
|
func TestHook_cancelWhileRun(t *testing.T) {
|
|
|
|
var finishLock sync.Mutex
|
|
|
|
finishOrder := make([]string, 0, 2)
|
|
|
|
|
|
|
|
h := &packer.MockHook{
|
|
|
|
RunFunc: func() error {
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
|
|
|
|
finishLock.Lock()
|
|
|
|
finishOrder = append(finishOrder, "run")
|
|
|
|
finishLock.Unlock()
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
// Serve
|
2013-12-10 14:50:30 -05:00
|
|
|
client, server := testClientServer(t)
|
|
|
|
defer client.Close()
|
|
|
|
defer server.Close()
|
|
|
|
server.RegisterHook(h)
|
|
|
|
hClient := client.Hook()
|
2013-08-31 02:10:16 -04:00
|
|
|
|
|
|
|
// Start the run
|
|
|
|
finished := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
hClient.Run("foo", nil, nil, nil)
|
|
|
|
close(finished)
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Cancel it pretty quickly.
|
|
|
|
time.Sleep(10 * time.Millisecond)
|
|
|
|
hClient.Cancel()
|
|
|
|
|
|
|
|
finishLock.Lock()
|
|
|
|
finishOrder = append(finishOrder, "cancel")
|
|
|
|
finishLock.Unlock()
|
|
|
|
|
|
|
|
// Verify things are good
|
|
|
|
<-finished
|
|
|
|
|
|
|
|
// Check the results
|
|
|
|
expected := []string{"cancel", "run"}
|
|
|
|
if !reflect.DeepEqual(finishOrder, expected) {
|
|
|
|
t.Fatalf("bad: %#v", finishOrder)
|
|
|
|
}
|
|
|
|
}
|