github.com/gofiber/fiber-cli@v0.0.3/cmd/tester_test.go (about)

     1  package cmd
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"os"
     9  	"os/exec"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/assert"
    13  
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  var (
    18  	needError bool
    19  	errFlag   = struct{}{}
    20  )
    21  
    22  func fakeExecCommand(command string, args ...string) *exec.Cmd {
    23  	cs := []string{"-test.run=TestHelperProcess", "--", command}
    24  	cs = append(cs, args...)
    25  	cmd := exec.Command(os.Args[0], cs...)
    26  	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
    27  	if needError {
    28  		cmd.Env = append(cmd.Env, "GO_WANT_HELPER_NEED_ERR=1")
    29  	}
    30  	return cmd
    31  }
    32  
    33  func TestHelperProcess(t *testing.T) {
    34  	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
    35  		return
    36  	}
    37  	args := os.Args
    38  	for len(args) > 0 {
    39  		if args[0] == "--" {
    40  			args = args[1:]
    41  			break
    42  		}
    43  		args = args[1:]
    44  	}
    45  
    46  	if len(args) == 0 {
    47  		_, _ = fmt.Fprintf(os.Stderr, "No command")
    48  		os.Exit(2)
    49  	}
    50  
    51  	if os.Getenv("GO_WANT_HELPER_NEED_ERR") == "1" {
    52  		_, _ = fmt.Fprintf(os.Stderr, "fake error")
    53  		os.Exit(1)
    54  	}
    55  
    56  	os.Exit(0)
    57  }
    58  
    59  func setupCmd(flag ...struct{}) {
    60  	execCommand = fakeExecCommand
    61  	if len(flag) > 0 {
    62  		needError = true
    63  	}
    64  }
    65  
    66  func teardownCmd() {
    67  	execCommand = exec.Command
    68  	needError = false
    69  }
    70  
    71  func setupLookPath(flag ...struct{}) {
    72  	execLookPath = func(file string) (s string, err error) {
    73  		if len(flag) > 0 {
    74  			err = errors.New("fake look path error")
    75  		}
    76  		return
    77  	}
    78  }
    79  
    80  func teardownLookPath() {
    81  	execLookPath = exec.LookPath
    82  }
    83  
    84  func setupOsExit(override ...func(int)) {
    85  	fn := func(_ int) {}
    86  	if len(override) > 0 {
    87  		fn = override[0]
    88  	}
    89  	osExit = fn
    90  }
    91  
    92  func teardownOsExit() {
    93  	osExit = os.Exit
    94  }
    95  
    96  func runCobraCmd(cmd *cobra.Command, args ...string) (string, error) {
    97  	b := new(bytes.Buffer)
    98  
    99  	cmd.ResetCommands()
   100  	cmd.SetErr(b)
   101  	cmd.SetOut(b)
   102  	cmd.SetArgs(args)
   103  	err := cmd.Execute()
   104  
   105  	return b.String(), err
   106  }
   107  
   108  func setupHomeDir(t *testing.T, pattern string) string {
   109  	homeDir, err := ioutil.TempDir("", "test_"+pattern)
   110  	assert.Nil(t, err)
   111  	return homeDir
   112  }
   113  
   114  func teardownHomeDir(dir string) {
   115  	_ = os.RemoveAll(dir)
   116  }