From 86bc7ed22493af77a889fcc8d540cd2d8b704137 Mon Sep 17 00:00:00 2001 From: James Rasell Date: Thu, 12 Dec 2024 13:43:32 +0000 Subject: [PATCH] cli: Ensure JSON flag is respected in `autopilot health` command. (#24655) --- .changelog/24655.txt | 3 +++ command/operator_autopilot_health.go | 4 ++-- command/operator_autopilot_health_test.go | 23 +++++++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 .changelog/24655.txt diff --git a/.changelog/24655.txt b/.changelog/24655.txt new file mode 100644 index 000000000..6cc5589f0 --- /dev/null +++ b/.changelog/24655.txt @@ -0,0 +1,3 @@ +```release-note:bug +cli: Ensure the `operator autopilot health` command only outputs JSON when the `json` flag is supplied +``` diff --git a/command/operator_autopilot_health.go b/command/operator_autopilot_health.go index 4b9e0c893..9d03e3606 100644 --- a/command/operator_autopilot_health.go +++ b/command/operator_autopilot_health.go @@ -59,10 +59,10 @@ func (c *OperatorAutopilotHealthCommand) Run(args []string) int { return 1 } c.Ui.Output(string(bytes)) + } else { + c.Ui.Output(formatAutopilotState(state)) } - c.Ui.Output(formatAutopilotState(state)) - return 0 } diff --git a/command/operator_autopilot_health_test.go b/command/operator_autopilot_health_test.go index f42b3269d..4c0a38d7c 100644 --- a/command/operator_autopilot_health_test.go +++ b/command/operator_autopilot_health_test.go @@ -4,8 +4,10 @@ package command import ( + "encoding/json" "testing" + "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/ci" "github.com/mitchellh/cli" "github.com/shoenig/test/must" @@ -31,3 +33,24 @@ func TestOperatorAutopilotStateCommand(t *testing.T) { out := ui.OutputWriter.String() must.StrContains(t, out, "Healthy") } + +func TestOperatorAutopilotStateCommand_JSON(t *testing.T) { + ci.Parallel(t) + s, _, addr := testServer(t, false, nil) + defer s.Shutdown() + + ui := cli.NewMockUi() + c := &OperatorAutopilotHealthCommand{Meta: Meta{Ui: ui}} + args := []string{"-address=" + addr, "-json"} + + code := c.Run(args) + must.Eq(t, 0, code, must.Sprintf("got error for exit code: %v", ui.ErrorWriter.String())) + + // Attempt to unmarshal the data which tests that the output is JSON and + // peak into the data, checking that healthy is an expected and no-default + // value. + operatorHealthyReply := api.OperatorHealthReply{} + + must.NoError(t, json.Unmarshal(ui.OutputWriter.Bytes(), &operatorHealthyReply)) + must.True(t, operatorHealthyReply.Healthy) +}