github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/command/metrics_test.go (about)

     1  package command
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/hashicorp/nomad/ci"
     7  	"github.com/mitchellh/cli"
     8  	"github.com/stretchr/testify/require"
     9  )
    10  
    11  var _ cli.Command = &OperatorMetricsCommand{}
    12  
    13  func TestCommand_Metrics_Cases(t *testing.T) {
    14  	ci.Parallel(t)
    15  
    16  	srv, _, url := testServer(t, false, nil)
    17  	defer srv.Shutdown()
    18  
    19  	ui := cli.NewMockUi()
    20  	cmd := &OperatorMetricsCommand{Meta: Meta{Ui: ui}}
    21  
    22  	cases := []struct {
    23  		name           string
    24  		args           []string
    25  		expectedCode   int
    26  		expectedOutput string
    27  		expectedError  string
    28  	}{
    29  		{
    30  			"gotemplate MetricsSummary",
    31  			[]string{"-address=" + url, "-t", "'{{ .Timestamp }}'"},
    32  			0,
    33  			"UTC",
    34  			"",
    35  		},
    36  		{
    37  			"json formatted MetricsSummary",
    38  			[]string{"-address=" + url, "-json"},
    39  			0,
    40  			"{",
    41  			"",
    42  		},
    43  		{
    44  			"pretty print json",
    45  			[]string{"-address=" + url, "-pretty"},
    46  			0,
    47  			"{",
    48  			"",
    49  		},
    50  		{
    51  			"prometheus format",
    52  			[]string{"-address=" + url, "-format", "prometheus"},
    53  			0,
    54  			"# HELP",
    55  			"",
    56  		},
    57  		{
    58  			"bad argument",
    59  			[]string{"-address=" + url, "-foo", "bar"},
    60  			1,
    61  			"Usage: nomad operator metrics",
    62  			"flag provided but not defined: -foo",
    63  		},
    64  		{
    65  			"bad address - no protocol",
    66  			[]string{"-address=foo"},
    67  			1,
    68  			"",
    69  			"Error getting metrics: Get \"/v1/metrics\": unsupported protocol scheme",
    70  		},
    71  		{
    72  			"bad address - fake host",
    73  			[]string{"-address=http://foo"},
    74  			1,
    75  			"",
    76  			"dial tcp: lookup foo: Temporary failure in name resolution",
    77  		},
    78  	}
    79  
    80  	for _, c := range cases {
    81  		t.Run(c.name, func(t *testing.T) {
    82  			code := cmd.Run(c.args)
    83  			out := ui.OutputWriter.String()
    84  			outerr := ui.ErrorWriter.String()
    85  
    86  			require.Equalf(t, code, c.expectedCode, "expected exit code %d, got: %d: %s", c.expectedCode, code, outerr)
    87  			require.Contains(t, out, c.expectedOutput, "expected output \"%s\", got \"%s\"", c.expectedOutput, out)
    88  			require.Containsf(t, outerr, c.expectedError, "expected error \"%s\", got \"%s\"", c.expectedError, outerr)
    89  
    90  			ui.OutputWriter.Reset()
    91  			ui.ErrorWriter.Reset()
    92  		})
    93  	}
    94  }