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: recompute property names after schema transform #611

Merged
merged 3 commits into from
Oct 16, 2024

Conversation

danielgtaylor
Copy link
Owner

@danielgtaylor danielgtaylor commented Oct 16, 2024

This PR makes a few small but important changes:

  1. Call schema.PrecomputeMessages() after a call to a huma.SchemaTransformer as it may have modified the schema.
  2. Make PrecomputeMessages() recreate the property names, rather than only setting them if they don't already exist.
  3. Sort the property names so the order is deterministic. This helps with testing.

Fixes #607.

Summary by CodeRabbit

  • New Features

    • Enhanced middleware functionality testing with new test cases for cookie handling, parameter validation, and response handling.
    • Introduced a new struct for schema modifications, allowing properties to be deleted.
  • Bug Fixes

    • Improved error message clarity in schema transformations.
  • Documentation

    • Updated test cases for better output and coverage, ensuring comprehensive validation of edge cases.

Copy link

coderabbitai bot commented Oct 16, 2024

Walkthrough

The changes made in this pull request enhance the testing and schema handling capabilities of the Huma API framework. Updates include the addition of new test cases in huma_test.go, modifications to the Schema struct in schema.go for better clarity and efficiency, and the introduction of a new struct in validate_test.go to support schema modifications. These alterations aim to improve middleware functionality, error handling, and overall schema management.

Changes

File(s) Change Summary
huma_test.go Added multiple new test cases for middleware functionality, including cookie handling and response handling. Updated function signatures for new tests.
schema.go Modified Schema struct methods for clarity and efficiency. Updated SchemaFromType for better error messaging.
validate_test.go Introduced TransformDeleteField struct to implement schema modifications. Updated ExampleModelValidator and added new test cases for schemas with discriminators.

Assessment against linked issues

Objective Addressed Explanation
Identify the cause of the panic in Schema.Properties and ensure correct absence of input_data (607)
Investigate the implementation of modifying s.Properties directly (607)
Propose a solution to achieve shared Go structures with different OpenAPI specifications (607) It's unclear if a comprehensive solution was proposed.

Possibly related PRs

Poem

🐇 In the garden of code, where the schemas grow,
New tests bloom brightly, putting on a show.
With cookies and parameters, we dance and we play,
Ensuring our framework shines brighter each day!
So hop along, friends, let the changes take flight,
For the Huma API is now a delight! 🌼


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

codecov bot commented Oct 16, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 92.83%. Comparing base (1c7affe) to head (99d6425).
Report is 10 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #611   +/-   ##
=======================================
  Coverage   92.83%   92.83%           
=======================================
  Files          22       22           
  Lines        3923     3923           
=======================================
  Hits         3642     3642           
  Misses        236      236           
  Partials       45       45           

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

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1c7affe and 7ed8933.

📒 Files selected for processing (3)
  • huma_test.go (1 hunks)
  • schema.go (2 hunks)
  • validate_test.go (2 hunks)
🧰 Additional context used
🔇 Additional comments (4)
schema.go (3)

293-301: Improved initialization and sorting of schema properties

The changes in the PrecomputeMessages method enhance the clarity and efficiency of the schema handling logic:

  1. propertyNames is now initialized with a known capacity, which is more memory-efficient.
  2. Sorting propertyNames ensures a consistent order, beneficial for testing and deterministic behavior.
  3. requiredMap is now initialized directly, simplifying the code.

These improvements contribute to better performance and maintainability of the schema handling process.


672-675: Enhanced schema customization with SchemaTransformer

The addition of the SchemaTransformer interface support in SchemaFromType is a valuable improvement:

  1. It allows types to implement custom schema transformations, providing greater flexibility in schema generation.
  2. The TransformSchema method enables fine-grained control over the generated schema.
  3. Recomputing error messages after transformation ensures consistency between the modified schema and its validation messages.

This feature enhances the extensibility of the schema generation process while maintaining the integrity of the validation system.


293-301: Summary: Effective improvements in schema handling and transformation

The changes in schema.go successfully address the objectives outlined in the PR:

  1. The PrecomputeMessages method now ensures consistent and efficient initialization of propertyNames and requiredMap.
  2. The introduction of SchemaTransformer support in SchemaFromType allows for flexible schema customization.
  3. Recomputing messages after schema transformation maintains the integrity of the validation system.

These improvements effectively resolve the inconsistencies mentioned in issue #607 by ensuring that schema transformations are properly handled and reflected in the final schema representation. The changes enhance the overall reliability and flexibility of the Huma framework's schema handling capabilities.

Also applies to: 672-675

huma_test.go (1)

1957-1960: LGTM!

The added error message assertions accurately reflect the expected length validation errors in the test case. This enhances the comprehensiveness of the test coverage.

validate_test.go Outdated
Comment on lines 1443 to 1452
func TestValidateSchemaTransformerDeleteField(t *testing.T) {
registry := huma.NewMapRegistry("#/components/schemas/", huma.DefaultSchemaNamer)
s := registry.Schema(reflect.TypeOf(&TransformDeleteField{}), true, "TestInput")
pb := huma.NewPathBuffer([]byte(""), 0)
res := &huma.ValidateResult{}

huma.Validate(registry, s, pb, huma.ModeReadFromServer, map[string]any{"field1": "value1"}, res)
// We should have no errors and no panics.
assert.Empty(t, res.Errors)
}
Copy link

@coderabbitai coderabbitai bot Oct 16, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure the schema transformation is correctly validated

In the TestValidateSchemaTransformerDeleteField test function, consider adding assertions to verify that field2 has been removed from the schema. This will confirm that the schema transformation behaves as expected and that the validation process is accurate.

You can add an assertion like:

assert.NotContains(t, s.Properties, "field2")

Copy link
Owner Author

Choose a reason for hiding this comment

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

Good idea, thanks!

Copy link

Choose a reason for hiding this comment

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

@danielgtaylor You're welcome! Glad it was helpful!

((_/)
( •_•)
❤️


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

validate_test.go Show resolved Hide resolved
Copy link
Contributor

@superstas superstas left a comment

Choose a reason for hiding this comment

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

@danielgtaylor Looks good to me, thanks!

@danielgtaylor danielgtaylor merged commit 0f7ad56 into main Oct 16, 2024
7 checks passed
@danielgtaylor danielgtaylor deleted the recompute-property-names-after-transform branch October 16, 2024 16:18
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.

[panicking] Schema.Properties gets inconsistent with the private Schema.propertyNames.
2 participants