Skip to content

🧹 chore: Improve tests coverage for decoder.go#31

Merged
gaby merged 2 commits intomainfrom
2025-08-10-17-21-17
Aug 10, 2025
Merged

🧹 chore: Improve tests coverage for decoder.go#31
gaby merged 2 commits intomainfrom
2025-08-10-17-21-17

Conversation

@gaby
Copy link
Copy Markdown
Member

@gaby gaby commented Aug 10, 2025

Summary

  • expand decoder slice tests for alias, pointer, and zero-empty cases
  • add multipart file decoding tests
  • cover TextUnmarshaler errors for slices

Summary by CodeRabbit

  • Tests
    • Added new tests to improve coverage of multipart file decoding, error handling for custom slice types, and decoding of comma-separated values with various options.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Aug 10, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

This change adds several new test functions to decoder_test.go to increase test coverage for multipart file header decoding, error handling in slice decoding with custom UnmarshalText implementations, and various scenarios involving decoding slices from comma-separated strings, including pointer slices and handling of zero/empty values.

Changes

Cohort / File(s) Change Summary
New multipart and slice decoding tests
decoder_test.go
Added test functions for multipart file header decoding, slice text unmarshaler error handling, and comma-separated slice decoding (including pointer slices, zero-empty handling, and alias type error cases).

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Function
    participant Decoder as Decoder
    participant Struct as Target Struct
    participant Files as Multipart Files Map

    Test->>Decoder: Call Decode with Files and Struct
    Decoder->>Struct: Populate file header fields
    Decoder-->>Test: Return decoded Struct

    Note over Test,Decoder: For error cases, Decoder returns error to Test
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Suggested reviewers

  • sixcolors
  • efectn

Poem

In fields of code where tests now grow,
Multipart files and slices in tow.
With commas and pointers, and errors that gleam,
The Decoder’s now tested—supreme!
Rabbits hop on, their coverage complete,
Every new test makes the suite more sweet.
🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2025-08-10-17-21-17

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @gaby, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

I've expanded the test coverage for the decoder, specifically focusing on various slice decoding scenarios, including multipart file handling, pointer and alias types, and error conditions for TextUnmarshaler implementations. This ensures the decoder behaves as expected under more diverse inputs and edge cases.

Highlights

  • Multipart File Decoding: I've added tests to verify the decoder's ability to correctly handle multipart.FileHeader types, supporting single file, multiple files, and pointer-to-slice configurations.
  • Slice Decoding Enhancements: I've introduced new tests for slice decoding, covering scenarios such as alias types, pointer types, and the ZeroEmpty option's behavior with comma-separated values, ensuring robust parsing.
  • TextUnmarshaler Error Coverage: I've added a test case to specifically cover error handling when a TextUnmarshaler implementation within a slice encounters an invalid input during decoding.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments or fill out our survey to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gaby gaby changed the title test: expand decoder coverage 🧹 chore: Improve tests coverage for decoder.go Aug 10, 2025
@gaby gaby marked this pull request as ready for review August 10, 2025 17:21
@gaby gaby requested a review from a team as a code owner August 10, 2025 17:21
@gaby gaby requested review from ReneWerner87, efectn and sixcolors and removed request for a team August 10, 2025 17:21
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request expands test coverage for the decoder, particularly for slice decoding with aliases, pointers, zero-empty cases, multipart files, and TextUnmarshaler errors. The new tests are well-structured and cover important edge cases. My review focuses on improving the robustness of test assertions to prevent panics on failure and to provide more informative failure messages. I've identified a couple of places where assertions could cause the test to panic and have suggested fixes.

Signed-off-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com>
@gaby gaby merged commit 2e7ce08 into main Aug 10, 2025
7 of 8 checks passed
@gaby gaby deleted the 2025-08-10-17-21-17 branch August 10, 2025 17:27
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
decoder_test.go (2)

3547-3577: Strengthen multipart assertions and diagnostics; avoid fragile index checks

Make failures more descriptive and robust by comparing slices with reflect.DeepEqual and printing expected vs got. This also avoids potential index issues in future edits. This mirrors prior feedback on similar tests.

Apply this diff:

 func TestDecodeMultipartFiles(t *testing.T) {
+    // t.Parallel() // consider enabling once test stability in parallel is confirmed
     type payload struct {
         Single   *multipart.FileHeader    `schema:"single"`
         Multiple []*multipart.FileHeader  `schema:"multi"`
         PtrSlice *[]*multipart.FileHeader `schema:"ptr"`
     }
@@
     if err := NewDecoder().Decode(&p, src, files); err != nil {
         t.Fatalf("unexpected error: %v", err)
     }
-    if p.Single != fh1 {
-        t.Fatalf("single not set")
-    }
-    if len(p.Multiple) != 2 || p.Multiple[0] != fh1 || p.Multiple[1] != fh2 {
-        t.Fatalf("multi not set")
-    }
-    if p.PtrSlice == nil || len(*p.PtrSlice) != 1 || (*p.PtrSlice)[0] != fh2 {
-        t.Fatalf("ptr slice not set")
-    }
+    if p.Single != fh1 {
+        t.Fatalf("single: got %v, want %v", p.Single, fh1)
+    }
+    expectedMultiple := []*multipart.FileHeader{fh1, fh2}
+    if !reflect.DeepEqual(p.Multiple, expectedMultiple) {
+        t.Fatalf("multi: got %v, want %v", p.Multiple, expectedMultiple)
+    }
+    expectedPtrSlice := []*multipart.FileHeader{fh2}
+    if p.PtrSlice == nil || !reflect.DeepEqual(*p.PtrSlice, expectedPtrSlice) {
+        var got []*multipart.FileHeader
+        if p.PtrSlice != nil {
+            got = *p.PtrSlice
+        }
+        t.Fatalf("ptr slice: got %v, want %v", got, expectedPtrSlice)
+    }
 }

