🧹 chore: Improve tests coverage for decoder.go#31
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughThis change adds several new test functions to Changes
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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Possibly related PRs
Suggested reviewers
Poem
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 unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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
-
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. ↩
There was a problem hiding this comment.
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>
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
decoder_test.go (2)
3547-3577: Strengthen multipart assertions and diagnostics; avoid fragile index checksMake 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 saferPrint 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 failuresValidate 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 conversionFor “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 speedMany 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
📒 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 objectivesNew 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.
Summary
Summary by CodeRabbit