Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🩹 fix: make SetValWithStruct set zero values and support more types #3167 #3227

Merged
merged 7 commits into from
Dec 13, 2024

Conversation

ksw2000
Copy link
Contributor

@ksw2000 ksw2000 commented Dec 2, 2024

Description

According to issue #3167, the SetValWithStruct function originally set only non-zero values, but it also set zero values in slices. After discussion, we have changed the behavior of SetValWithStruct to set both non-zero and zero values, starting from Fiber v3.

Additionally, in this PR, I have made SetValWithStruct more general by supporting more types, including uint, complex, and others.

Since I did not find any statements in the documentation describing that SetValWithStruct about handling zero values, I did not update the documentation. If anyone finds any, I will make the necessary changes.

Fixes #3167

Changes introduced

List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide.

  • Benchmarks: Describe any performance benchmarks and improvements related to the changes.
  • Documentation Update: Detail the updates made to the documentation and links to the changed files.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes.
  • API Alignment with Express: Explain how the changes align with the Express API.
  • API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

Please delete options that are not relevant.

  • Enhancement (improvement to existing features and functionality)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

Walkthrough

The changes in this pull request modify the SetValWithStruct function in client/request.go to enhance its ability to handle various data types, including unsigned integers and complex numbers, while allowing zero values to be processed. The associated tests in client/request_test.go have been updated to reflect these changes, adding new fields and adjusting assertions to ensure comprehensive coverage of the updated functionality.

Changes

File Change Summary
client/request.go Updated SetValWithStruct function comment, modified internal logic to handle unsigned integers and complex numbers, refined boolean handling, removed zero value checks, and changed variable name for consistency.
client/request_test.go Expanded args struct with new fields (TUint, TComplex), updated test cases for new fields, removed zero value test, and clarified comments.

Assessment against linked issues

