github.com/haraldrudell/parl@v0.4.176/pexec/exit-error-data_test.go (about)

     1  /*
     2  © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pexec
     7  
     8  import (
     9  	"os/exec"
    10  	"strings"
    11  	"testing"
    12  
    13  	"github.com/haraldrudell/parl/pbytes"
    14  )
    15  
    16  func TestExitErrorString(t *testing.T) {
    17  	var name = "date"
    18  	var args = []string{"%"}
    19  	var expStderr = "date:"
    20  
    21  	var stdout, exitErrorStderr []byte
    22  	var err error
    23  	var errS, stderrS string
    24  
    25  	// command: “date %” produces an error
    26  	stdout, err = exec.Command(name, args...).Output()
    27  	if err == nil {
    28  		t.Fatal("exec.Command: missing error")
    29  	}
    30  
    31  	// verify error type to be exec.ExitError
    32  	//	- those errors have status code and stderr
    33  	// err type: *exec.ExitError
    34  	t.Logf("err type: %T", err)
    35  
    36  	// command should echo to stderr
    37  	if e := err.(*exec.ExitError); e != nil {
    38  		exitErrorStderr = e.Stderr
    39  		t.Logf("err.Stderr length: %d", len(string(exitErrorStderr)))
    40  		if len(exitErrorStderr) == 0 {
    41  			t.Error("stderrr empty")
    42  		}
    43  	}
    44  
    45  	// command should not echo to stdout
    46  	if len(stdout) > 0 {
    47  		t.Errorf("stdout output: %q", string(stdout))
    48  	}
    49  
    50  	// status code should be non-zero and no signal
    51  	hasStatusCode, statusCode, signal, stderr := ExitError(err)
    52  	if !hasStatusCode {
    53  		t.Fatal("err not ExitError")
    54  	}
    55  	if signal != 0 {
    56  		t.Errorf("signal: %s", signal)
    57  	}
    58  	if statusCode == 0 {
    59  		t.Error("status code: 0")
    60  	}
    61  
    62  	// returned stderr should contain expStderr
    63  	t.Logf("stderr: %d bytes", len(stderr))
    64  	stderrS = string(stderr)
    65  	if !strings.HasPrefix(stderrS, expStderr) {
    66  		t.Fatalf("stderr no prefix: %q: %q", expStderr, stderrS)
    67  	}
    68  
    69  	errS = NewExitErrorData(err).ExitErrorString(ExitErrorIncludeStderr)
    70  	expErrS := string(pbytes.TrimNewline(exitErrorStderr))
    71  	if !strings.Contains(errS, expErrS) {
    72  		t.Errorf("ExitErrorString no contain %q: %q", stderrS, expErrS)
    73  	}
    74  }