packer-cn/packer/communicator_test.go

89 lines
1.6 KiB
Go
Raw Normal View History

2013-05-28 21:02:14 -04:00
package packer
2013-06-03 13:49:23 -04:00
import (
"bytes"
"context"
2019-04-08 05:22:01 -04:00
"io"
"strings"
2013-06-03 13:49:23 -04:00
"testing"
"time"
"github.com/google/go-cmp/cmp"
2019-04-08 05:22:01 -04:00
"github.com/mitchellh/iochan"
"golang.org/x/sync/errgroup"
2013-06-03 13:49:23 -04:00
)
func TestRemoteCmd_StartWithUi(t *testing.T) {
2019-04-08 05:22:01 -04:00
data := []string{
"hello",
"world",
"foo",
"there",
}
2019-04-08 05:22:01 -04:00
originalOutputReader, originalOutputWriter := io.Pipe()
uilOutputReader, uilOutputWriter := io.Pipe()
testComm := new(MockCommunicator)
2019-04-08 05:22:01 -04:00
testComm.StartStdout = strings.Join(data, "\n") + "\n"
testUi := &BasicUi{
Reader: new(bytes.Buffer),
2019-04-08 05:22:01 -04:00
Writer: uilOutputWriter,
}
rc := &RemoteCmd{
Command: "test",
2019-04-08 05:22:01 -04:00
Stdout: originalOutputWriter,
}
ctx := context.TODO()
2019-04-08 05:22:01 -04:00
wg := errgroup.Group{}
testPrintFn := func(in io.Reader, expected []string) error {
i := 0
got := []string{}
for output := range iochan.LineReader(in) {
got = append(got, output)
i++
if i == len(expected) {
// here ideally the LineReader chan should be closed, but since
// the stream virtually has no ending we need to leave early.
break
}
}
if diff := cmp.Diff(got, expected); diff != "" {
t.Fatalf("bad output: %s", diff)
}
return nil
}
2019-04-08 05:22:01 -04:00
wg.Go(func() error { return testPrintFn(uilOutputReader, data) })
wg.Go(func() error { return testPrintFn(originalOutputReader, data) })
2019-04-08 05:22:01 -04:00
err := rc.RunWithUi(ctx, testComm, testUi)
if err != nil {
t.Fatalf("err: %s", err)
}
2019-04-08 05:22:01 -04:00
wg.Wait()
}
2013-06-03 13:49:23 -04:00
func TestRemoteCmd_Wait(t *testing.T) {
var cmd RemoteCmd
result := make(chan bool)
go func() {
cmd.Wait()
result <- true
}()
cmd.SetExited(42)
2013-06-03 13:49:23 -04:00
select {
case <-result:
// Success
case <-time.After(500 * time.Millisecond):
t.Fatal("never got exit notification")
}
}