-
Notifications
You must be signed in to change notification settings - Fork 85
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
feat: [#441] Optimize the HTTP testing process [#2] #708
Conversation
Important Review skippedAuto reviews are limited to specific labels. 🏷️ Labels to auto review (1)
Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughThis pull request introduces several enhancements to the testing package, including the addition of new interfaces and methods for handling JSON and HTTP requests/responses. A new Changes
Possibly related PRs
Suggested labels
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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 (
|
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
⚠️ Performance Alert ⚠️
Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50
.
Benchmark suite | Current: e0d80c7 | Previous: 8b33e6b | Ratio |
---|---|---|---|
Benchmark_Panic |
0.001133 ns/op 0 B/op 0 allocs/op |
0.000695 ns/op 0 B/op 0 allocs/op |
1.63 |
Benchmark_Panic - ns/op |
0.001133 ns/op |
0.000695 ns/op |
1.63 |
This comment was automatically generated by workflow using github-action-benchmark.
There was a problem hiding this 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
🧹 Outside diff range and nitpick comments (8)
contracts/testing/assertable_json.go (1)
3-5
: LGTM! Clean and well-designed interface.The interface follows Go best practices with a focused, single-method design that adheres to interface segregation principles.
Consider adding a doc comment to describe the interface's purpose and usage:
+// AssertableJSON represents a type that can provide its data as a JSON object. +// This interface is typically used in testing scenarios to assert on JSON responses. type AssertableJSON interface { + // Json returns the underlying data as a map representation of a JSON object. Json() map[string]any }testing/assertable_json_string.go (2)
9-12
: Consider adding field documentation.While the field names are concise, adding documentation comments would improve code maintainability by clarifying the purpose of each field.
type AssertableJSONString struct { + // json holds the original JSON string representation json string + // decoded holds the unmarshaled JSON data as a map decoded map[string]any }
27-29
: LGTM! Consider adding compile-time interface check.The implementation is clean and correct. To ensure continued interface compliance, consider adding a compile-time check.
Add this line at the package level:
var _ contractstesting.AssertableJSON = (*AssertableJSONString)(nil)contracts/testing/test_request.go (1)
14-14
: LGTM: Context support follows best practicesThe
WithContext
method follows Go's context propagation patterns, enabling proper request cancellation and timeout management.Consider adding a doc comment explaining the context behavior, e.g.:
// WithContext returns a new TestRequest with the provided context // The context will be used for all subsequent HTTP requestscontracts/testing/test_response.go (1)
39-43
: Consider adding documentation for the boolean variadic parametersThe new assertion methods
AssertDontSee
,AssertSee
, andAssertSeeInOrder
use variadic boolean parameters, but their purpose isn't immediately clear. Consider adding interface documentation to explain:
- What the boolean parameters control (case sensitivity?)
- The expected behavior when no boolean flags are provided
- The order of precedence if multiple flags are given
Example documentation:
// AssertSee checks if the response contains all given strings. // Optional boolean parameters control case sensitivity (default: true).testing/test_request.go (2)
57-60
: Consider adding documentation for the WithContext method.The implementation is correct and follows the builder pattern consistently. Consider adding a doc comment to describe the method's purpose and any context-specific considerations.
Add documentation:
+// WithContext sets the context for subsequent HTTP requests. +// This context will be used for all requests made through this TestRequest instance. func (r *TestRequest) WithContext(ctx context.Context) contractstesting.TestRequest {
66-88
: Add tests for new HTTP methods and context handling.Please ensure comprehensive test coverage for:
- Context propagation through the request chain
- All new HTTP methods (POST, PUT, PATCH, DELETE, HEAD, OPTIONS)
- Error cases for invalid requests
Would you like me to help create test cases for these scenarios?
testing/test_response.go (1)
246-249
: Consider clarifying theescaped
parameter usage in assertion methodsIn the methods
AssertDontSee
,AssertSee
, andAssertSeeInOrder
, theescaped
parameter determines whether to escape HTML characters in the values before comparison. The current implementation defaultsshouldEscape
totrue
whenescaped
is not provided, which might be counterintuitive. Consider:
- Renaming the parameter to
escape
to reflect its action more clearly.- Adjusting the default behavior to
false
to align with the principle of least surprise.This change would enhance the clarity and intuitiveness of the API for users.
Also applies to: 267-270, 288-291
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (3)
mocks/testing/AssertableJSON.go
is excluded by!mocks/**
mocks/testing/TestRequest.go
is excluded by!mocks/**
mocks/testing/TestResponse.go
is excluded by!mocks/**
📒 Files selected for processing (6)
contracts/testing/assertable_json.go
(1 hunks)contracts/testing/test_request.go
(1 hunks)contracts/testing/test_response.go
(2 hunks)testing/assertable_json_string.go
(1 hunks)testing/test_request.go
(3 hunks)testing/test_response.go
(4 hunks)
🔇 Additional comments (16)
contracts/testing/assertable_json.go (1)
4-4
: 🛠️ Refactor suggestion
Consider adding error handling to the Json method.
Since JSON operations can fail (e.g., parsing errors, invalid data), it might be beneficial to include error handling in the interface contract.
Consider modifying the method signature to include an error return:
- Json() map[string]any
+ Json() (map[string]any, error)
Let's check if other JSON-related operations in the codebase handle errors:
testing/assertable_json_string.go (2)
1-7
: LGTM! Clean package structure and imports.
The package name and imports are well-organized, with appropriate use of aliasing for the testing contract.
1-29
: Verify if similar functionality exists in testing libraries.
While the implementation is solid, it's worth checking if this functionality already exists in commonly used Go testing libraries to avoid duplication.
contracts/testing/test_request.go (1)
3-6
: LGTM: Clean import additions
The new imports are appropriate for the enhanced HTTP testing functionality.
contracts/testing/test_response.go (3)
4-5
: LGTM: Status check methods follow standard HTTP conventions
The new methods IsSuccessful()
and IsServerError()
are well-named and follow HTTP status code conventions for success (2xx) and server errors (5xx).
34-34
: LGTM: Simplified method signatures improve readability
The removal of parameter names in these method signatures follows Go interface best practices, making the interface more concise while maintaining clarity.
Also applies to: 36-38
6-7
: Verify error handling in Content() and Json() implementations
The new content retrieval methods look good, but their implementations should handle various edge cases:
- Empty response bodies
- Invalid JSON formatting
- Character encoding issues
✅ Verification successful
Error handling is properly implemented
The implementations handle the key edge cases appropriately:
- Empty responses: The
getContent()
method properly reads the response body usingio.ReadAll
and returns any errors - Invalid JSON: The
Json()
method usesjson.Unmarshal
throughNewAssertableJSONString
which returns an error for malformed JSON - Character encoding: Content is properly handled as strings and bytes throughout the chain
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for the implementation of these methods to verify error handling
ast-grep --pattern 'func ($receiver $_) Content() (string, error) {
$$$
}'
ast-grep --pattern 'func ($receiver $_) Json() (map[string]any, error) {
$$$
}'
Length of output: 162
Script:
#!/bin/bash
# Let's try with ripgrep to find these method implementations
rg -U "func.*Content\(\).*\(string, error\)" -A 10
rg -U "func.*Json\(\).*\(map\[string\]any, error\)" -A 10
Length of output: 2953
Script:
#!/bin/bash
# Let's check the NewAssertableJSONString implementation for JSON validation
rg -U "func NewAssertableJSONString" -A 10
# Also check if there's any content validation in getContent
rg -U "r.content = " -A 5
Length of output: 1053
testing/test_request.go (2)
4-5
: LGTM! Well-structured context integration.
The addition of context support is implemented cleanly with proper initialization using context.Background()
as the default value.
Also applies to: 18-18, 26-26
90-91
: Verify error handling for nil context.
The implementation looks good, but let's ensure proper error handling when the context is nil.
testing/test_response.go (7)
28-40
: Well-implemented Json
method for parsing response content
The Json
method correctly retrieves the response content and parses it into a JSON map with proper error handling. This enhances the usability of the TestResponseImpl
by providing a straightforward way to work with JSON responses.
42-45
: Accurate implementation of IsSuccessful
method
The IsSuccessful
method properly checks if the response status code indicates a successful response (status code 200-299). This offers a convenient way to validate successful HTTP responses in tests.
47-50
: Correct IsServerError
method to detect server errors
The IsServerError
method accurately identifies server error responses (status code 500-599), aiding in asserting that the server responded with an error as expected.
52-54
: Proper Content
method to retrieve response content
The Content
method effectively returns the response content by invoking getContent
, allowing testers to access the raw response body for further assertions.
82-84
: Appropriate content assertion in AssertNoContent
The added assertions in AssertNoContent
correctly verify that the response content is empty, ensuring the response complies with the expected no-content status.
230-234
: AssertSuccessful
method correctly asserts successful responses
The AssertSuccessful
method utilizes IsSuccessful
to confirm that the response status code indicates success, streamlining success assertions in tests.
236-240
: AssertServerError
method properly asserts server error responses
The AssertServerError
method checks for server error status codes using IsServerError
, providing a clear way to assert server errors in the response.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #708 +/- ##
==========================================
- Coverage 69.75% 69.60% -0.15%
==========================================
Files 194 195 +1
Lines 15108 15225 +117
==========================================
+ Hits 10539 10598 +59
- Misses 3999 4055 +56
- Partials 570 572 +2 ☔ View full report in Codecov by Sentry. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Great PR 👍 just one question.
Get(uri string) (TestResponse, error) | ||
Post(uri string, body io.Reader) (TestResponse, error) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure, we can provide a interface to write body. (May be in next PR?)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can optimize it in another PR if you want.
📑 Description
RelatedTo goravel/goravel#441
Summary by CodeRabbit
New Features
AssertableJSON
for flexible JSON representation.TestRequest
interface with methods for various HTTP request types and context management.TestResponse
interface with new methods for response verification and content handling.AssertableJSONString
type for handling JSON strings and decoding.Bug Fixes
AssertableJSONString
.Documentation
TestResponse
.✅ Checks