Skip to content

Add utility tests and benchmarks#29

Merged
ReneWerner87 merged 9 commits intomainfrom
codex/2025-07-11-18-06-35
Jul 12, 2025
Merged

Add utility tests and benchmarks#29
ReneWerner87 merged 9 commits intomainfrom
codex/2025-07-11-18-06-35

Conversation

@ReneWerner87
Copy link
Copy Markdown
Member

@ReneWerner87 ReneWerner87 commented Jul 11, 2025

Summary

  • add tests for field tag parsing, tag options, pointer validity, and pointer conversion
  • add benchmarks for tag parsing, zero-checking, and pointer conversion

Testing

  • go test ./...
  • go test -bench BenchmarkParseTag -benchmem
  • go test -bench BenchmarkIsZero -benchmem
  • go test -bench BenchmarkConvertPointer -benchmem

https://chatgpt.com/codex/tasks/task_e_6871518da4848326a954cf8e451b8651

Summary by CodeRabbit

  • Tests
    • Added comprehensive unit tests for utility functions covering tag parsing, struct pointer validation, zero-value detection, and pointer conversion.
    • Introduced tests for error handling and merging in multi-error management.
    • Added unit tests and benchmarks for type conversion functions.
    • Included benchmarks to measure the performance of key utility functions.
    • Updated benchmark loops in encoding and decoding tests to use idiomatic iteration patterns.

@ReneWerner87 ReneWerner87 requested a review from a team as a code owner July 11, 2025 18:06
@ReneWerner87 ReneWerner87 requested review from efectn, gaby and sixcolors and removed request for a team July 11, 2025 18:06
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jul 11, 2025

Walkthrough

New test files util_test.go, multierror_test.go, and converter_test.go have been added to the schema package. They introduce comprehensive unit tests and benchmarks for utility functions related to struct tag parsing, reflection, pointer conversion, zero-value detection, type conversion functions, and the MultiError type's error formatting and merging behavior. Additionally, benchmark loops in decoder_test.go and encoder_test.go were updated to use the idiomatic b.Loop() method, removing explicit loops and timer resets.

Changes

File(s) Change Summary
schema/util_test.go Added unit tests and benchmarks for struct tag parsing, reflection-based type handling, zero-value detection, and pointer conversion.
schema/multierror_test.go Added unit tests for MultiError type covering error string formatting and merging of multiple errors, plus benchmarks.
schema/converter_test.go Added unit tests and benchmarks for various type conversion functions and verification of builtin converters map completeness.
schema/decoder_test.go Updated benchmark loops to use b.Loop() idiomatic form; removed explicit loops and b.ResetTimer() calls.
schema/encoder_test.go Updated benchmark loops to use b.Loop() idiomatic form; removed explicit loops and b.ResetTimer() calls.

Suggested labels

🧹 Updates

Suggested reviewers

  • gaby
  • sixcolors

Poem

In the warren of code, new tests now appear,
Checking tags and pointers with bunny-like cheer.
Benchmarks hop quickly, results in their wake,
Ensuring each function makes not a mistake.
MultiError’s tales now told with care,
Converters dance lightly through the air! 🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a3ed089 and c41ac69.

📒 Files selected for processing (5)
  • converter_test.go (1 hunks)
  • decoder_test.go (8 hunks)
  • encoder_test.go (3 hunks)
  • multierror_test.go (1 hunks)
  • util_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • decoder_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • multierror_test.go
  • util_test.go
  • converter_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: juls0730
