Skip to content

fix: [#589] Context in PrepareForValidation always nil#919

Merged
hwbrzzl merged 1 commit intomasterfrom
bowen/#589-1
Feb 28, 2025
Merged

fix: [#589] Context in PrepareForValidation always nil#919
hwbrzzl merged 1 commit intomasterfrom
bowen/#589-1

Conversation

@hwbrzzl
Copy link
Contributor

@hwbrzzl hwbrzzl commented Feb 28, 2025

📑 Description

Closes goravel/goravel#589

Summary by CodeRabbit

  • New Features

    • Enhanced the validation process by incorporating context support, allowing for more flexible and controlled validation flows.
  • Tests

    • Added and updated test cases to verify proper context handling and to ensure robust error assertions during validation.

✅ Checks

  • Added test cases for my code

Copilot AI review requested due to automatic review settings February 28, 2025 02:57
@hwbrzzl hwbrzzl requested a review from a team as a code owner February 28, 2025 02:57
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 28, 2025

Walkthrough

This pull request updates context handling across multiple parts of the codebase. In the HTTP package, a comment in the WithValue method is reformatted. In the validation package, the PrepareForValidation function now accepts a context parameter, stores it in an options map, and the Make method of the Validation struct retrieves this context if available before calling the preparation function. Additionally, test cases have been updated to use the new context parameter and revised error assertions.

Changes

File(s) Summary of Change
http/context.go Adjusted the inline comment in the WithValue method from //nolint:all to // nolint:all.
validation/options.go
validation/validation.go
Updated PrepareForValidation and Make to accept and retrieve a context parameter. The options map now stores the context, and Make checks for the context before invoking the preparation method.
validation/validation_test.go Modified test cases to create and use a new context (switching from http.Context to contractshttp.Context in the test), updated error assertions, and added a test for context-aware validation.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Validator
    participant PrepFunc

    Caller->>Validator: Invoke Make() for validation
    Validator->>Validator: Check generateOptions for context
    alt Context found
        Validator->>PrepFunc: Call prepareForValidation(ctx, data)
    else Context not found
        Validator->>PrepFunc: Call prepareForValidation(nil, data)
    end
    PrepFunc-->>Validator: Return error/success
    Validator-->>Caller: Return validation result
Loading

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24.0)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24.0)

✨ 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.

@codecov
Copy link

codecov bot commented Feb 28, 2025

Codecov Report

Attention: Patch coverage is 75.00000% with 3 lines in your changes missing coverage. Please review.

Project coverage is 68.82%. Comparing base (f21bf46) to head (9ce8451).
Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
validation/validation.go 66.66% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #919      +/-   ##
==========================================
- Coverage   68.82%   68.82%   -0.01%     
==========================================
  Files         154      154              
  Lines       10191    10200       +9     
==========================================
+ Hits         7014     7020       +6     
- Misses       2855     2857       +2     
- Partials      322      323       +1     

☔ 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

🧹 Nitpick comments (1)
validation/validation_test.go (1)

87-91: Consider adding a test for nil context

There's no test case that verifies the behavior when PrepareForValidation is called without a context, which explains the lack of test coverage noted in static analysis.

Consider adding a test case like:

{
    description: "success when PrepareForValidation is called without context",
    data:        map[string]any{"a": "   b  "},
    rules:       map[string]string{"a": "required"},
    options: []httpvalidate.Option{
        Filters(map[string]string{"a": "trim"}),
        PrepareForValidation(nil, func(ctx contractshttp.Context, data httpvalidate.Data) error {
            // Test that ctx is nil but validation still works
            return nil
        }),
    },
    expectValidator: true,
    expectData:      Data{A: "b"},
},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f21bf46 and 9ce8451.

📒 Files selected for processing (4)
  • http/context.go (1 hunks)
  • validation/options.go (1 hunks)
  • validation/validation.go (1 hunks)
  • validation/validation_test.go (6 hunks)
✅ Files skipped from review due to trivial changes (1)
  • http/context.go
🧰 Additional context used
🪛 GitHub Check: codecov/patch
validation/validation.go

[warning] 63-64: validation/validation.go#L63-L64
Added lines #L63 - L64 were not covered by tests

⏰ Context from checks skipped due to timeout of 300000ms (1)
  • GitHub Check: test / windows (1.24)
🔇 Additional comments (6)
validation/validation.go (2)

57-65: Context handling enhancement

Good implementation of context handling for PrepareForValidation. The code properly retrieves context from options and handles the case where it doesn't exist.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 63-64: validation/validation.go#L63-L64
Added lines #L63 - L64 were not covered by tests


63-64: Add test coverage for the nil context case

According to static analysis, these lines aren't covered by tests, indicating that there's no test for the case when context doesn't exist in options.

Consider adding a test case where PrepareForValidation is called without a context to ensure both code paths are covered.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 63-64: validation/validation.go#L63-L64
Added lines #L63 - L64 were not covered by tests

validation/options.go (1)

60-62: Function signature update properly integrates context

The function now correctly accepts a context parameter and stores it in the options map, which fixes the issue where context in PrepareForValidation was always nil.

validation/validation_test.go (3)

110-126: Good test case for context usage

This new test case properly verifies that context values can be retrieved and used in PrepareForValidation, which is essential for the fix.


22-24: Test setup for context properly initialized

The setup code correctly initializes the context with a test value that will be used throughout the tests.


88-89: Verify the error assertion change

The error assertion changed from a specific error (likely errors.ErrInvalidData) to the generic assert.AnError. This makes the test less specific about what error is expected.

Was this change intentional? It's generally better to assert for specific error types when possible to ensure the exact error condition is being tested.

Copy link
Contributor

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 the issue where the context passed to PrepareForValidation was always nil, by updating the function signature and propagating the context through the options. Key changes include:

  • Updating the PrepareForValidation signature in options.go to accept a context parameter.
  • Adjusting the Make function in validation.go to extract and use the provided context.
  • Updating tests in validation_test.go to create and pass a proper context for validation.

Reviewed Changes

File Description
validation/validation_test.go Updated imports and test cases to create and pass context to PrepareForValidation.
validation/validation.go Modified Make to retrieve the context from options instead of hardcoding nil.
validation/options.go Revised PrepareForValidation to include the context parameter and set it in options.

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

Comments suppressed due to low confidence (2)

validation/validation_test.go:87

  • Ensure that the context type used in the closure matches the expected type (http.Context) as defined in the options. If contractshttp.Context and http.Context are interchangeable, consider adding a clarifying comment.
PrepareForValidation(ctx, func(ctx contractshttp.Context, data httpvalidate.Data) error {

validation/validation.go:61

  • [nitpick] Since the comma-ok type assertion already yields a nil value when the key is missing, explicitly setting ctx to nil in the if-condition might be redundant. Consider simplifying this block.
ctx, exist = generateOptions["ctx"].(http.Context)

@hwbrzzl hwbrzzl merged commit 2e950ff into master Feb 28, 2025
14 checks passed
@hwbrzzl hwbrzzl deleted the bowen/#589-1 branch February 28, 2025 03:35
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

2 participants