Skip to content
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

fix: dump body directly if json indent fails #643

Merged
merged 2 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion humatest/humatest.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,10 @@ func dumpBody(body io.ReadCloser, buf *bytes.Buffer) (io.ReadCloser, error) {
}
body.Close()
if strings.Contains(buf.String(), "json") {
json.Indent(buf, b, "", " ")
if err := json.Indent(buf, b, "", " "); err != nil {
// Indent failed, so just write the buffer.
buf.Write(b)
}
Comment on lines +348 to +351
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding test coverage for the error path.

The new error handling code is currently not covered by tests. Consider adding test cases for:

  1. Invalid JSON that fails indentation
  2. Malformed JSON with special characters

Would you like me to help generate test cases for these scenarios?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 349-351: humatest/humatest.go#L349-L351
Added lines #L349 - L351 were not covered by tests

} else {
buf.Write(b)
}
Expand Down
13 changes: 12 additions & 1 deletion humatest/humatest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ func TestNewAPI(t *testing.T) {
}

func TestDumpBodyError(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "http://example.com/foo?bar=baz", nil)
req := httptest.NewRequest(http.MethodGet, "http://example.com/foo?bar=baz", nil)
req.Header.Set("Foo", "bar")
req.Host = "example.com"
req.Body = io.NopCloser(iotest.ErrReader(io.ErrUnexpectedEOF))
Expand All @@ -165,6 +165,17 @@ func TestDumpBodyError(t *testing.T) {
require.Error(t, err)
}

func TestDumpBodyInvalidJSON(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://example.com/foo?bar=baz", nil)
req.Header.Set("Content-Type", "application/json")
req.Host = "example.com"
req.Body = io.NopCloser(strings.NewReader("invalid json"))

b, err := DumpRequest(req)
require.NoError(t, err)
assert.Contains(t, string(b), "invalid json")
}

func TestOpenAPIRequired(t *testing.T) {
assert.PanicsWithValue(t, "custom huma.Config structs must specify a value for OpenAPI", func() {
New(t, huma.Config{})
Expand Down
Loading