♻️ refactor: Make genericParseType return error#3473
♻️ refactor: Make genericParseType return error#3473ReneWerner87 merged 8 commits intogofiber:mainfrom
Conversation
WalkthroughThe changes refactor generic parsing logic to return errors explicitly, update the handling of default values in parsing functions, and enhance test coverage and benchmarking. The parsing functions now return errors on failure, and default values are used only when provided. Tests are consolidated and benchmarks are added for comprehensive type coverage. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller
participant Ctx
participant Parser
Caller->>Ctx: GetReqHeader/Params/Query(key, defaultValue)
Ctx->>Parser: genericParseType(str)
Parser-->>Ctx: value, error
alt error and defaultValue provided
Ctx-->>Caller: defaultValue
else no error
Ctx-->>Caller: value
end
Assessment against linked issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🧰 Additional context used🧬 Code Graph Analysis (1)helpers_test.go (1)
⏰ Context from checks skipped due to timeout of 90000ms (6)
🔇 Additional comments (3)
✨ Finishing Touches
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. 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## main #3473 +/- ##
==========================================
+ Coverage 84.32% 84.47% +0.15%
==========================================
Files 120 120
Lines 12157 12194 +37
==========================================
+ Hits 10251 10301 +50
+ Misses 1478 1467 -11
+ Partials 428 426 -2
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
ctx.go (1)
1111-1129: Consistent implementation with same logical issue.The
Paramsfunction follows the same error handling pattern asGetReqHeader, which is good for consistency. The same comment/implementation mismatch exists here regarding unsupported types.The unsupported type handling issue noted in the
helpers.goreview applies here as well.🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 1127-1128: ctx.go#L1127-L1128
Added lines #L1127 - L1128 were not covered by tests
🧹 Nitpick comments (1)
ctx.go (1)
1252-1256: Complete the error handling pattern consistently.The
Queryfunction correctly implements the same error handling pattern as the other two functions, maintaining consistency across the API.Minor test coverage note:
Static analysis shows lines 1127-1128 lack test coverage. Consider adding tests that trigger parsing errors with default values provided.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
ctx.go(4 hunks)ctx_test.go(4 hunks)helpers.go(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
ctx_test.go (1)
helpers.go (1)
GenericTypeInteger(861-863)
🪛 GitHub Check: codecov/patch
ctx.go
[warning] 1127-1128: ctx.go#L1127-L1128
Added lines #L1127 - L1128 were not covered by tests
helpers.go
[warning] 767-768: helpers.go#L767-L768
Added lines #L767 - L768 were not covered by tests
[warning] 791-792: helpers.go#L791-L792
Added lines #L791 - L792 were not covered by tests
[warning] 797-798: helpers.go#L797-L798
Added lines #L797 - L798 were not covered by tests
[warning] 821-822: helpers.go#L821-L822
Added lines #L821 - L822 were not covered by tests
[warning] 827-828: helpers.go#L827-L828
Added lines #L827 - L828 were not covered by tests
[warning] 833-834: helpers.go#L833-L834
Added lines #L833 - L834 were not covered by tests
[warning] 839-840: helpers.go#L839-L840
Added lines #L839 - L840 were not covered by tests
[warning] 853-853: helpers.go#L853
Added line #L853 was not covered by tests
🔇 Additional comments (9)
helpers.go (2)
756-759: LGTM! Well-defined error constants.The new error variables provide clear, specific error messages for empty parsing results, which improves error handling clarity.
761-855:Details
❌ Incorrect review comment
Critical bug in unsupported type handling logic.
The refactored function has excellent error handling for supported types, but there's a logical inconsistency for unsupported types:
- Line 853: For unsupported types, the function returns
(zero_value, nil)- no error is returned- Consumer functions (in ctx.go): Only use default values when
err != nil AND len(defaultValue) > 0- Issue: For unsupported types, since no error is returned, the zero value will always be returned even when a default value is provided
This contradicts the documented behavior in the comments added to ctx.go (lines 647-648, 1111-1112) which state that unsupported types should return the default value if provided.
Fix for unsupported type handling:
default: - return v, nil + return v, errors.New("unsupported generic type")Address test coverage gaps:
The static analysis indicates several error handling paths lack test coverage. Consider adding tests for:
- Integer overflow scenarios (lines 767-768, 791-792, etc.)
- Invalid boolean values (lines 839-840)
- Unsupported types (line 853)
Would you like me to generate comprehensive test cases to improve coverage of these error handling paths?
🏁 Script executed:
#!/bin/bash set -e # Locate usages of genericParseType across Go files to see how its return values are handled rg -n "genericParseType" -C5 --glob "*.go" echo "----" # Locate occurrences of defaultValue handling to verify the conditional logic around defaults rg -n "defaultValue" -C5 --glob "*.go"Length of output: 37058
🏁 Script executed:
#!/bin/bash set -e # Find definition of GenericType constraint rg -n "type GenericType" -C5 --glob "*.go"Length of output: 859
No issue: unsupported branch is unreachable under the GenericType constraint
The
defaultcase ingenericParseTypeonly ever applies if you instantiate the function with a type outside theGenericTypeunion. But Go’s type‐list constraints (GenericType=int|int8|…|float64|bool|string|[]byte) prevent you from callinggenericParseTypewith any other type at compile time. As a result:
- The
defaultpath (return v, nil) is never taken at runtime.- Consumers correctly get a non-
nilerror only when parsing fails on supported types, so the default-value logic inctx.goworks as intended.No change or additional test is needed for “unsupported types.” Please disregard the suggested
errors.New("unsupported generic type")patch.Likely an incorrect or invalid review comment.
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 767-768: helpers.go#L767-L768
Added lines #L767 - L768 were not covered by tests
[warning] 791-792: helpers.go#L791-L792
Added lines #L791 - L792 were not covered by tests
[warning] 797-798: helpers.go#L797-L798
Added lines #L797 - L798 were not covered by tests
[warning] 821-822: helpers.go#L821-L822
Added lines #L821 - L822 were not covered by tests
[warning] 827-828: helpers.go#L827-L828
Added lines #L827 - L828 were not covered by tests
[warning] 833-834: helpers.go#L833-L834
Added lines #L833 - L834 were not covered by tests
[warning] 839-840: helpers.go#L839-L840
Added lines #L839 - L840 were not covered by tests
[warning] 853-853: helpers.go#L853
Added line #L853 was not covered by testsctx.go (1)
647-654: Error handling pattern is correct, but comment doesn't match implementation.The error handling logic correctly returns the default value when parsing fails AND a default is provided. However, the comment states that unsupported types return the default value, but the current implementation in
genericParseTypedoesn't return an error for unsupported types, so the default won't be used.This inconsistency should be resolved by fixing the unsupported type handling in
helpers.goas noted in the previous comment.ctx_test.go (6)
31-31: Good use ofunsafepackage for determining native type sizes.The addition of the
unsafepackage is appropriate here as it's used to dynamically determine the bit sizes of nativeintanduinttypes in the tests, making them portable across different architectures.
5255-5380: Excellent refactoring of integer parsing tests!The consolidated test structure with systematic coverage of all integer types and their boundaries is a significant improvement. The use of subtests and proper error checking for out-of-range values enhances test reliability.
5383-5493: Well-structured unsigned integer parsing tests.The tests properly cover all unsigned integer types with appropriate boundary testing and error handling for overflow conditions.
5496-5538: Proper implementation of float parsing tests with epsilon comparison.Good use of
require.InEpsilonfor floating-point comparisons, which correctly handles precision issues.
5541-5580: Correct implementation of byte parsing tests with explicit error handling.The tests properly validate the new error behavior where empty strings return
errParsedEmptyBytes, aligning with the PR's objective of explicit error handling.
5639-5803: Excellent benchmark coverage with helper functions.The benchmarks are comprehensive and well-structured. The use of helper functions
benchGenericParseTypeIntandbenchGenericParseTypeUInteffectively reduces code duplication while maintaining thorough coverage of all type boundaries.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
helpers.go (1)
762-856: Excellent refactoring with comprehensive type coverage.The generic parsing function successfully consolidates parsing logic with explicit error handling. The type switch approach provides clean, maintainable code with consistent error handling across all supported types.
One design consideration: The function returns errors for empty strings when parsing to
stringand[]bytetypes (lines 844-846, 849-851). Consider whether empty strings should be treated as valid inputs that return empty results rather than errors, depending on your application's requirements.🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 768-769: helpers.go#L768-L769
Added lines #L768 - L769 were not covered by tests
[warning] 792-793: helpers.go#L792-L793
Added lines #L792 - L793 were not covered by tests
[warning] 798-799: helpers.go#L798-L799
Added lines #L798 - L799 were not covered by tests
[warning] 822-823: helpers.go#L822-L823
Added lines #L822 - L823 were not covered by tests
[warning] 828-829: helpers.go#L828-L829
Added lines #L828 - L829 were not covered by tests
[warning] 834-835: helpers.go#L834-L835
Added lines #L834 - L835 were not covered by tests
[warning] 840-841: helpers.go#L840-L841
Added lines #L840 - L841 were not covered by tests
[warning] 854-854: helpers.go#L854
Added line #L854 was not covered by tests
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
helpers.go(1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
helpers.go
[warning] 768-769: helpers.go#L768-L769
Added lines #L768 - L769 were not covered by tests
[warning] 792-793: helpers.go#L792-L793
Added lines #L792 - L793 were not covered by tests
[warning] 798-799: helpers.go#L798-L799
Added lines #L798 - L799 were not covered by tests
[warning] 822-823: helpers.go#L822-L823
Added lines #L822 - L823 were not covered by tests
[warning] 828-829: helpers.go#L828-L829
Added lines #L828 - L829 were not covered by tests
[warning] 834-835: helpers.go#L834-L835
Added lines #L834 - L835 were not covered by tests
[warning] 840-841: helpers.go#L840-L841
Added lines #L840 - L841 were not covered by tests
[warning] 854-854: helpers.go#L854
Added line #L854 was not covered by tests
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: unit (1.23.x, windows-latest)
- GitHub Check: unit (1.24.x, macos-latest)
- GitHub Check: unit (1.24.x, windows-latest)
- GitHub Check: unit (1.24.x, macos-13)
- GitHub Check: repeated
- GitHub Check: Compare
🔇 Additional comments (2)
helpers.go (2)
756-760: LGTM! Well-defined error variables for explicit error handling.The error variables provide clear, descriptive messages for different parsing failure scenarios, which aligns well with the refactoring goal of making error handling more explicit.
766-855: Solid implementation with room for improved test coverage.The type-specific parsing logic is well-implemented:
- Correct use of
strconvfunctions with appropriate bit sizes- Consistent error wrapping with descriptive messages
- Proper type assertions for generic return values
However, static analysis indicates several error handling paths lack test coverage. Consider adding tests for these scenarios to ensure robust error handling.
Would you like me to help generate comprehensive test cases for the error handling paths to improve coverage?
🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 768-769: helpers.go#L768-L769
Added lines #L768 - L769 were not covered by tests
[warning] 792-793: helpers.go#L792-L793
Added lines #L792 - L793 were not covered by tests
[warning] 798-799: helpers.go#L798-L799
Added lines #L798 - L799 were not covered by tests
[warning] 822-823: helpers.go#L822-L823
Added lines #L822 - L823 were not covered by tests
[warning] 828-829: helpers.go#L828-L829
Added lines #L828 - L829 were not covered by tests
[warning] 834-835: helpers.go#L834-L835
Added lines #L834 - L835 were not covered by tests
[warning] 840-841: helpers.go#L840-L841
Added lines #L840 - L841 were not covered by tests
[warning] 854-854: helpers.go#L854
Added line #L854 was not covered by tests
There was a problem hiding this comment.
Pull Request Overview
Refactors the parsing utility to return explicit errors and streamlines context methods to handle defaults cleanly.
- Converts
genericParseTypeto return(V, error)with distinct error values - Updates
GetReqHeader,Params, andQueryto apply provided defaults on parse errors - Removes obsolete helpers (
genericParseDefault,assertValueType, and related functions)
Reviewed Changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| helpers.go | Refactored genericParseType to return errors, removed legacy parsing code |
| ctx.go | Updated generic context getters to unwrap errors and apply default values |
Comments suppressed due to low confidence (1)
helpers.go:757
- [nitpick] Error variable names mix past tense (
Parsed) with context; consider renaming toerrEmptyStringorerrEmptyResultStringfor clarity and consistency.
errParsedEmptyString = errors.New("parsed result is empty string")
gaby
left a comment
There was a problem hiding this comment.
LGTM, we just expand the tests a bit to cover all the missing lines from coverage report.
|
@ksw2000 can you check the missing coverage and add test for this |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
helpers_test.go (1)
740-745: Use Go naming conventions for test names.The test names use underscores which is not idiomatic Go. Consider using camelCase for consistency with Go conventions.
- testGenericTypeInt[int8](t, "test_genericParseTypeInt8s", ints) - testGenericTypeInt[int16](t, "test_genericParseTypeInt16s", ints) - testGenericTypeInt[int32](t, "test_genericParseTypeInt32s", ints) - testGenericTypeInt[int64](t, "test_genericParseTypeInt64s", ints) - testGenericTypeInt[int](t, "test_genericParseTypeInts", ints) + testGenericTypeInt[int8](t, "testGenericParseTypeInt8s", ints) + testGenericTypeInt[int16](t, "testGenericParseTypeInt16s", ints) + testGenericTypeInt[int32](t, "testGenericParseTypeInt32s", ints) + testGenericTypeInt[int64](t, "testGenericParseTypeInt64s", ints) + testGenericTypeInt[int](t, "testGenericParseTypeInts", ints)ctx_test.go (1)
5325-5337: Consider reducing test execution time.While the test logic is correct, sleeping for 2 seconds makes this test slower than necessary. Consider reducing the sleep duration or using a more controlled timeout mechanism.
- time.Sleep(2 * time.Second) + time.Sleep(100 * time.Millisecond)And adjust the test timeout accordingly in the
app.Test()call if needed.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
ctx_test.go(2 hunks)helpers_test.go(2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
helpers_test.go (1)
helpers.go (2)
GenericTypeInteger(862-864)GenericType(858-860)
⏰ Context from checks skipped due to timeout of 90000ms (5)
- GitHub Check: unit (1.24.x, windows-latest)
- GitHub Check: unit (1.24.x, macos-13)
- GitHub Check: unit (1.23.x, windows-latest)
- GitHub Check: Compare
- GitHub Check: repeated
🔇 Additional comments (10)
helpers_test.go (4)
8-9: LGTM! Required imports for new tests.The added imports are necessary for the new generic parsing tests -
mathfor type constants,strconvfor number formatting, andunsafefor sizeof operations.Also applies to: 13-13
673-1315: Excellent test coverage for generic parsing!The test implementation is comprehensive and well-structured:
- Covers all supported types (integers, floats, bytes, strings, booleans)
- Tests boundary values and error cases
- Includes both unit tests and benchmarks
- Uses generics effectively to reduce code duplication
The test design follows good practices with clear separation between test data and test logic.
910-910:Details
❌ Incorrect review comment
Missing errParsedEmptyBytes error definition.
The tests use
errParsedEmptyBytesbut it's not defined in this file. This error should be imported or defined.Also applies to: 1232-1232
🏁 Script executed:
#!/bin/bash # Search for errParsedEmptyBytes definition rg "errParsedEmptyBytes\s*=" --type goLength of output: 118
errParsedEmptyBytes is already defined in helpers.go. The tests in helpers_test.go can access this variable without additional imports or definitions, so no changes are necessary.
Likely an incorrect or invalid review comment.
870-870:Details
❌ Incorrect review comment
Missing epsilon constant definition.
The tests use
epsilonfor float comparisons, but it's not defined in this file. This will cause a compilation error.Also applies to: 880-880
🏁 Script executed:
#!/bin/bash # Search for epsilon definition in the codebase rg -A 2 "epsilon\s*=" --type goLength of output: 125
🏁 Script executed:
#!/bin/bash # Check package declarations in the test files to ensure epsilon is in scope rg '^package ' -n helpers_test.go ctx_test.goLength of output: 107
No missing epsilon definition—tests share the same package
The
epsilonconstant is defined inctx_test.go(const epsilon = 0.001) and, since bothctx_test.goandhelpers_test.godeclarepackage fiber, the constant is in scope. There’s no compilation error.Likely an incorrect or invalid review comment.
ctx_test.go (6)
2496-2496: LGTM! Good test coverage for default value behavior.This addition properly tests that the generic
Paramsfunction correctly returns a default value when an optional parameter is not provided, which aligns with the refactoring to improve error handling mentioned in the PR objectives.
5254-5280: LGTM! Well-structured test for Drop() functionality.The test correctly verifies that:
Drop()prevents any response from being sent (verified byErrTestGotEmptyResponse)- Normal handlers without
Drop()still work as expected- Proper error checking and assertions are used
5283-5304: LGTM! Good test coverage for Drop() with middleware interaction.This test properly verifies that
Drop()works correctly even when middleware attempts to set headers afterc.Next(), ensuring the connection is still dropped as expected.
5307-5322: LGTM! Proper test for End() functionality.The test correctly verifies that
End()allows content to be sent before ending the response, which is the expected behavior for this lifecycle control method.
5340-5360: LGTM! Good test for complex middleware interaction.This test properly verifies the interaction between
End()and middleware that callsDrop()afterc.Next(), ensuring thatEnd()takes precedence and the response is still sent.
5363-5381: LGTM! Comprehensive test for Drop() and End() interaction.This test correctly verifies that when
Drop()is called first, subsequentEnd()calls don't change the behavior - the connection remains dropped. The test structure with middleware is well-designed.
|
Hi @ReneWerner87, I fixed the cover test problem and moved the code about generic parsing test into |
Description
The original
genericParseTypefunction returned a default value when errors occurred, which made it unclear whether a parsing error had actually happened. I've refactoredgenericParseTypeto explicitly return an error, improving error handling clarity.Furthermore,
ctx_test.gocontained excessive redundant code related to testinggenericParseType. I've streamlined these tests to improve the overall clarity and cleanliness of the codebase.Resolves #3393
Type of change
Checklist
Before you submit your pull request, please make sure you meet these requirements:
/docs/directory for Fiber's documentation.