code.vegaprotocol.io/vega@v0.79.0/cmd/vega/commands/main_test.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package commands 17 18 import ( 19 "context" 20 "fmt" 21 "io/ioutil" 22 "os" 23 "path/filepath" 24 "strings" 25 "testing" 26 27 vgrand "code.vegaprotocol.io/vega/libs/rand" 28 29 "github.com/stretchr/testify/require" 30 ) 31 32 var ( 33 err error 34 out []byte 35 ) 36 37 type CommandSuite struct{} 38 39 // RunMain simulates a CLI execution. It formats a cmd invocation given a format and its args and overwrites os.Args. 40 // The output of the command is captured and returned. 41 func (suite *CommandSuite) RunMain(ctx context.Context, format string, args ...interface{}) ([]byte, error) { 42 stdout := os.Stdout 43 stderr := os.Stderr 44 r, w, _ := os.Pipe() 45 os.Stdout = w 46 os.Stderr = w 47 48 cmd := fmt.Sprintf(format, args...) 49 fmt.Fprintf(stdout, "-> %s\n", cmd) 50 os.Args = append([]string{"vega"}, strings.Fields(cmd)...) 51 err := Main(ctx) 52 53 w.Close() 54 out, _ := ioutil.ReadAll(r) 55 fmt.Fprintf(stdout, "<- %s\n", out) 56 os.Stdout = stdout 57 os.Stderr = stderr 58 59 return out, err 60 } 61 62 // PrepareSandbox creates a sandbox directory where to run a command. 63 // It returns the path of the new created directory and a closer function. 64 func (suite *CommandSuite) PrepareSandbox(t *testing.T) (string, string, func()) { 65 t.Helper() 66 path := filepath.Join("/tmp", "vega-tests", "test-sandbox", vgrand.RandomStr(10)) 67 err := os.MkdirAll(path, os.ModePerm) 68 if err != nil { 69 panic(err) 70 } 71 72 pass := filepath.Join(path, "passphrase") 73 f, err := os.Create(pass) 74 require.NoError(t, err) 75 76 _, err = f.WriteString("the password") 77 require.NoError(t, err) 78 f.Close() 79 80 return path, pass, func() { 81 os.RemoveAll(path) 82 } 83 } 84 85 func TestSuite(t *testing.T) { 86 s := &CommandSuite{} 87 88 t.Run("Faucet", s.TestFaucet) 89 }