瀏覽代碼

internal/cmdtest: Expose process exit status and errors (#18046)

Javier Peletier 7 年之前
父節點
當前提交
7bf7bd2f50
共有 1 個文件被更改,包括 19 次插入2 次删除
  1. 19 2
      internal/cmdtest/test_cmd.go

+ 19 - 2
internal/cmdtest/test_cmd.go

@@ -27,6 +27,7 @@ import (
 	"regexp"
 	"regexp"
 	"strings"
 	"strings"
 	"sync"
 	"sync"
+	"syscall"
 	"testing"
 	"testing"
 	"text/template"
 	"text/template"
 	"time"
 	"time"
@@ -50,6 +51,8 @@ type TestCmd struct {
 	stdout *bufio.Reader
 	stdout *bufio.Reader
 	stdin  io.WriteCloser
 	stdin  io.WriteCloser
 	stderr *testlogger
 	stderr *testlogger
+	// Err will contain the process exit error or interrupt signal error
+	Err error
 }
 }
 
 
 // Run exec's the current binary using name as argv[0] which will trigger the
 // Run exec's the current binary using name as argv[0] which will trigger the
@@ -182,11 +185,25 @@ func (tt *TestCmd) ExpectExit() {
 }
 }
 
 
 func (tt *TestCmd) WaitExit() {
 func (tt *TestCmd) WaitExit() {
-	tt.cmd.Wait()
+	tt.Err = tt.cmd.Wait()
 }
 }
 
 
 func (tt *TestCmd) Interrupt() {
 func (tt *TestCmd) Interrupt() {
-	tt.cmd.Process.Signal(os.Interrupt)
+	tt.Err = tt.cmd.Process.Signal(os.Interrupt)
+}
+
+// ExitStatus exposes the process' OS exit code
+// It will only return a valid value after the process has finished.
+func (tt *TestCmd) ExitStatus() int {
+	if tt.Err != nil {
+		exitErr := tt.Err.(*exec.ExitError)
+		if exitErr != nil {
+			if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
+				return status.ExitStatus()
+			}
+		}
+	}
+	return 0
 }
 }
 
 
 // StderrText returns any stderr output written so far.
 // StderrText returns any stderr output written so far.