From 6401ac5c68aab685fb435f8fd26358bcfabd7b05 Mon Sep 17 00:00:00 2001 From: Lucas Barros Date: Sat, 21 Nov 2026 11:51:39 -0300 Subject: [PATCH] fix: reject an unknown equinix api --format before the request The output switch only handled json and yaml, so any other --format made the request, printed a blank line and exited 0. Validate the flag in PreRunE so the command fails with a usage error naming the supported values, without calling the API. Refs #88 Signed-off-by: Lucas Barros --- cmd/api.go | 7 +++++++ cmd/api_output_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) 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) + } +}