github.com/KyaXTeam/consul@v1.4.5/command/snapshot/save/snapshot_save_test.go (about)

     1  package save
     2  
     3  import (
     4  	"os"
     5  	"path"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/hashicorp/consul/agent"
    10  	"github.com/hashicorp/consul/testutil"
    11  	"github.com/mitchellh/cli"
    12  )
    13  
    14  func TestSnapshotSaveCommand_noTabs(t *testing.T) {
    15  	t.Parallel()
    16  	if strings.ContainsRune(New(cli.NewMockUi()).Help(), '\t') {
    17  		t.Fatal("help has tabs")
    18  	}
    19  }
    20  func TestSnapshotSaveCommand_Validation(t *testing.T) {
    21  	t.Parallel()
    22  
    23  	cases := map[string]struct {
    24  		args   []string
    25  		output string
    26  	}{
    27  		"no file": {
    28  			[]string{},
    29  			"Missing FILE argument",
    30  		},
    31  		"extra args": {
    32  			[]string{"foo", "bar", "baz"},
    33  			"Too many arguments",
    34  		},
    35  	}
    36  
    37  	for name, tc := range cases {
    38  		ui := cli.NewMockUi()
    39  		c := New(ui)
    40  
    41  		// Ensure our buffer is always clear
    42  		if ui.ErrorWriter != nil {
    43  			ui.ErrorWriter.Reset()
    44  		}
    45  		if ui.OutputWriter != nil {
    46  			ui.OutputWriter.Reset()
    47  		}
    48  
    49  		code := c.Run(tc.args)
    50  		if code == 0 {
    51  			t.Errorf("%s: expected non-zero exit", name)
    52  		}
    53  
    54  		output := ui.ErrorWriter.String()
    55  		if !strings.Contains(output, tc.output) {
    56  			t.Errorf("%s: expected %q to contain %q", name, output, tc.output)
    57  		}
    58  	}
    59  }
    60  
    61  func TestSnapshotSaveCommand(t *testing.T) {
    62  	t.Parallel()
    63  	a := agent.NewTestAgent(t, t.Name(), ``)
    64  	defer a.Shutdown()
    65  	client := a.Client()
    66  
    67  	ui := cli.NewMockUi()
    68  	c := New(ui)
    69  
    70  	dir := testutil.TempDir(t, "snapshot")
    71  	defer os.RemoveAll(dir)
    72  
    73  	file := path.Join(dir, "backup.tgz")
    74  	args := []string{
    75  		"-http-addr=" + a.HTTPAddr(),
    76  		file,
    77  	}
    78  
    79  	code := c.Run(args)
    80  	if code != 0 {
    81  		t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String())
    82  	}
    83  
    84  	f, err := os.Open(file)
    85  	if err != nil {
    86  		t.Fatalf("err: %v", err)
    87  	}
    88  	defer f.Close()
    89  
    90  	if err := client.Snapshot().Restore(nil, f); err != nil {
    91  		t.Fatalf("err: %v", err)
    92  	}
    93  }