github.imxd.top/hashicorp/consul@v1.4.5/command/snapshot/restore/snapshot_restore_test.go (about)

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