Add schema path context to error messages#2786
Conversation
📝 WalkthroughWalkthroughA new Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
CodSpeed Performance ReportMerging #2786 will not alter performanceComparing Summary
Footnotes
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (3)
tests/main/test_main_general.py (1)
477-552: NewSchemaParseErrortests cover key behaviorsThe four tests collectively verify:
- Integration with
generate()for both flat and nested schemas (including$defs/MyModelpath),- Preservation of
original_errorandpath,- Message formatting when
pathis omitted.They are focused, resilient (regex-based), and exercise the intended API surface well.
If you want slightly stronger guarantees, you could also assert on
exc_info.value.pathcontents in the nested-path test (e.g., that it ends with["#/$defs", "MyModel"]), but the current coverage is already solid.src/datamodel_code_generator/__init__.py (1)
393-414:SchemaParseErrordesign and export look correct
- The class cleanly extends
Error, preserves the original exception viaoriginal_error, and adds structuredpathinformation while formatting a human-readable message.- Defaulting
pathto[]and formatting only when non-empty matches the tests’ expectations (both with and without path).- Adding
"SchemaParseError"to__all__makes the type publicly consumable, which is consistent with how it’s used in tests and in the JSON Schema parser.If you later need to distinguish the raw message from the path-augmented one, consider storing the unformatted message in a separate attribute (e.g.,
base_message), but it’s not necessary for the current use cases.Also applies to: 1005-1025
src/datamodel_code_generator/parser/jsonschema.py (1)
24-40: Centralized schema-object validation withSchemaParseErroris well-structured
- Importing
SchemaParseErrorhere and introducing_validate_schema_object()gives a single, consistent place to wrap low-level validation failures into a richer error that includespathandoriginal_error.- The
except SchemaParseError: raiseclause avoids double-wrapping if future callers already raise that type, while the broadexcept Exception as ecorrectly captures any validation/runtime issues frommodel_validate.- Using
message=f"{type(e).__name__}: {e}"preserves the original exception type in the human-facing message, while the underlying exception remains available viaoriginal_errorfor advanced consumers.You might later consider also routing other internal
model_validate(self.SCHEMA_OBJECT_TYPE, ...)call sites (e.g., in_load_ref_schema_objector merge helpers) through_validate_schema_objectso that all schema-object construction failures benefit from path-awareSchemaParseError, but the current scope is already an improvement aligned with the PR goal.Also applies to: 3109-3134
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/datamodel_code_generator/__init__.pysrc/datamodel_code_generator/parser/jsonschema.pytests/main/test_main_general.py
🧰 Additional context used
🧬 Code graph analysis (2)
src/datamodel_code_generator/parser/jsonschema.py (3)
src/datamodel_code_generator/__init__.py (1)
SchemaParseError(393-413)src/datamodel_code_generator/util.py (1)
model_validate(201-205)src/datamodel_code_generator/__main__.py (1)
parse_obj(126-128)
tests/main/test_main_general.py (1)
src/datamodel_code_generator/__init__.py (1)
SchemaParseError(393-413)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
- GitHub Check: py312-pydantic1 on Ubuntu
- GitHub Check: 3.12 on Ubuntu
- GitHub Check: py312-black24 on Ubuntu
- GitHub Check: py312-isort7 on Ubuntu
- GitHub Check: py312-black22 on Ubuntu
- GitHub Check: py312-isort6 on Ubuntu
- GitHub Check: 3.10 on macOS
- GitHub Check: 3.10 on Windows
- GitHub Check: 3.12 on macOS
- GitHub Check: 3.11 on Windows
- GitHub Check: py312-isort5 on Ubuntu
- GitHub Check: 3.11 on macOS
- GitHub Check: 3.13 on macOS
- GitHub Check: 3.10 on Ubuntu
- GitHub Check: 3.12 on Windows
- GitHub Check: 3.11 on Ubuntu
- GitHub Check: 3.14 on Windows
- GitHub Check: 3.13 on Windows
- GitHub Check: Analyze (python)
- GitHub Check: benchmarks
🔇 Additional comments (2)
tests/main/test_main_general.py (1)
11-20: Public import ofSchemaParseErroris appropriateExposing
SchemaParseErrorat the top-level for tests (and users) matches its role as a first-class, library-defined error type and aligns with the new test usage.src/datamodel_code_generator/parser/jsonschema.py (1)
3278-3299: Path propagation intoSchemaParseErrorfrom file roots, definitions, and JSON pointers
- Validating
rawwith_validate_schema_object(raw, path_parts or ["#"])ensures root-level schema failures now report either the source path or a synthetic"#"anchor.- For definitions, constructing
definition_path = [*path_parts, schema_path, key]and using it for both_validate_schema_objectandparse_idgives precise paths like.../#/$defs/MyModel, which matches the new nested-path test and improves $id bookkeeping.- For targeted object paths and reserved refs, passing
pathderived from the JSON pointer (reserved_path.split("/")) yields intuitive messages such as#/components/schemas/Foo, tying errors directly to the pointer being resolved.Because
parse_idnow receivesdefinition_pathinstead of justpath_parts, the stored$id→ path mapping in the model resolver will change slightly for schemas under#/definitions/#/$defs. This should be an improvement, but please verify any existing tests or fixtures that rely on$id-based resolution (especially multi-file or external$idreferences) still behave as expected.Also applies to: 3318-3319
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2786 +/- ##
=======================================
Coverage 99.47% 99.47%
=======================================
Files 88 88
Lines 13213 13256 +43
Branches 1556 1557 +1
=======================================
+ Hits 13144 13187 +43
Misses 36 36
Partials 33 33
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Breaking Change AnalysisResult: Breaking changes detected Reasoning: This PR changes the exception type raised when schema parsing fails. Previously, Pydantic's ValidationError would propagate directly from model_validate() calls. Now, these errors are caught and re-raised as SchemaParseError with additional path context. While this improves error messages by including schema path information, it changes the exception type that users might be catching. Users who specifically catch pydantic.ValidationError for schema validation errors will need to update their exception handling to catch SchemaParseError instead. Content for Release NotesError Handling Changes
This analysis was performed by Claude Code Action |
* Add --collapse-root-models-name-strategy option * docs: update CLI reference documentation and prompt data 🤖 Generated by GitHub Actions * Add pragma no cover for defensive edge cases * Achieve 100% diff coverage for collapse-root-models-name-strategy * Use cast instead of type ignore comment * Remove line comments from collapse-root-models implementation * Add complex e2e tests for collapse-root-models-name-strategy * Update reference metadata when renaming in parent strategy * Refactor collapse-root-models tests to use parameterization for v1/v2 * Add schema path context to error messages (#2786) * Return str or dict when output=None in generate() (#2787) * Add --http-timeout CLI option (#2788) * Add --http-timeout CLI option for configurable HTTP request timeout * docs: update CLI reference documentation and prompt data 🤖 Generated by GitHub Actions --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * Pass schema extensions to templates (#2790) * Pass schema extensions to templates * Move model_base import to top of file * Add schema extensions documentation Document how x-* schema extensions are passed to custom templates via the extensions variable, with examples for database model configuration and other use cases. 🤖 Generated with [Claude Code](https://claude.com/claude-code) * Add propertyNames and x-propertyNames support (#2789) * Add propertyNames and x-propertyNames support * Fix Pydantic v1 compatibility for x-propertyNames Use the model_validate utility function from util module instead of calling JsonSchemaObject.model_validate() directly, which only exists in Pydantic v2. 🤖 Generated with [Claude Code](https://claude.com/claude-code) * Add test for x-propertyNames non-dict branch coverage Test that x-propertyNames with non-dict value (e.g., boolean) is correctly ignored, achieving 100% diff coverage. 🤖 Generated with [Claude Code](https://claude.com/claude-code) * Add support for additional_imports in extra-template-data JSON (#2793) * Update zensical to 0.0.15 (#2794) * Add --use-field-description-example option (#2792) * Add --use-field-description-example option * docs: update CLI reference documentation and prompt data 🤖 Generated by GitHub Actions * Add tests for complete branch coverage of docstring property --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com> * Fix formatting in test file --------- Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Fixes: #1330
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.