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

feat: case-insensitive field matching for JSON/CBOR #629

Merged
merged 1 commit into from
Oct 28, 2024

Conversation

danielgtaylor
Copy link
Owner

@danielgtaylor danielgtaylor commented Oct 28, 2024

This PR updates the field validation to use case-insensitive matches when validating input objects. This is done because:

  1. Go's JSON & CBOR unmarshalers use this behavior, preferring exact matches but falling back to case-insensitive ones.
  2. Updating legacy services to Huma may require supporting clients which send different cases, and this makes it easier to switch to Huma.

Fixes #577.

Summary by CodeRabbit

  • New Features

    • Introduced a global variable for controlling case sensitivity in field name validation, enhancing flexibility for clients with varying casing conventions.
    • Added new test cases to validate case-insensitive property handling.
  • Bug Fixes

    • Improved error handling for unexpected properties to support case-insensitive checks.
  • Tests

    • Enhanced test structure to allow setup and teardown functions for more complex scenarios.

Copy link

coderabbitai bot commented Oct 28, 2024

Walkthrough

The changes introduce a new global variable ValidateStrictCasing in validate.go, which controls case sensitivity during validation. The validation logic has been updated to allow case-insensitive checks for map keys when this variable is disabled. Additionally, the error handling for unexpected properties has been modified to support case-insensitive checks. In validate_test.go, the test structure has been enhanced to include setup and teardown functions, and new test cases have been added to validate case-insensitive handling.

Changes

File Change Summary
validate.go Introduced ValidateStrictCasing variable; modified validation logic for case-insensitive checks; updated error handling for unexpected properties.
validate_test.go Enhanced test structure with before and cleanup fields; added new test cases for case-insensitive property handling; updated TestValidate logic.

Assessment against linked issues

Objective Addressed Explanation
Introduce case insensitivity for JSON tags (#577)

Possibly related PRs

Suggested reviewers

  • superstas

Poem

In the fields where data plays,
A rabbit hops through JSON ways.
With casing loose, it finds its way,
Validations bright, come what may!
Hooray for changes, let’s all cheer,
For every field, we hold so dear! 🐇✨


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

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: 2

🧹 Outside diff range and nitpick comments (2)
validate.go (1)

38-43: Consider thread-safety implications of the global variable.

While the documentation clearly explains the purpose and default behavior, using a global variable for validation configuration could lead to race conditions in concurrent scenarios. Consider one of these alternatives:

  1. Make it a field in the ValidateResult struct
  2. Add it as a parameter to the Validate function
validate_test.go (1)

923-950: Consider grouping case sensitivity test cases.

While the test cases comprehensively cover the case-insensitive functionality, consider grouping them together using a descriptive prefix like TestCaseSensitivity_ for better organization and readability.

Apply this diff to improve test organization:

-		name: "case-insensive success",
+		name: "TestCaseSensitivity_InsensitiveSuccess",
 		typ: reflect.TypeOf(struct {
 			Value string `json:"value"`
 		}{}),
 		input: map[string]any{"VaLuE": "works"},
 	},
 	{
-		name: "case-insensive fail",
+		name: "TestCaseSensitivity_InsensitiveFail",
 		typ: reflect.TypeOf(struct {
 			Value string `json:"value" maxLength:"3"`
 		}{}),
 		input: map[string]any{"VaLuE": "fails"},
 		errs:  []string{"expected length <= 3"},
 	},
 	{
-		name: "case-sensive fail",
+		name: "TestCaseSensitivity_StrictFail",
 		before:  func() { huma.ValidateStrictCasing = true },
 		cleanup: func() { huma.ValidateStrictCasing = false },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 52482f3 and 91ff308.

📒 Files selected for processing (2)
  • validate.go (4 hunks)
  • validate_test.go (4 hunks)
🔇 Additional comments (4)
validate.go (2)

Line range hint 619-662: LGTM! Clean implementation of case-insensitive matching.

The implementation correctly:

  • Preserves the original casing from the input
  • Uses strings.EqualFold for proper case-insensitive comparison
  • Maintains validation of required fields and dependencies

667-679: LGTM! Well-structured additional properties validation.

The implementation:

  • Correctly handles case-insensitive matching for additional properties
  • Uses a clean labeled break pattern for control flow
  • Maintains clear error messaging
validate_test.go (2)

31-39: LGTM: Well-structured test case setup.

The addition of before and cleanup fields follows good testing practices by providing clear setup and teardown capabilities for each test case.


1401-1407: LGTM: Proper test setup and cleanup handling.

The implementation correctly handles test setup and cleanup, using defer for cleanup functions to ensure they run even if the test panics.

Copy link

codecov bot commented Oct 28, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 92.90%. Comparing base (52482f3) to head (91ff308).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #629      +/-   ##
==========================================
+ Coverage   92.88%   92.90%   +0.02%     
==========================================
  Files          22       22              
  Lines        4834     4848      +14     
==========================================
+ Hits         4490     4504      +14     
  Misses        299      299              
  Partials       45       45              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@jc-fireball
Copy link

Thanks for the change.

@danielgtaylor danielgtaylor merged commit d67ab01 into main Oct 28, 2024
7 checks passed
@danielgtaylor danielgtaylor deleted the case-insensitive-matching branch October 28, 2024 20:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Case Sensitivity For JSON tags
2 participants