diff --git a/cmd/api.go b/cmd/api.go index 37c2e65..d66ae2a 100644 --- a/cmd/api.go +++ b/cmd/api.go @@ -23,6 +23,13 @@ var apiCmd = &cobra.Command{ Short: "Make a raw API request to the given Equinix API path", Long: `Make a raw authenticated request to the Equinix API using your configured credentials.`, Args: cobra.ExactArgs(1), + PreRunE: func(_ *cobra.Command, _ []string) error { + switch format { + case "json", "yaml": + return nil + } + return fmt.Errorf("invalid --format %q: must be json or yaml", format) + }, Run: func(_ *cobra.Command, args []string) { path := args[0] diff --git a/cmd/api_output_test.go b/cmd/api_output_test.go index f29ecbc..d0964f4 100644 --- a/cmd/api_output_test.go +++ b/cmd/api_output_test.go @@ -65,3 +65,39 @@ func TestE2E_APINonJSONResponseIsPrintedAsIs(t *testing.T) { t.Errorf("output = %q, want %q", out, "OK\n") } } + +// An unknown --format used to make the request and print a blank line. +func TestE2E_APIRejectsUnknownFormat(t *testing.T) { + var requests int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]string{ + "access_token": "fake-token", + "token_timeout": "3600", + "token_type": "Bearer", + "user_name": "fake-user", + "id": "abc", + }) + })) + t.Cleanup(srv.Close) + target, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + orig := http.DefaultTransport + http.DefaultTransport = redirectTransport{target: target, base: orig} + t.Cleanup(func() { http.DefaultTransport = orig }) + t.Cleanup(func() { format = "json" }) + + out, err := runCLI(t, "api", "fabric/v4/ports", "--format", "xml") + if err == nil { + t.Fatalf("command succeeded with --format xml, output %q", out) + } + if want := `invalid --format "xml": must be json or yaml`; err.Error() != want { + t.Errorf("error = %q, want %q", err, want) + } + if requests != 0 { + t.Errorf("made %d API requests, want none", requests) + } +}