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: [#589] Context in PrepareForValidation always nil #151

Merged
merged 1 commit into from
Feb 28, 2025
Merged

Conversation

hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Feb 28, 2025

📑 Description

Closes goravel/goravel#589

Summary by CodeRabbit

  • Enhancements

    • Improved request validation by incorporating context data to deliver better error responses.
    • Updated server startup logging to display routes more clearly with simplified formatting.
  • Dependency Updates

    • Upgraded several dependencies and removed obsolete ones for enhanced performance and stability.
  • Tests

    • Introduced new tests verifying context-based validation, ensuring consistent HTTP response behavior.

✅ Checks

  • Added test cases for my code

@Copilot Copilot bot review requested due to automatic review settings February 28, 2025 08:23
@hwbrzzl hwbrzzl requested a review from a team as a code owner February 28, 2025 08:23
Copy link

coderabbitai bot commented Feb 28, 2025

Walkthrough

The pull request updates how request validation is handled by passing the context (r.ctx) to the validation function in the ContextRequest struct. A new test for context-based validation has been added. Additionally, the dependencies in go.mod have been updated with new versions and some removed, and the logging in routing has been modified by replacing the termlink package with the str package. Minor changes in the test file include renaming an import alias and adjusting validation logic.

Changes

File(s) Change Summary
context_request.go
context_request_test.go
Updated the ValidateRequest method to pass r.ctx to validation.PrepareForValidation and added the test TestValidateRequest_PrepareForValidationWithContext to ensure context-based validation works correctly.
go.mod Updated dependency versions for packages such as goravel/framework, fsnotify, mimetype, go-toml, locafero, grpc, protobuf, net, and sys; removed dependencies like termlink, cloud.google.com/go packages, and gopkg.in/yaml.v2.
route.go
route_test.go
Replaced the termlink package with the str package for logging server listening addresses in route.go. In route_test.go, renamed the configuration mock alias and modified CreateUser.PrepareForValidation to include a context-derived string using the cast package.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant ContextRequest
    participant Validator

    Client->>Server: Send GET request with context parameter
    Server->>ContextRequest: Invoke ValidateRequest method
    ContextRequest->>Validator: Call PrepareForValidation(ctx, validationFunc)
    Validator-->>ContextRequest: Return validation result
    ContextRequest->>Server: Return JSON response or error status
    Server->>Client: Respond with validation result
Loading

Possibly related PRs

  • fix: link #139: Updates in logging and removal of the termlink dependency in route.go, aligning with similar changes in this PR.
  • fix: Context method  #126: Adjustments to context handling in validation methods, affecting how context values are passed in function calls.

Suggested reviewers

  • kkumar-gcc
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
  • @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.

@hwbrzzl hwbrzzl changed the base branch from master to v1.3.x February 28, 2025 08:24
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

PR Overview

This PR fixes an issue where the context passed to PrepareForValidation was always nil by updating the PrepareForValidation call and adding a dedicated test. It also includes refactoring changes such as renaming config mocks and updating log messages for consistency.

  • Added a new test to validate that context values are correctly passed in PrepareForValidation.
  • Updated the PrepareForValidation call to include the context.
  • Renamed config mock imports and refined log output in route methods.

Reviewed Changes

File Description
context_request_test.go Added a test to verify the context value after validation.
route_test.go Renamed references from configmocks to mocksconfig.
route.go Updated logging and refactored Listen/ListenTLS methods.
context_request.go Fixed the PrepareForValidation call by passing the context.

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Comment on lines +1409 to +1420
ctx.WithValue("test", "-ctx")

var createUser CreateUser
validateErrors, err := ctx.Request().ValidateRequest(&createUser)
if err != nil {
return ctx.Response().String(http.StatusBadRequest, "Validate error: "+err.Error())
}
if validateErrors != nil {
return ctx.Response().String(http.StatusBadRequest, fmt.Sprintf("Validate fail: %+v", validateErrors.All()))
}

return ctx.Response().Success().Json(contractshttp.Json{
Copy link
Preview

Copilot AI Feb 28, 2025

Choose a reason for hiding this comment

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

Verify that ctx.WithValue properly updates the context. If WithValue returns a new context instance rather than modifying in place, consider capturing and using the returned context.

Suggested change
ctx.WithValue("test", "-ctx")
var createUser CreateUser
validateErrors, err := ctx.Request().ValidateRequest(&createUser)
if err != nil {
return ctx.Response().String(http.StatusBadRequest, "Validate error: "+err.Error())
}
if validateErrors != nil {
return ctx.Response().String(http.StatusBadRequest, fmt.Sprintf("Validate fail: %+v", validateErrors.All()))
}
return ctx.Response().Success().Json(contractshttp.Json{
newCtx := ctx.WithValue("test", "-ctx")
var createUser CreateUser
validateErrors, err := newCtx.Request().ValidateRequest(&createUser)
if err != nil {
return newCtx.Response().String(http.StatusBadRequest, "Validate error: "+err.Error())
}
if validateErrors != nil {
return newCtx.Response().String(http.StatusBadRequest, fmt.Sprintf("Validate fail: %+v", validateErrors.All()))
}
return newCtx.Response().Success().Json(contractshttp.Json{

Copilot is powered by AI, so mistakes are possible. Review output carefully before use.

Positive Feedback
Negative Feedback

Provide additional feedback

Please help us improve GitHub Copilot by sharing more details about this comment.

Please select one or more of the options
Copy link

@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 (1)
route.go (1)

26-26: Replaced termlink with internal str package.

Removed dependency on external termlink package in favor of the internal str package from the framework.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 694e0a5 and 298c05a.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (5)
  • context_request.go (1 hunks)
  • context_request_test.go (1 hunks)
  • go.mod (2 hunks)
  • route.go (5 hunks)
  • route_test.go (19 hunks)
🔇 Additional comments (16)
context_request.go (1)

485-485: Bug fix: Added context to PrepareForValidation.

The change passes the request context (r.ctx) to the validation preparation function, addressing issue #589 where context was previously nil in PrepareForValidation. This fix ensures that context-dependent validation can work properly.

context_request_test.go (1)

1406-1432: Good addition of test for context-aware validation.

This test effectively verifies the bugfix by:

  1. Setting a context value (-ctx)
  2. Validating a request with that context
  3. Confirming the context value is correctly appended to the final name

The test demonstrates that the context is now properly passed to the PrepareForValidation function.

route_test.go (2)

21-22: Updated import aliases for consistency.

The import for config mock package has been renamed from configmocks to mocksconfig, and the cast package has been added for string type conversion.


753-757: Enhanced PrepareForValidation to use context values.

The updated implementation now reads the "test" value from the context and appends it to the name field. This works in conjunction with the fix in context_request.go to demonstrate that context values are properly passed to PrepareForValidation.

route.go (4)

156-158: Improved logging sequence and formatting.

Now routes are output before the server listening message, and the URL formatting uses the internal str package instead of termlink.


185-190: Improved HTTPS logging format.

Server listening message now uses a more consistent format with str package, and routes are output before starting the server.


206-208: Updated HTTP server logging format.

Server startup message now uses the internal str package for URL formatting.


241-243: Updated HTTPS server logging format.

Server startup message for HTTPS now uses the internal str package for URL formatting.

go.mod (8)

11-11: Dependency Update: github.com/goravel/framework to v1.15.4
This update bumps the framework version from v1.15.0 to v1.15.4. Ensure that any breaking changes (if any) are handled in the codebase.


22-22: Dependency Update: github.com/containerd/console v1.0.4
The version for containerd/console has been updated. Verify that this indirect dependency update does not introduce any conflicts downstream.


25-26: Dependency Updates: fsnotify and mimetype

  • github.com/fsnotify/fsnotify has been updated to v1.8.0.
  • github.com/gabriel-vasile/mimetype has been updated to v1.4.8.
    These updates likely include bug fixes or performance improvements. Please ensure that any consumers of these packages in the project remain compatible.

37-37: Dependency Update: github.com/magiconair/properties to v1.8.9
This update brings a new version of the properties package. A quick check for any API changes on the consumer side is recommended.


42-42: Dependency Update: github.com/pelletier/go-toml/v2 to v2.2.3
The TOML parser has been updated from v2.2.2 to v2.2.3. Confirm that the latest fixes or improvements align with your configuration needs.


47-47: Dependency Update: github.com/sagikazarmark/locafero to v0.6.0
This update represents a jump from v0.4.0 to v0.6.0. Review the release notes for any breaking changes or additional features that might affect filesystem abstraction logic within the codebase.


59-63: Multiple Dependency Updates: Go Ecosystem Packages
The following dependencies have been updated:

  • go.uber.org/multierr to v1.11.0
  • golang.org/x/exp to v0.0.0-20250106191152-7588d65b2ba8
  • golang.org/x/net to v0.34.0
  • golang.org/x/sys to v0.29.0
  • golang.org/x/term to v0.28.0
    These updates aim to streamline improvements and security fixes in common Go libraries. Verify that the indirect dependencies used by the project integrate well with these versions, and consider running go mod tidy to clean up the module graph if necessary.

65-68: Multiple Dependency Updates: Google & YAML Packages
The following updates have been applied:

  • google.golang.org/genproto/googleapis/rpc to v0.0.0-20250124145028-65684f501c47
  • google.golang.org/grpc to v1.70.0
  • google.golang.org/protobuf to v1.36.4
  • gopkg.in/check.v1 to v1.0.0-20201130134442-10cb98267c6c
    Review these changes to ensure that any grpc or protobuf-related functionalities are compatible with the new versions. These updates can bring performance improvements and additional features, but verifying against your integration tests is advisable.

@hwbrzzl hwbrzzl closed this Feb 28, 2025
@hwbrzzl hwbrzzl reopened this Feb 28, 2025
@hwbrzzl hwbrzzl merged commit bdfb701 into v1.3.x Feb 28, 2025
8 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#589 branch February 28, 2025 08:33
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.

Context in PrepareForValidation always nil
1 participant