github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/command/operator_snapshot_inspect_test.go (about) 1 package command 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path/filepath" 7 "testing" 8 9 "github.com/hashicorp/nomad/api" 10 "github.com/hashicorp/nomad/command/agent" 11 "github.com/mitchellh/cli" 12 "github.com/stretchr/testify/require" 13 ) 14 15 func TestOperatorSnapshotInspect_Works(t *testing.T) { 16 t.Parallel() 17 18 snapPath := generateSnapshotFile(t, nil) 19 20 ui := cli.NewMockUi() 21 cmd := &OperatorSnapshotInspectCommand{Meta: Meta{Ui: ui}} 22 23 code := cmd.Run([]string{snapPath}) 24 require.Zero(t, code) 25 26 output := ui.OutputWriter.String() 27 for _, key := range []string{ 28 "ID", 29 "Size", 30 "Index", 31 "Term", 32 "Version", 33 } { 34 require.Contains(t, output, key) 35 } 36 37 } 38 func TestOperatorSnapshotInspect_HandlesFailure(t *testing.T) { 39 t.Parallel() 40 41 tmpDir, err := ioutil.TempDir("", "nomad-clitests-") 42 require.NoError(t, err) 43 defer os.RemoveAll(tmpDir) 44 45 err = ioutil.WriteFile( 46 filepath.Join(tmpDir, "invalid.snap"), 47 []byte("invalid data"), 48 0600) 49 require.NoError(t, err) 50 51 t.Run("not found", func(t *testing.T) { 52 ui := cli.NewMockUi() 53 cmd := &OperatorSnapshotInspectCommand{Meta: Meta{Ui: ui}} 54 55 code := cmd.Run([]string{filepath.Join(tmpDir, "foo")}) 56 require.NotZero(t, code) 57 require.Contains(t, ui.ErrorWriter.String(), "no such file") 58 }) 59 60 t.Run("invalid file", func(t *testing.T) { 61 ui := cli.NewMockUi() 62 cmd := &OperatorSnapshotInspectCommand{Meta: Meta{Ui: ui}} 63 64 code := cmd.Run([]string{filepath.Join(tmpDir, "invalid.snap")}) 65 require.NotZero(t, code) 66 require.Contains(t, ui.ErrorWriter.String(), "Error verifying snapshot") 67 }) 68 69 } 70 71 func generateSnapshotFile(t *testing.T, prepare func(srv *agent.TestAgent, client *api.Client, url string)) string { 72 73 tmpDir, err := ioutil.TempDir("", "nomad-tempdir") 74 require.NoError(t, err) 75 76 t.Cleanup(func() { os.RemoveAll(tmpDir) }) 77 78 srv, api, url := testServer(t, false, func(c *agent.Config) { 79 c.DevMode = false 80 c.DataDir = filepath.Join(tmpDir, "server") 81 82 c.AdvertiseAddrs.HTTP = "127.0.0.1" 83 c.AdvertiseAddrs.RPC = "127.0.0.1" 84 c.AdvertiseAddrs.Serf = "127.0.0.1" 85 }) 86 87 defer srv.Shutdown() 88 89 if prepare != nil { 90 prepare(srv, api, url) 91 } 92 93 ui := cli.NewMockUi() 94 cmd := &OperatorSnapshotSaveCommand{Meta: Meta{Ui: ui}} 95 96 dest := filepath.Join(tmpDir, "backup.snap") 97 code := cmd.Run([]string{ 98 "--address=" + url, 99 dest, 100 }) 101 require.Zero(t, code) 102 103 return dest 104 }