github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/command/operator_snapshot_inspect_test.go (about) 1 package command 2 3 import ( 4 "io/ioutil" 5 "path/filepath" 6 "testing" 7 8 "github.com/hashicorp/nomad/api" 9 "github.com/hashicorp/nomad/ci" 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 ci.Parallel(t) 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 ci.Parallel(t) 40 41 tmpDir := t.TempDir() 42 43 err := ioutil.WriteFile( 44 filepath.Join(tmpDir, "invalid.snap"), 45 []byte("invalid data"), 46 0600) 47 require.NoError(t, err) 48 49 t.Run("not found", func(t *testing.T) { 50 ui := cli.NewMockUi() 51 cmd := &OperatorSnapshotInspectCommand{Meta: Meta{Ui: ui}} 52 53 code := cmd.Run([]string{filepath.Join(tmpDir, "foo")}) 54 require.NotZero(t, code) 55 require.Contains(t, ui.ErrorWriter.String(), "no such file") 56 }) 57 58 t.Run("invalid file", func(t *testing.T) { 59 ui := cli.NewMockUi() 60 cmd := &OperatorSnapshotInspectCommand{Meta: Meta{Ui: ui}} 61 62 code := cmd.Run([]string{filepath.Join(tmpDir, "invalid.snap")}) 63 require.NotZero(t, code) 64 require.Contains(t, ui.ErrorWriter.String(), "Error verifying snapshot") 65 }) 66 } 67 68 func generateSnapshotFile(t *testing.T, prepare func(srv *agent.TestAgent, client *api.Client, url string)) string { 69 tmpDir := t.TempDir() 70 71 srv, api, url := testServer(t, false, func(c *agent.Config) { 72 c.DevMode = false 73 c.DataDir = filepath.Join(tmpDir, "server") 74 75 c.AdvertiseAddrs.HTTP = "127.0.0.1" 76 c.AdvertiseAddrs.RPC = "127.0.0.1" 77 c.AdvertiseAddrs.Serf = "127.0.0.1" 78 }) 79 80 defer srv.Shutdown() 81 82 if prepare != nil { 83 prepare(srv, api, url) 84 } 85 86 ui := cli.NewMockUi() 87 cmd := &OperatorSnapshotSaveCommand{Meta: Meta{Ui: ui}} 88 89 dest := filepath.Join(tmpDir, "backup.snap") 90 code := cmd.Run([]string{ 91 "--address=" + url, 92 dest, 93 }) 94 require.Zero(t, code) 95 96 return dest 97 }