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