3609-3615: Avoid pointer address printing and make slice checks safer

Print values, not pointer addresses, and check the length before dereferencing. This mirrors a previous comment.

Apply this diff:

-    if len(s.N) != 2 || *s.N[0] != 1 || *s.N[1] != 2 {
-        t.Fatalf("unexpected values: %v %v", s.N[0], s.N[1])
-    }
+    if len(s.N) != 2 {
+        t.Fatalf("unexpected slice length: got %d, want 2", len(s.N))
+    }
+    if *s.N[0] != 1 || *s.N[1] != 2 {
+        t.Fatalf("unexpected values: got [%d, %d], want [1, 2]", *s.N[0], *s.N[1])
+    }
🧹 Nitpick comments (3)
decoder_test.go (3)

3579-3588: Assert error type and location for TextUnmarshaler slice failures

Validate MultiError and that the ConversionError is reported on key "b" for stronger guarantees.

Apply this diff:

 func TestDecodeSliceTextUnmarshalerError(t *testing.T) {
     type target struct {
         B []rudeBool `schema:"b"`
     }
 
-    var s target
-    if err := NewDecoder().Decode(&s, map[string][]string{"b": {"maybe"}}); err == nil {
-        t.Fatalf("expected error")
-    }
+    var s target
+    err := NewDecoder().Decode(&s, map[string][]string{"b": {"maybe"}})
+    if err == nil {
+        t.Fatalf("expected error")
+    }
+    me, ok := err.(MultiError)
+    if !ok {
+        t.Fatalf("expected MultiError, got %T: %v", err, err)
+    }
+    if _, ok := me["b"].(ConversionError); !ok {
+        t.Fatalf(`expected ConversionError at key "b", got %T: %v`, me["b"], me["b"])
+    }
 }

3623-3626: Assert MultiError and error index for alias slice conversion

For “1,a”, the second element should fail. Asserting the error index makes the test more precise.

Apply this diff:

-    var s target
-    if err := NewDecoder().Decode(&s, map[string][]string{"a": {"1,a"}}); err == nil {
-        t.Fatalf("expected error")
-    }
+    var s target
+    err := NewDecoder().Decode(&s, map[string][]string{"a": {"1,a"}})
+    if err == nil {
+        t.Fatalf("expected error")
+    }
+    me, ok := err.(MultiError)
+    if !ok {
+        t.Fatalf("expected MultiError, got %T: %v", err, err)
+    }
+    ce, ok := me["a"].(ConversionError)
+    if !ok {
+        t.Fatalf(`expected ConversionError at key "a", got %T: %v`, me["a"], me["a"])
+    }
+    if ce.Index != 1 {
+        t.Fatalf("expected failing index 1, got %d", ce.Index)
+    }

3547-3549: Run new tests in parallel (t.Parallel) for consistency and speed

Many tests in this file leverage t.Parallel. Consider adding it at the top of each new test for consistency, provided no shared state is impacted.

Example:

 func TestDecodeMultipartFiles(t *testing.T) {
+    t.Parallel()
@@
 }
 
 func TestDecodeSliceTextUnmarshalerError(t *testing.T) {
+    t.Parallel()
@@
 }
 
 func TestDecodeCommaSeparatedZeroEmpty(t *testing.T) {
+    t.Parallel()
@@
 }
 
 func TestDecodeCommaSeparatedPointerSlice(t *testing.T) {
+    t.Parallel()
@@
 }
 
 func TestDecodeCommaSeparatedAliasSliceError(t *testing.T) {
+    t.Parallel()
@@
 }

Also applies to: 3579-3581, 3590-3593, 3605-3608, 3618-3621

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2279510 and fb1cdb6.

📒 Files selected for processing (1)
  • decoder_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2024-12-13T08:14:22.851Z
Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.

Applied to files:

  • decoder_test.go
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.

Applied to files:

  • decoder_test.go
🧬 Code Graph Analysis (1)
decoder_test.go (1)
decoder.go (1)
  • NewDecoder (21-23)
🔇 Additional comments (1)
decoder_test.go (1)

3546-3627: Good coverage additions — align with PR objectives

New tests cover multipart files, TextUnmarshaler slice errors, zero-empty behavior, pointer slices, and alias slice error paths. These directly support the stated goal of increasing decoder slice and multipart coverage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant