github.com/verrazzano/verrazzano@v1.7.1/pkg/os/exec_test.go (about)

     1  // Copyright (c) 2020, 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package os
     5  
     6  import (
     7  	"errors"
     8  	"github.com/stretchr/testify/assert"
     9  	"os/exec"
    10  	"testing"
    11  )
    12  
    13  // TestRun tests the exec Run command
    14  // GIVEN a command
    15  //
    16  //	WHEN I call Run
    17  //	THEN the value returned will have the correct stdout and stderr
    18  func TestRun(t *testing.T) {
    19  	assert := assert.New(t)
    20  
    21  	// override cmd.Run function
    22  	cmdRunFunc = goodCmdRunner
    23  	cmd := exec.Command("helm", "arg1", "arg2", "arg3")
    24  	stdout, stderr, err := DefaultRunner{}.Run(cmd)
    25  	assert.NoError(err, "Error should not be returned from exec")
    26  	assert.Len(stderr, 0, "stderr is incorrect")
    27  	assert.Equal("success", string(stdout), "stdout is incorrect")
    28  	assert.NoError(err, "Error should not be returned from exec")
    29  	assert.Contains(cmd.Path, "helm", "exec command should contain helm")
    30  	assert.Contains(cmd.Args[0], "helm", "exec args should contain helm")
    31  	assert.Equal(cmd.Args[1], "arg1", "exec arg should equal arg1")
    32  	assert.Equal(cmd.Args[2], "arg2", "exec arg should equal arg2")
    33  	assert.Contains(cmd.Args[3], "arg3", "exec arg should equal arg3 ")
    34  }
    35  
    36  // TestRunError tests the exec Run error condition
    37  // GIVEN a command and a fake runner that returns an error
    38  //
    39  //	WHEN I call Run
    40  //	THEN the value returned will have and error status and the correct stdout and stderr
    41  func TestRunError(t *testing.T) {
    42  	assert := assert.New(t)
    43  
    44  	// override cmd.Run function
    45  	cmdRunFunc = badCmdRunner
    46  	cmd := exec.Command("helm", "arg1", "arg2", "arg3")
    47  	stdout, stderr, err := DefaultRunner{}.Run(cmd)
    48  	assert.Error(err, "Error should be returned from exec")
    49  	assert.Len(stdout, 0, "stdout is incorrect")
    50  	assert.Equal("err", string(stderr), "stderr is incorrect")
    51  }
    52  
    53  func goodCmdRunner(cmd *exec.Cmd) error {
    54  	cmd.Stdout.Write([]byte("success"))
    55  	cmd.Stderr.Write([]byte(""))
    56  	return nil
    57  }
    58  
    59  func badCmdRunner(cmd *exec.Cmd) error {
    60  	cmd.Stdout.Write([]byte(""))
    61  	cmd.Stderr.Write([]byte("err"))
    62  	return errors.New("error")
    63  }