Objective Addressed Explanation
SetValWithStruct should skip 0 in the int slice (Issue #3167) The changes allow zero values to be processed, contrary to the expected behavior.

🐰 In the meadow, I hop and play,
With structs and fields, I find my way.
Zero values now, they come along,
In the world of types, we all belong!
Let's set the values, both big and small,
In this joyful code, we embrace them all! 🌼


📜 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 defa061 and d629b5f.

📒 Files selected for processing (2)
  • client/request.go (2 hunks)
  • client/request_test.go (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/request.go
🔇 Additional comments (4)
client/request_test.go (4)

1533-1544: LGTM: Test struct additions properly cover new types

The additions of TUint and TComplex fields to the test struct appropriately expand type coverage for testing the enhanced SetValWithStruct functionality.


1555-1570: LGTM: Test assertions properly verify new type support

The test assertions for TUint and TComplex fields properly verify the new type support, with appropriate value checking.


1589-1597: LGTM: Test now verifies zero value handling

The addition of test assertions for zero values in TIntSlice properly verifies the fix for the zero value skipping bug.


Line range hint 1684-1752: LGTM: Benchmark tests maintain parity with regular tests

The benchmark tests have been appropriately updated to maintain parity with the regular tests, ensuring performance characteristics are measured for all new functionality.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Experiment)
  • @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 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.

@ksw2000 ksw2000 marked this pull request as ready for review December 2, 2024 07:04
@ksw2000 ksw2000 requested a review from a team as a code owner December 2, 2024 07:04
@ksw2000 ksw2000 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team December 2, 2024 07:04
Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
client/request_test.go (1)

Line range hint 1468-1515: Exclude unsupported types from benchmark test

The benchmark test includes function and map types, which are not supported for serialization into parameters. Removing these types will make the benchmark more accurate and focused on measuring performance with valid data types.

Apply this diff to modify the benchmark test:

 type args struct { //nolint:govet // Aligning the struct fields is not necessary.
     TString   string
     TSlice    []string
     TIntSlice []int `param:"int_slice"`
     unexport  int
     TInt      int
     TUint     uint
     TFloat    float64
     TComplex  complex128
     TBool     bool
-    TFunc     func()
-    TMap      map[int]int
 }

 b.Run("the struct should be applied", func(b *testing.B) {
     ...
     for i := 0; i < b.N; i++ {
         SetValWithStruct(p, "param", args{
             unexport:  5,
             TInt:      5,
             TUint:     5,
             TString:   "string",
             TFloat:    3.1,
             TComplex:  3 + 4i,
             TBool:     false,
             TSlice:    []string{"foo", "bar"},
             TIntSlice: []int{0, 1, 2},
-            TFunc:     func() {},
-            TMap:      map[int]int{1: 2},
         })
     }
     ...
 })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9a2ceb7 and fdbc653.

📒 Files selected for processing (2)
  • client/request.go (4 hunks)
  • client/request_test.go (4 hunks)

client/request.go Outdated Show resolved Hide resolved
client/request_test.go Outdated Show resolved Hide resolved
client/request_test.go Outdated Show resolved Hide resolved
Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (2)
client/request_test.go (2)

1382-1389: Improve test readability for zero value checks

The zero value test case is buried within multiple similar test blocks. Consider extracting zero value tests into a dedicated test case for better visibility and documentation of the fixed behavior.

+	t.Run("zero values should be set", func(t *testing.T) {
+		t.Parallel()
+		p := &QueryParam{
+			Args: fasthttp.AcquireArgs(),
+		}
+
+		SetValWithStruct(p, "param", args{
+			TInt:      0,
+			TUint:     0,
+			TBool:     false,
+			TIntSlice: []int{0},
+		})
+
+		require.Equal(t, []byte("0"), p.Peek("TInt"))
+		require.Equal(t, []byte("0"), p.Peek("TUint"))
+		require.Equal(t, []byte("false"), p.Peek("TBool"))
+		require.Equal(t, []byte("0"), p.PeekMulti("int_slice")[0])
+	})

Line range hint 1477-1524: Streamline benchmarks to focus on supported types

The benchmark includes unsupported types (TFunc, TMap) which may skew performance metrics. Consider focusing benchmarks on the core supported types to get more accurate performance measurements.

 type args struct {
     TString   string
     TSlice    []string
     TIntSlice []int `param:"int_slice"`
     unexport  int
     TInt      int
     TUint     uint
     TFloat    float64
     TComplex  complex128
     TBool     bool
-    TFunc     func()
-    TMap      map[int]int
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fdbc653 and 4215e0f.

📒 Files selected for processing (1)
  • client/request_test.go (6 hunks)
🔇 Additional comments (1)
client/request_test.go (1)

1320-1332: Remove unsupported types from test struct

Including function types (TFunc) and map types (TMap) in the test struct args is not meaningful, as these types are not typically serialized into parameters.

@ReneWerner87 ReneWerner87 added the v3 label Dec 2, 2024
@ReneWerner87 ReneWerner87 added this to the v3 milestone Dec 2, 2024
Copy link
Contributor

@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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4215e0f and 5cc62be.

📒 Files selected for processing (1)
  • client/request.go (4 hunks)
🔇 Additional comments (4)
client/request.go (4)

956-957: Support for unsigned integer types added

The addition correctly handles unsigned integer types using strconv.FormatUint, ensuring that uint, uint8, uint16, uint32, uint64, and uintptr are properly converted to strings.


958-959: Support for complex number types added

The inclusion of complex number types (complex64, complex128) and their handling using strconv.FormatComplex is correctly implemented. This allows complex numbers to be added as parameters.


963-964: Boolean false values are now properly handled

The addition of the else branch ensures that when a boolean value is false, it is explicitly added as "false" to the parameters. This change improves the consistency of boolean value handling.


975-977: ⚠️ Potential issue

Avoid adding unsupported types like functions and maps to parameters

Including function types (func) and map types (map) as parameters may lead to unintended behavior or serialization issues. Functions cannot be serialized, and maps may not serialize in a predictable way suitable for query parameters or form data. Excluding these types will ensure that only supported and serializable types are added.

Apply this diff to exclude functions and maps from being added:

 default:
+    if val.Kind() == reflect.Func || val.Kind() == reflect.Map {
+        return
+    }
     if val.CanInterface() {
         p.Add(name, fmt.Sprintf("%#v", val.Interface()))
     }

client/request.go Outdated Show resolved Hide resolved
Copy link

codecov bot commented Dec 4, 2024

Codecov Report

Attention: Patch coverage is 90.00000% with 1 line in your changes missing coverage. Please review.

Project coverage is 82.73%. Comparing base (a63bd34) to head (d629b5f).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
client/request.go 90.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3227      +/-   ##
==========================================
+ Coverage   82.69%   82.73%   +0.04%     
==========================================
  Files         115      115              
  Lines       11377    11383       +6     
==========================================
+ Hits         9408     9418      +10     
+ Misses       1561     1558       -3     
+ Partials      408      407       -1     
Flag Coverage Δ
unittests 82.73% <90.00%> (+0.04%) ⬆️

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.

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (1)
client/request.go (1)

932-939: Update documentation to reflect zero value handling

The documentation should explicitly mention that the function now sets both zero and non-zero values, as this is a significant behavioral change mentioned in the PR objectives.

Add a note like:

 // SetValWithStruct stores the fields of `v` into `p`.
 // `tagName` specifies the key used to store into `p`. If not specified,
 // the field name is used by default.
 // `v` is a struct or a pointer to a struct containing some data.
+// All field values, including zero values, are stored.
 // Fields in `v` should be string, int, int8, int16, int32, int64, uint,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fecef5e and defa061.

📒 Files selected for processing (2)
  • client/request.go (2 hunks)
  • client/request_test.go (6 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
client/request.go

[warning] 977-977: client/request.go#L977
Added line #L977 was not covered by tests

🔇 Additional comments (7)
client/request.go (3)

958-963: LGTM! Support for additional types added

The implementation correctly adds support for unsigned integers and complex numbers as specified in the PR objectives.


967-968: LGTM! Explicit handling of boolean false values

The implementation now explicitly sets "false" for boolean values, which aligns with the PR objective of handling zero values.


977-977: ⚠️ Potential issue

Add test coverage for default case

The default case in the switch statement is not covered by tests.

Consider adding test cases that exercise the default case by including unsupported types in the test struct.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 977-977: client/request.go#L977
Added line #L977 was not covered by tests

client/request_test.go (4)

1320-1331: LGTM! Test struct updated with new types

The test struct has been properly updated to include the new supported types (uint and complex128).


1342-1348: LGTM! Comprehensive test values

The test values appropriately cover:

  • New types (uint and complex)
  • Zero values in slices (TIntSlice starting with 0)
  • Boolean false values

1376-1384: LGTM! Zero value assertions added

The test now properly verifies that zero values (0) in slices are correctly handled.


1353-1357: LGTM! New type assertions added

The test properly verifies the handling of new types:

  • uint values
  • complex number formatting

@ReneWerner87
Copy link
Member

benchmark errors are ok
more allocations have been added to the bench for the function, as more test data is being tested

the other errors are caused by a non-updated bench which was also changed in master as we switched from go 1.22 to 1.23

@ReneWerner87 ReneWerner87 merged commit 1134e1f into gofiber:main Dec 13, 2024
13 of 14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: client.SetValWithStruct set zero value if the field is slice
4 participants