code.vegaprotocol.io/vega@v0.79.0/cmd/data-node/commands/root_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"
    24  	"strings"
    25  	"testing"
    26  
    27  	"github.com/stretchr/testify/require"
    28  )
    29  
    30  type CommandSuite struct{}
    31  
    32  // RunMain simulates a CLI execution. It formats a cmd invocation given a format and its args and overwrites os.Args.
    33  // The output of the command is captured and returned.
    34  func (suite *CommandSuite) RunMain(ctx context.Context, format string, args ...interface{}) ([]byte, error) {
    35  	old := os.Stdout
    36  	r, w, _ := os.Pipe()
    37  	os.Stdout = w
    38  
    39  	cmd := fmt.Sprintf(format, args...)
    40  	fmt.Fprintf(old, "-> %s\n", cmd)
    41  	os.Args = append([]string{"vega"}, strings.Fields(cmd)...)
    42  	err := Execute(ctx)
    43  
    44  	w.Close()
    45  	out, _ := ioutil.ReadAll(r)
    46  	fmt.Fprintf(old, "<- %s\n", out)
    47  	os.Stdout = old
    48  
    49  	return out, err
    50  }
    51  
    52  // PrepareSandbox creates a sandbox directory where to run a command.
    53  // It returns the path of the new created directory and a closer function.
    54  func (suite *CommandSuite) PrepareSandbox(t *testing.T) (string, func()) {
    55  	t.Helper()
    56  	dir, err := ioutil.TempDir(".", "test-sandbox-*")
    57  	require.NoError(t, err)
    58  
    59  	pass := path.Join(dir, "passphrase")
    60  	f, err := os.Create(pass)
    61  	require.NoError(t, err)
    62  
    63  	_, err = f.WriteString("the password")
    64  	require.NoError(t, err)
    65  	f.Close()
    66  
    67  	return dir, func() {
    68  		os.RemoveAll(dir)
    69  	}
    70  }