github.com/hernad/nomad@v1.6.112/command/operator_snapshot_save_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/ci"
    12  	"github.com/hernad/nomad/command/agent"
    13  	"github.com/hernad/nomad/helper/snapshot"
    14  	"github.com/mitchellh/cli"
    15  	"github.com/stretchr/testify/require"
    16  )
    17  
    18  func TestOperatorSnapshotSave_Works(t *testing.T) {
    19  	ci.Parallel(t)
    20  
    21  	tmpDir := t.TempDir()
    22  
    23  	srv, _, url := testServer(t, false, func(c *agent.Config) {
    24  		c.DevMode = false
    25  		c.DataDir = filepath.Join(tmpDir, "server")
    26  
    27  		c.AdvertiseAddrs.HTTP = "127.0.0.1"
    28  		c.AdvertiseAddrs.RPC = "127.0.0.1"
    29  		c.AdvertiseAddrs.Serf = "127.0.0.1"
    30  	})
    31  
    32  	defer srv.Shutdown()
    33  
    34  	ui := cli.NewMockUi()
    35  	cmd := &OperatorSnapshotSaveCommand{Meta: Meta{Ui: ui}}
    36  
    37  	dest := filepath.Join(tmpDir, "backup.snap")
    38  	code := cmd.Run([]string{
    39  		"--address=" + url,
    40  		dest,
    41  	})
    42  	require.Zero(t, code)
    43  	require.Contains(t, ui.OutputWriter.String(), "State file written to "+dest)
    44  
    45  	f, err := os.Open(dest)
    46  	require.NoError(t, err)
    47  
    48  	meta, err := snapshot.Verify(f)
    49  	require.NoError(t, err)
    50  	require.NotZero(t, meta.Index)
    51  }
    52  
    53  func TestOperatorSnapshotSave_Fails(t *testing.T) {
    54  	ci.Parallel(t)
    55  
    56  	ui := cli.NewMockUi()
    57  	cmd := &OperatorSnapshotSaveCommand{Meta: Meta{Ui: ui}}
    58  
    59  	// Fails on misuse
    60  	code := cmd.Run([]string{"some", "bad", "args"})
    61  	require.Equal(t, 1, code)
    62  	require.Contains(t, ui.ErrorWriter.String(), commandErrorText(cmd))
    63  	ui.ErrorWriter.Reset()
    64  
    65  	// Fails when specified file does not exist
    66  	code = cmd.Run([]string{"/unicorns/leprechauns"})
    67  	require.Equal(t, 1, code)
    68  	require.Contains(t, ui.ErrorWriter.String(), "no such file")
    69  }