-
Notifications
You must be signed in to change notification settings - Fork 0
fix(output): valid JSON on stdout and numeric toObjectId parsing #56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
piekstra
wants to merge
3
commits into
main
Choose a base branch
from
fix/json-output-stdout-and-associations
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| package api | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestClient_ListAssociations(t *testing.T) { | ||
| t.Run("results with numeric toObjectId parse successfully", func(t *testing.T) { | ||
| // The HubSpot CRM v4 associations API returns toObjectId as a JSON | ||
| // number, not a string. This used to fail with: | ||
| // json: cannot unmarshal number into Go struct field | ||
| // Association.results.toObjectId of type string | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| assert.Equal(t, "/crm/v4/objects/contacts/12345/associations/notes", r.URL.Path) | ||
| assert.Equal(t, http.MethodGet, r.Method) | ||
|
|
||
| w.WriteHeader(http.StatusOK) | ||
| _, _ = w.Write([]byte(`{ | ||
| "results": [ | ||
| { | ||
| "toObjectId": 98765, | ||
| "associationTypes": [ | ||
| { | ||
| "category": "HUBSPOT_DEFINED", | ||
| "typeId": 202, | ||
| "label": "Contact to Note" | ||
| } | ||
| ] | ||
| } | ||
| ] | ||
| }`)) | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| client := &Client{ | ||
| BaseURL: server.URL, | ||
| AccessToken: "test-token", | ||
| HTTPClient: server.Client(), | ||
| } | ||
|
|
||
| result, err := client.ListAssociations(ObjectTypeContacts, "12345", ObjectTypeNotes, ListOptions{}) | ||
| require.NoError(t, err) | ||
| require.Len(t, result.Results, 1) | ||
| assert.Equal(t, "98765", result.Results[0].ToObjectID.String()) | ||
| require.Len(t, result.Results[0].AssociationTypes, 1) | ||
| assert.Equal(t, "HUBSPOT_DEFINED", result.Results[0].AssociationTypes[0].Category) | ||
| assert.Equal(t, 202, result.Results[0].AssociationTypes[0].TypeID) | ||
| }) | ||
|
|
||
| t.Run("empty results parse cleanly", func(t *testing.T) { | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusOK) | ||
| _, _ = w.Write([]byte(`{"results": []}`)) | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| client := &Client{ | ||
| BaseURL: server.URL, | ||
| AccessToken: "test-token", | ||
| HTTPClient: server.Client(), | ||
| } | ||
|
|
||
| result, err := client.ListAssociations(ObjectTypeContacts, "12345", ObjectTypeNotes, ListOptions{}) | ||
| require.NoError(t, err) | ||
| assert.Empty(t, result.Results) | ||
| }) | ||
|
|
||
| t.Run("result re-serializes to valid JSON with numeric id", func(t *testing.T) { | ||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.WriteHeader(http.StatusOK) | ||
| _, _ = w.Write([]byte(`{ | ||
| "results": [ | ||
| {"toObjectId": 98765, "associationTypes": []} | ||
| ] | ||
| }`)) | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| client := &Client{ | ||
| BaseURL: server.URL, | ||
| AccessToken: "test-token", | ||
| HTTPClient: server.Client(), | ||
| } | ||
|
|
||
| result, err := client.ListAssociations(ObjectTypeContacts, "12345", ObjectTypeNotes, ListOptions{}) | ||
| require.NoError(t, err) | ||
|
|
||
| // Re-marshalling produces valid JSON; json.Number preserves the | ||
| // number as a number (not a quoted string). | ||
| out, err := json.Marshal(result) | ||
| require.NoError(t, err) | ||
|
|
||
| var roundtrip map[string]interface{} | ||
| require.NoError(t, json.Unmarshal(out, &roundtrip), "marshalled output must be valid JSON") | ||
| assert.Contains(t, string(out), `"toObjectId":98765`) | ||
| }) | ||
|
|
||
| t.Run("empty from ID returns error", func(t *testing.T) { | ||
| client := &Client{BaseURL: "https://api.hubapi.com"} | ||
| result, err := client.ListAssociations(ObjectTypeContacts, "", ObjectTypeNotes, ListOptions{}) | ||
| assert.Error(t, err) | ||
| assert.Contains(t, err.Error(), "from object ID is required") | ||
| assert.Nil(t, result) | ||
| }) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| package view | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "encoding/json" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| // newTestView returns a View that writes to the provided buffers, with color | ||
| // disabled so assertions can match raw text without ANSI escape codes. | ||
| func newTestView(format string) (*View, *bytes.Buffer, *bytes.Buffer) { | ||
| var out, errBuf bytes.Buffer | ||
| v := New(format, true) // noColor=true | ||
| v.Out = &out | ||
| v.Err = &errBuf | ||
| return v, &out, &errBuf | ||
| } | ||
|
|
||
| // TestStatusMessagesGoToStderr ensures human-facing status/progress messages | ||
| // are written to stderr, not stdout. This is what keeps `--output json` | ||
| // output valid (issue #52): only the JSON payload may land on stdout. | ||
| func TestStatusMessagesGoToStderr(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| call func(v *View) | ||
| want string | ||
| }{ | ||
| {"Success", func(v *View) { v.Success("created with ID %s", "98765") }, "created with ID 98765"}, | ||
| {"Info", func(v *View) { v.Info("Found %d contact(s)", 3) }, "Found 3 contact(s)"}, | ||
| {"PrintStatus", func(v *View) { v.PrintStatus("progress %d%%", 50) }, "progress 50%"}, | ||
| {"PrintlnStatus", func(v *View) { v.PrintlnStatus("More results available") }, "More results available"}, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| v, out, errBuf := newTestView("json") | ||
| tt.call(v) | ||
|
|
||
| assert.Empty(t, out.String(), "status message must NOT be written to stdout") | ||
| assert.Contains(t, errBuf.String(), tt.want, "status message must be written to stderr") | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| // TestErrorAndWarningGoToStderr documents that Error and Warning remain on | ||
| // stderr (they always have); this is now consistent with the status methods | ||
| // Success/Info/PrintStatus/PrintlnStatus. | ||
| func TestErrorAndWarningGoToStderr(t *testing.T) { | ||
| v, out, errBuf := newTestView("json") | ||
|
|
||
| v.Error("boom %s", "x") | ||
| v.Warning("careful %s", "y") | ||
|
|
||
| assert.Empty(t, out.String()) | ||
| assert.Contains(t, errBuf.String(), "boom x") | ||
| assert.Contains(t, errBuf.String(), "careful y") | ||
| } | ||
|
|
||
| // TestStdoutIsValidJSON simulates a command that emits a status message | ||
| // followed by a JSON payload, and verifies stdout alone is parseable JSON. | ||
| func TestStdoutIsValidJSON(t *testing.T) { | ||
| v, out, _ := newTestView("json") | ||
|
|
||
| // Order mirrors real commands: status first, then structured payload. | ||
| v.Success("Note created with ID: %s", "98765") | ||
| v.Info("Found 1 result") | ||
| require.NoError(t, v.JSON(map[string]interface{}{ | ||
| "id": "98765", | ||
| "name": "Demo", | ||
| })) | ||
| v.Info("More results available. Use --after abc123 to get the next page.") | ||
|
|
||
| stdout := out.String() | ||
| assert.NotContains(t, stdout, "Note created", "no status banner may leak to stdout") | ||
| assert.NotContains(t, stdout, "More results", "no pagination text may leak to stdout") | ||
|
|
||
| var parsed map[string]interface{} | ||
| require.NoError(t, json.Unmarshal([]byte(stdout), &parsed), | ||
| "stdout must be valid JSON, got: %q", stdout) | ||
| assert.Equal(t, "98765", parsed["id"]) | ||
| } | ||
|
|
||
| // TestPrimaryOutputGoesToStdout guarantees the other half of the invariant: | ||
| // the primary rendered result (Table/Plain/Render/JSON) always lands on stdout, | ||
| // never stderr, even while status chatter is routed to stderr. If a "status" | ||
| // method ever leaked primary output to stderr, this would catch it. | ||
| func TestPrimaryOutputGoesToStdout(t *testing.T) { | ||
| t.Run("table renders to stdout in human mode", func(t *testing.T) { | ||
| v, out, errBuf := newTestView("table") | ||
| // Interleave status messages with the primary rendered result. | ||
| v.Info("Found 1 result") | ||
| require.NoError(t, v.Render([]string{"ID", "NAME"}, [][]string{{"98765", "Demo"}}, nil)) | ||
| v.PrintlnStatus("More results available") | ||
|
|
||
| stdout := out.String() | ||
| assert.Contains(t, stdout, "98765", "primary rendered data must be on stdout") | ||
| assert.Contains(t, stdout, "Demo", "primary rendered data must be on stdout") | ||
| // Status chatter must not leak into the primary stdout stream. | ||
| assert.NotContains(t, stdout, "Found 1 result") | ||
| assert.NotContains(t, stdout, "More results available") | ||
| assert.Contains(t, errBuf.String(), "Found 1 result") | ||
| assert.Contains(t, errBuf.String(), "More results available") | ||
| }) | ||
|
|
||
| t.Run("plain renders to stdout in plain mode", func(t *testing.T) { | ||
| v, out, errBuf := newTestView("plain") | ||
| v.Info("Found 1 result") | ||
| require.NoError(t, v.Render(nil, [][]string{{"98765", "Demo"}}, nil)) | ||
|
|
||
| assert.Contains(t, out.String(), "98765", "primary rendered data must be on stdout") | ||
| assert.NotContains(t, out.String(), "Found 1 result") | ||
| assert.Contains(t, errBuf.String(), "Found 1 result") | ||
| }) | ||
| } | ||
|
|
||
| // TestJSONOutputUnaffectedByColorFlag is a small sanity check that JSON output | ||
| // is plain (no ANSI codes regardless of color setting). | ||
| func TestJSONOutputUnaffectedByColorFlag(t *testing.T) { | ||
| v, out, _ := newTestView("json") | ||
| require.NoError(t, v.JSON([]string{"a", "b"})) | ||
| assert.False(t, strings.Contains(out.String(), "\x1b["), "JSON output must not contain ANSI escapes") | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.