PR: gofiber/recipes#2710
File: tableflip/main.go:61-62
Timestamp: 2024-12-01T01:15:48.126Z
Learning: In the GoFiber `tableflip` recipe (`tableflip/main.go`), the implementation matches the upstream reference implementation. Future code suggestions should consider maintaining this alignment to ensure consistency.
Learnt from: ReneWerner87
PR: gofiber/recipes#0
File: :0-0
Timestamp: 2024-11-26T20:05:15.793Z
Learning: For future contributions to the `gofiber/recipes` repository, ensure that the tasks outlined in `.github/CONTRIBUTING.md` are incorporated, including creating a new directory without a "fiber" prefix, adding a `README.md` with Docusaurus metadata, and updating the overview by running `make generate`.
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
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`.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
encoder_test.go (4)
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse_test.go:138-160
Timestamp: 2024-07-01T15:48:53.094Z
Learning: The `Test_Reset` function in `clickhouse/clickhouse_test.go` already includes a verification step to ensure the storage is empty after a reset operation by checking that a previously set key returns an empty byte slice.
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse_test.go:138-160
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `Test_Reset` function in `clickhouse/clickhouse_test.go` already includes a verification step to ensure the storage is empty after a reset operation by checking that a previously set key returns an empty byte slice.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/middleware_test.go:190-191
Timestamp: 2024-10-12T10:01:44.206Z
Learning: When testing session `IdleTimeout` expiration, it's acceptable to use `time.Sleep` to simulate the passage of time in tests.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/middleware_test.go:190-191
Timestamp: 2024-09-25T17:05:06.991Z
Learning: When testing session `IdleTimeout` expiration, it's acceptable to use `time.Sleep` to simulate the passage of time in tests.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: Compare
  • GitHub Check: unit (1.24.x, ubuntu-latest)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: lint
  • GitHub Check: repeated
🔇 Additional comments (3)
encoder_test.go (3)

675-675: Excellent modernization of benchmark loop syntax!

The update to use for b.Loop() follows the new Go benchmarking best practices introduced in Go 1.24, providing cleaner syntax and automatic timing management.


739-739: Great improvement to benchmark syntax!

Consistent application of the modern for b.Loop() pattern across all sequential benchmarks.


788-788: Perfect consistency with modern Go benchmarking!

The use of for b.Loop() completes the modernization of all sequential benchmark functions in this file.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/2025-07-11-18-06-35

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.
    • @coderabbitai modularize this function.
  • 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.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 auto-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 @ReneWerner87, 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!

This pull request significantly enhances the robustness and performance understanding of the project's utility functions by introducing a dedicated test file. It adds comprehensive unit tests to ensure the correctness of various reflection-based operations and establishes benchmarks to measure the efficiency of key parsing and conversion routines, contributing to overall code quality and maintainability.

Highlights

  • Unit Tests: Added new unit tests for utility functions, specifically covering field tag parsing (parseTag, fieldAlias), tag option handling (tagOptions.Contains, getDefaultOptionValue), pointer validity checks (isValidStructPointer), and pointer type conversion (convertPointer). These tests ensure the correctness and expected behavior of these reflection-based utilities.
  • Performance Benchmarks: Introduced performance benchmarks for critical utility operations, including tag parsing (parseTag), zero-value checking (isZero), and pointer conversion (convertPointer). These benchmarks will help monitor and optimize the efficiency of these frequently used functions.
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 is currently in preview and 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 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.

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: 5

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 03290a2 and 44a1c3d.

📒 Files selected for processing (1)
  • util_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
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`.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
util_test.go (9)
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`.
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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.22.x, macos-13)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: unit (1.23.x, macos-latest)
  • GitHub Check: unit (1.23.x, ubuntu-latest)
  • GitHub Check: unit (1.24.x, ubuntu-latest)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: unit (1.22.x, windows-latest)
  • GitHub Check: Compare
  • GitHub Check: repeated
🔇 Additional comments (1)
util_test.go (1)

88-106: Benchmark functions are well-structured and appropriate.

The benchmark functions cover key utility functions and follow Go benchmarking best practices. The test cases are representative of typical usage patterns.

Comment on lines +21 to +36
func TestFieldAlias(t *testing.T) {
type S struct {
Field string `json:"custom,omitempty"`
}
f, ok := reflect.TypeOf(S{}).FieldByName("Field")
if !ok {
t.Fatal("field not found")
}
alias, opts := fieldAlias(f, "json")
if alias != "custom" {
t.Fatalf("expected alias custom, got %s", alias)
}
if !opts.Contains("omitempty") {
t.Fatalf("expected omitempty option")
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use testify/require for assertions to maintain consistency with project standards.

 func TestFieldAlias(t *testing.T) {
 	type S struct {
 		Field string `json:"custom,omitempty"`
 	}
 	f, ok := reflect.TypeOf(S{}).FieldByName("Field")
-	if !ok {
-		t.Fatal("field not found")
-	}
+	require.True(t, ok, "field not found")
 	alias, opts := fieldAlias(f, "json")
-	if alias != "custom" {
-		t.Fatalf("expected alias custom, got %s", alias)
-	}
-	if !opts.Contains("omitempty") {
-		t.Fatalf("expected omitempty option")
-	}
+	require.Equal(t, "custom", alias)
+	require.True(t, opts.Contains("omitempty"))
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestFieldAlias(t *testing.T) {
type S struct {
Field string `json:"custom,omitempty"`
}
f, ok := reflect.TypeOf(S{}).FieldByName("Field")
if !ok {
t.Fatal("field not found")
}
alias, opts := fieldAlias(f, "json")
if alias != "custom" {
t.Fatalf("expected alias custom, got %s", alias)
}
if !opts.Contains("omitempty") {
t.Fatalf("expected omitempty option")
}
}
func TestFieldAlias(t *testing.T) {
type S struct {
Field string `json:"custom,omitempty"`
}
f, ok := reflect.TypeOf(S{}).FieldByName("Field")
require.True(t, ok, "field not found")
alias, opts := fieldAlias(f, "json")
require.Equal(t, "custom", alias)
require.True(t, opts.Contains("omitempty"))
}
🤖 Prompt for AI Agents
In util_test.go around lines 21 to 36, the test uses standard library t.Fatalf
and t.Fatal for assertions, but the project prefers using testify/require for
consistency. Replace all t.Fatal and t.Fatalf calls with require functions like
require.True, require.Equal, and require.Contains from the testify/require
package to assert conditions and fail tests more cleanly.

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 adds a suite of tests and benchmarks for utility functions. The tests cover the basic functionality, but they could be improved by using table-driven tests to increase coverage of edge cases and improve maintainability. I've also identified a potential panic in one of the utility functions that the new tests don't catch. My review provides suggestions to make the tests more robust and idiomatic.

Comment on lines +48 to +64
func TestIsValidStructPointer(t *testing.T) {
type S struct{}
if !isValidStructPointer(reflect.ValueOf(&S{})) {
t.Errorf("expected true for struct pointer")
}
if isValidStructPointer(reflect.ValueOf(S{})) {
t.Errorf("expected false for struct value")
}
var sp *S
if isValidStructPointer(reflect.ValueOf(sp)) {
t.Errorf("expected false for nil pointer")
}
var i int
if isValidStructPointer(reflect.ValueOf(&i)) {
t.Errorf("expected false for pointer to non-struct")
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The function isValidStructPointer is not robust against an invalid reflect.Value (e.g., one returned from reflect.ValueOf(nil)). Calling it with such a value will cause a panic because it calls v.Type() without first checking v.IsValid().

I recommend refactoring this test to be table-driven and adding a commented-out test case for this scenario to highlight the issue. The function in encoder.go should be fixed to prevent panics. A simple if !v.IsValid() { return false } at the beginning of isValidStructPointer would solve this.

func TestIsValidStructPointer(t *testing.T) {
	type S struct{}
	var sp *S
	var i int

	testCases := []struct {
		name  string
		value reflect.Value
		want  bool
	}{
		{"valid struct pointer", reflect.ValueOf(&S{}), true},
		{"struct value", reflect.ValueOf(S{}), false},
		{"nil pointer to struct", reflect.ValueOf(sp), false},
		{"pointer to non-struct", reflect.ValueOf(&i), false},
		// {"invalid value", reflect.Value{}, false}, // This would panic, isValidStructPointer should be fixed.
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			if got := isValidStructPointer(tc.value); got != tc.want {
				t.Errorf("isValidStructPointer() = %v, want %v", got, tc.want)
			}
		})
	}
}

@codecov
Copy link
Copy Markdown

codecov bot commented Jul 12, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 89.94%. Comparing base (03290a2) to head (c41ac69).
Report is 10 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #29      +/-   ##
==========================================
+ Coverage   88.46%   89.94%   +1.48%     
==========================================
  Files           4        4              
  Lines         945      945              
==========================================
+ Hits          836      850      +14     
+ Misses         91       77      -14     
  Partials       18       18              
Flag Coverage Δ
unittests 89.94% <ø> (+1.48%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

with:
go-version: ${{ matrix.go-version }}

- name: Download gotestsum
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This can be removed

esac
curl -sSL "https://github.com/gotestyourself/gotestsum/releases/download/v${VER}/gotestsum_${VER}_${OS}_${ARCH}.tar.gz" | tar -xz
- name: Test
run: go run gotest.tools/gotestsum@latest -f testname -- ./... -race -count=1 -coverprofile=coverage.txt -covermode=atomic -shuffle=on
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Here instead of @latest use @v1.12.0

Until we remove old go versions from the repo

with:
go-version: stable

- name: Download gotestsum
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same here

@gaby
Copy link
Copy Markdown
Member

gaby commented Jul 12, 2025

@ReneWerner87 copy the golangci-lint workflow from gofiber/fiber. It's diff than the one here

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

🧹 Nitpick comments (3)
multierror_test.go (3)

3-7: Consider adding testify imports for better assertions.

Based on project preferences, consider adding testify imports to improve test readability and error reporting.

 import (
 	"errors"
 	"strings"
 	"testing"
+
+	"github.com/stretchr/testify/require"
 )

9-37: Replace manual assertions with testify/require for better error reporting.

The test logic is correct, but the project prefers using testify/require methods for assertions instead of manual comparisons and calls to t.Fatal or t.Fatalf.

 func TestMultiErrorError(t *testing.T) {
 	var m MultiError
-	if got := m.Error(); got != "(0 errors)" {
-		t.Fatalf("expected (0 errors), got %q", got)
-	}
+	require.Equal(t, "(0 errors)", m.Error())
 
 	errA := errors.New("a")
 	m = MultiError{"a": errA}
-	if got := m.Error(); got != errA.Error() {
-		t.Fatalf("expected %q, got %q", errA.Error(), got)
-	}
+	require.Equal(t, errA.Error(), m.Error())
 
 	errB := errors.New("b")
 	m = MultiError{"a": errA, "b": errB}
 	out := m.Error()
-	if !strings.HasSuffix(out, "(and 1 other error)") {
-		t.Fatalf("unexpected output %q", out)
-	}
-	if !strings.HasPrefix(out, errA.Error()) && !strings.HasPrefix(out, errB.Error()) {
-		t.Fatalf("unexpected prefix %q", out)
-	}
+	require.True(t, strings.HasSuffix(out, "(and 1 other error)"), "unexpected output %q", out)
+	require.True(t, strings.HasPrefix(out, errA.Error()) || strings.HasPrefix(out, errB.Error()), "unexpected prefix %q", out)
 
 	errC := errors.New("c")
 	m = MultiError{"a": errA, "b": errB, "c": errC}
 	out = m.Error()
-	if !strings.HasSuffix(out, "(and 2 other errors)") {
-		t.Fatalf("unexpected output %q", out)
-	}
+	require.True(t, strings.HasSuffix(out, "(and 2 other errors)"), "unexpected output %q", out)
 }

39-54: Replace manual assertions with testify/require for consistency.

The merge test logic is correct and properly validates that existing keys are not overwritten while new keys are added. However, consider using testify/require for consistency with project preferences.

 func TestMultiErrorMerge(t *testing.T) {
 	errA := errors.New("a")
 	m1 := MultiError{"a": errA}
 	errB := errors.New("b")
 	m2 := MultiError{"a": errors.New("ignore"), "b": errB}
 	m1.merge(m2)
-	if len(m1) != 2 {
-		t.Fatalf("expected len 2, got %d", len(m1))
-	}
-	if m1["a"] != errA {
-		t.Errorf("existing key overwritten")
-	}
-	if m1["b"].Error() != errB.Error() {
-		t.Errorf("missing merged error")
-	}
+	require.Len(t, m1, 2)
+	require.Equal(t, errA, m1["a"], "existing key should not be overwritten")
+	require.Equal(t, errB.Error(), m1["b"].Error(), "merged error should be present")
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 44a1c3d and af397f5.

⛔ Files ignored due to path filters (4)
  • .github/workflows/benchmark.yml is excluded by !**/*.yml
  • .github/workflows/linter.yml is excluded by !**/*.yml
  • .github/workflows/test.yml is excluded by !**/*.yml
  • go.mod is excluded by !**/*.mod
📒 Files selected for processing (2)
  • multierror_test.go (1 hunks)
  • util_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • util_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: juls0730
PR: gofiber/recipes#2710
File: tableflip/main.go:61-62
Timestamp: 2024-12-01T01:15:48.126Z
Learning: In the GoFiber `tableflip` recipe (`tableflip/main.go`), the implementation matches the upstream reference implementation. Future code suggestions should consider maintaining this alignment to ensure consistency.
Learnt from: ReneWerner87
PR: gofiber/recipes#0
File: :0-0
Timestamp: 2024-11-26T20:05:15.793Z
Learning: For future contributions to the `gofiber/recipes` repository, ensure that the tasks outlined in `.github/CONTRIBUTING.md` are incorporated, including creating a new directory without a "fiber" prefix, adding a `README.md` with Docusaurus metadata, and updating the overview by running `make generate`.
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
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`.
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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/memory_db_test.go:0-0
Timestamp: 2024-11-25T19:36:45.661Z
Learning: In the `clean-code/app/datasources/database/memory_db.go`, the in-memory database implementation is not intended for production use. Therefore, adding extensive tests for concurrency and error handling in `memory_db_test.go` is unnecessary.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
multierror_test.go (9)
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`.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/memory_db_test.go:0-0
Timestamp: 2024-11-25T19:36:45.661Z
Learning: In the `clean-code/app/datasources/database/memory_db.go`, the in-memory database implementation is not intended for production use. Therefore, adding extensive tests for concurrency and error handling in `memory_db_test.go` is unnecessary.
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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
🧬 Code Graph Analysis (1)
multierror_test.go (1)
decoder.go (1)
  • MultiError (727-727)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, macos-latest)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: unit (1.24.x, ubuntu-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
  • GitHub Check: lint

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: 3

♻️ Duplicate comments (6)
util_test.go (6)

8-19: Use testify/require for assertions to maintain consistency with project standards.


21-36: Use testify/require for assertions to maintain consistency with project standards.


38-46: Use testify/require for assertions to maintain consistency with project standards.


48-64: Use testify/require for assertions and address robustness concerns.


66-86: Use testify/require for assertions and consider table-driven approach.


3-6: Add testify/require import for consistent assertion style.

To support the assertion style improvements suggested in other comments, the testify/require package needs to be imported.

 import (
 	"reflect"
 	"testing"
+
+	"github.com/stretchr/testify/require"
 )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between af397f5 and a3ed089.

📒 Files selected for processing (3)
  • converter_test.go (1 hunks)
  • multierror_test.go (1 hunks)
  • util_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • multierror_test.go
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: juls0730
PR: gofiber/recipes#2710
File: tableflip/main.go:61-62
Timestamp: 2024-12-01T01:15:48.126Z
Learning: In the GoFiber `tableflip` recipe (`tableflip/main.go`), the implementation matches the upstream reference implementation. Future code suggestions should consider maintaining this alignment to ensure consistency.
Learnt from: ReneWerner87
PR: gofiber/recipes#0
File: :0-0
Timestamp: 2024-11-26T20:05:15.793Z
Learning: For future contributions to the `gofiber/recipes` repository, ensure that the tasks outlined in `.github/CONTRIBUTING.md` are incorporated, including creating a new directory without a "fiber" prefix, adding a `README.md` with Docusaurus metadata, and updating the overview by running `make generate`.
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
Learnt from: ReneWerner87
PR: gofiber/fiber#2864
File: ctx_test.go:4816-4816
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `ParamsInt` function's behavior, including handling empty string parameters, will be addressed in future PRs as per ReneWerner87's guidance.
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`.
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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
converter_test.go (10)
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
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`.
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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
Learnt from: sixcolors
PR: gofiber/fiber#3051
File: middleware/session/session.go:215-216
Timestamp: 2024-06-30T00:38:06.580Z
Learning: Parallel tests for `Session.Save` already exist in the `middleware/session/session_test.go` file, specifically in the `Test_Session_Save` and `Test_Session_Save_Expiration` functions.
util_test.go (18)
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`.
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.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-07-02T13:29:56.992Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: gaby
PR: gofiber/fiber#3056
File: middleware/encryptcookie/utils.go:22-25
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `encryptcookie_test.go` file contains unit tests that validate key lengths for both `EncryptCookie` and `DecryptCookie` functions, ensuring that invalid key lengths raise appropriate errors.
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db_mock.go:13-19
Timestamp: 2024-11-23T19:50:06.387Z
Learning: In test code within `clean-code/app/datasources/database/db_mock.go`, adding safety checks like context validation, safe type assertions, and extra documentation is not necessary.
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse_test.go:138-160
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `Test_Reset` function in `clickhouse/clickhouse_test.go` already includes a verification step to ensure the storage is empty after a reset operation by checking that a previously set key returns an empty byte slice.
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse_test.go:138-160
Timestamp: 2024-07-01T15:48:53.094Z
Learning: The `Test_Reset` function in `clickhouse/clickhouse_test.go` already includes a verification step to ensure the storage is empty after a reset operation by checking that a previously set key returns an empty byte slice.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/datasources/database/db.go:16-19
Timestamp: 2024-11-23T19:43:14.861Z
Learning: In the Go file `clean-code/app/datasources/database/db.go`, the `NewBook` struct should not include validation constraints as validation is not in scope.
Learnt from: norri
PR: gofiber/recipes#2701
File: clean-code/app/server/handlers/books.go:28-43
Timestamp: 2024-11-23T19:54:01.389Z
Learning: In 'clean-code/app/server/handlers/books.go', validation is out of scope and should not be suggested.
Learnt from: juls0730
PR: gofiber/recipes#2710
File: tableflip/main.go:61-62
Timestamp: 2024-12-01T01:15:48.126Z
Learning: In the GoFiber `tableflip` recipe (`tableflip/main.go`), the implementation matches the upstream reference implementation. Future code suggestions should consider maintaining this alignment to ensure consistency.
Learnt from: mdelapenya
PR: gofiber/storage#1665
File: cassandra/cassandra_test.go:35-38
Timestamp: 2025-04-20T23:52:03.362Z
Learning: In testcontainers-go, calling `testcontainers.CleanupContainer(t, c)` before checking the error from container creation is safe due to the implementation details of the library. The CleanupContainer function handles nil or partially initialized containers gracefully.
Learnt from: gaby
PR: gofiber/storage#1562
File: neo4j/neo4j.go:221-221
Timestamp: 2025-02-02T23:41:30.921Z
Learning: In the Neo4j storage implementation, the `mapToStruct` function should return an error instead of panicking when JSON unmarshaling fails to prevent server crashes.
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse.go:106-107
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The `IsZero` function for `time.Time` structs in the ClickHouse storage driver was returning false even for zero value `time.Time` structs. As a result, a different verification logic was implemented to avoid bugs.
Learnt from: luk3skyw4lker
PR: gofiber/storage#1342
File: clickhouse/clickhouse.go:106-107
Timestamp: 2024-07-01T15:49:51.308Z
Learning: The `IsZero` function for `time.Time` structs in the ClickHouse storage driver was returning false even for zero value `time.Time` structs. As a result, a different verification logic was implemented to avoid bugs.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: unit (1.24.x, macos-13)
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: unit (1.24.x, ubuntu-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
  • GitHub Check: lint
🔇 Additional comments (4)
converter_test.go (1)

57-67: Benchmark functions are well-implemented.

The benchmark tests provide good performance measurement coverage for the core conversion functions.

util_test.go (3)

88-106: Benchmark functions are well-implemented.

The benchmark tests provide comprehensive performance measurement for key utility functions including tag parsing, zero detection, and pointer conversion.


112-152: Comprehensive zero-value detection tests with good edge case coverage.

The test covers important scenarios including slices, arrays, structs, and custom IsZero methods. The logic is sound and the test cases are well-structured.


154-182: Well-designed panic and map zero-value tests.

The test correctly verifies that isZero panics when called on function values, and properly tests map zero-value detection for nil, empty, and non-empty maps. The panic testing approach using defer and recover is appropriate.

Comment on lines +3 to +6
import (
"reflect"
"testing"
)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add testify/require import for consistent assertion style.

Based on project standards, tests should use testify/require assertions instead of standard Go testing assertions.

 import (
 	"reflect"
 	"testing"
+
+	"github.com/stretchr/testify/require"
 )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import (
"reflect"
"testing"
)
import (
"reflect"
"testing"
"github.com/stretchr/testify/require"
)
🤖 Prompt for AI Agents
In converter_test.go around lines 3 to 6, the test imports only "reflect" and
"testing" but should also import "github.com/stretchr/testify/require" to use
testify/require assertions. Add the require import to the import block and
update the test assertions to use require functions for consistency with project
standards.

Comment on lines +8 to +41
func TestConverters(t *testing.T) {
tests := []struct {
name string
v reflect.Value
want interface{}
valid bool
}{
{"boolTrue", convertBool("true"), true, true},
{"boolOn", convertBool("on"), true, true},
{"boolInvalid", convertBool("x"), nil, false},
{"float32", convertFloat32("1.5"), float32(1.5), true},
{"float32Invalid", convertFloat32("x"), nil, false},
{"float64", convertFloat64("2.5"), 2.5, true},
{"float64Invalid", convertFloat64("x"), nil, false},
{"int", convertInt("10"), int(10), true},
{"intInvalid", convertInt("x"), nil, false},
{"uint", convertUint("5"), uint(5), true},
{"uintInvalid", convertUint("-1"), nil, false},
{"string", convertString("abc"), "abc", true},
}
for _, tt := range tests {
if tt.valid {
if !tt.v.IsValid() {
t.Errorf("%s: expected valid value", tt.name)
continue
}
if got := tt.v.Interface(); got != tt.want {
t.Errorf("%s: expected %v, got %v", tt.name, tt.want, got)
}
} else if tt.v.IsValid() {
t.Errorf("%s: expected invalid value", tt.name)
}
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use testify/require for assertions to maintain consistency with project standards.

The test logic and coverage are excellent, but the assertion style should be updated to match project conventions.

 func TestConverters(t *testing.T) {
 	tests := []struct {
 		name  string
 		v     reflect.Value
 		want  interface{}
 		valid bool
 	}{
 		{"boolTrue", convertBool("true"), true, true},
 		{"boolOn", convertBool("on"), true, true},
 		{"boolInvalid", convertBool("x"), nil, false},
 		{"float32", convertFloat32("1.5"), float32(1.5), true},
 		{"float32Invalid", convertFloat32("x"), nil, false},
 		{"float64", convertFloat64("2.5"), 2.5, true},
 		{"float64Invalid", convertFloat64("x"), nil, false},
 		{"int", convertInt("10"), int(10), true},
 		{"intInvalid", convertInt("x"), nil, false},
 		{"uint", convertUint("5"), uint(5), true},
 		{"uintInvalid", convertUint("-1"), nil, false},
 		{"string", convertString("abc"), "abc", true},
 	}
 	for _, tt := range tests {
-		if tt.valid {
-			if !tt.v.IsValid() {
-				t.Errorf("%s: expected valid value", tt.name)
-				continue
-			}
-			if got := tt.v.Interface(); got != tt.want {
-				t.Errorf("%s: expected %v, got %v", tt.name, tt.want, got)
-			}
-		} else if tt.v.IsValid() {
-			t.Errorf("%s: expected invalid value", tt.name)
-		}
+		t.Run(tt.name, func(t *testing.T) {
+			if tt.valid {
+				require.True(t, tt.v.IsValid(), "expected valid value")
+				require.Equal(t, tt.want, tt.v.Interface())
+			} else {
+				require.False(t, tt.v.IsValid(), "expected invalid value")
+			}
+		})
 	}
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In converter_test.go around lines 8 to 41, the test uses manual if statements
and t.Errorf for assertions, which is inconsistent with the project's use of
testify/require. Replace the manual checks with require functions such as
require.True, require.False, and require.Equal to assert validity and equality,
improving readability and consistency with project standards.

Comment on lines +43 to +55
func TestBuiltinConverters(t *testing.T) {
kinds := []reflect.Kind{
reflect.Bool, reflect.Float32, reflect.Float64,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.String,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
}
for _, k := range kinds {
if builtinConverters[k] == nil {
t.Errorf("missing converter for %v", k)
}
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use testify/require for assertions to maintain consistency with project standards.

 func TestBuiltinConverters(t *testing.T) {
 	kinds := []reflect.Kind{
 		reflect.Bool, reflect.Float32, reflect.Float64,
 		reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
 		reflect.String,
 		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
 	}
 	for _, k := range kinds {
-		if builtinConverters[k] == nil {
-			t.Errorf("missing converter for %v", k)
-		}
+		require.NotNil(t, builtinConverters[k], "missing converter for %v", k)
 	}
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestBuiltinConverters(t *testing.T) {
kinds := []reflect.Kind{
reflect.Bool, reflect.Float32, reflect.Float64,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.String,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
}
for _, k := range kinds {
if builtinConverters[k] == nil {
t.Errorf("missing converter for %v", k)
}
}
}
func TestBuiltinConverters(t *testing.T) {
kinds := []reflect.Kind{
reflect.Bool, reflect.Float32, reflect.Float64,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.String,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
}
for _, k := range kinds {
require.NotNil(t, builtinConverters[k], "missing converter for %v", k)
}
}
🤖 Prompt for AI Agents
In converter_test.go around lines 43 to 55, the test uses t.Errorf for
assertions, but the project standard is to use testify/require for assertions.
Replace the t.Errorf calls with require.NotNil assertions from the
testify/require package to check that builtinConverters[k] is not nil, ensuring
consistent and clearer test failure reporting.

@ReneWerner87 ReneWerner87 merged commit 783299c into main Jul 12, 2025
10 checks passed
@ReneWerner87 ReneWerner87 deleted the codex/2025-07-11-18-06-35 branch July 12, 2025 16:56
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.

2 participants