Skip to content

Fix snake case array discriminator#3125

Merged
koxudaxi merged 3 commits into
mainfrom
fix/snake-case-array-discriminator
May 7, 2026
Merged

Fix snake case array discriminator#3125
koxudaxi merged 3 commits into
mainfrom
fix/snake-case-array-discriminator

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented May 7, 2026

Fixes: #3091

Summary by CodeRabbit

  • Documentation

    • Adjusted CLI reference example formatting for the single-line docstring output to improve readability.
  • Bug Fixes

    • Validated and normalized discriminator field names when collapsing root models to ensure generated discriminators use valid field names.
  • Tests

    • Added a regression test and expected output covering discriminator-in-array scenarios with snake_case fields targeting Pydantic v2.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 7, 2026

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2cdb7e26-9377-461d-bbf1-11f8e9cc5bf2

📥 Commits

Reviewing files that changed from the base of the PR and between 5af17f7 and 00f4c97.

📒 Files selected for processing (2)
  • docs/cli-reference/field-customization.md
  • tests/main/openapi/test_main_openapi.py
✅ Files skipped from review due to trivial changes (1)
  • docs/cli-reference/field-customization.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/main/openapi/test_main_openapi.py

📝 Walkthrough

Walkthrough

Normalize discriminator property names during root-model collapse by validating them with ModelResolver.get_valid_field_name_and_alias; add a golden Pydantic v2 artifact and a regression test for discriminator-in-array snake_case behavior; adjust a documentation example's snippet formatting.

Changes

Discriminator Snake-Case Normalization

Layer / File(s) Summary
Core Implementation
src/datamodel_code_generator/parser/base.py
Discriminator property names in Parser.__collapse_root_models are now passed through ModelResolver.get_valid_field_name_and_alias(...) and the validated field name is assigned to copied_data_type.discriminator.
Expected Output
tests/data/expected/main/openapi/discriminator/in_array_snake_case_pydantic_v2.py
Adds golden Pydantic v2 models and enums for discriminated union-in-array with snake_case field aliasing and Field(discriminator='object_type').
Regression Test
tests/main/openapi/test_main_openapi.py
New test test_main_openapi_discriminator_in_array_snake_case validates generation from discriminator_in_array_snake_case.yaml with --snake-case-field, --collapse-root-models, and Pydantic v2 flags, asserting output matches the golden file.
Documentation
docs/cli-reference/field-customization.md
Adjusted example code block header/import whitespace for the --use-single-line-docstring section to match current rendered output.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • ilovelinux

Poem

🐰 I nibbled names to make them right,
turned camel-hooks to snake_case light.
Discriminators now align,
tests and golden outputs sign.
Hooray — models import without fright!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Fix snake case array discriminator' is directly related to and accurately summarizes the main change, addressing the bug fix for discriminators in array items with snake_case field conversion.
Linked Issues check ✅ Passed The PR successfully addresses issue #3091 by normalizing discriminator field names through ModelResolver.get_valid_field_name_and_alias in Parser.__collapse_root_models, ensuring discriminator property names are correctly converted to snake_case when collapsing root models with array items discriminators.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing the discriminator snake_case issue: core fix in base.py, documentation example update, test artifact addition, and regression test. No unrelated or out-of-scope changes detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/snake-case-array-discriminator

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 7, 2026

📚 Docs Preview: https://pr-3125.datamodel-code-generator.pages.dev

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented May 7, 2026

Merging this PR will not alter performance

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

✅ 11 untouched benchmarks
⏩ 98 skipped benchmarks1


Comparing fix/snake-case-array-discriminator (00f4c97) with main (2a2ed06)

Open in CodSpeed

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 7, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (2a2ed06) to head (00f4c97).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #3125   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           88        88           
  Lines        18536     18541    +5     
  Branches      2141      2141           
=========================================
+ Hits         18536     18541    +5     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@koxudaxi koxudaxi enabled auto-merge (squash) May 7, 2026 09:00
@koxudaxi koxudaxi merged commit 90b0729 into main May 7, 2026
42 checks passed
@koxudaxi koxudaxi deleted the fix/snake-case-array-discriminator branch May 7, 2026 09:01
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 7, 2026

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR fixes a bug where discriminator field names in collapsed root models (array items) were not normalized through get_valid_field_name_and_alias(). Previously, with --snake-case-field and --collapse-root-models, the discriminator value in generated code used the raw schema property name (e.g., objectType) instead of the snake_case Python field name (e.g., object_type). This produced invalid Pydantic v2 code that would fail at runtime, since Pydantic requires the discriminator to match the Python field name, not the alias. The generated output changes only in the specific scenario where it was previously broken, making this a correctional bug fix rather than a breaking change.


This analysis was performed by Claude Code Action

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 7, 2026

🎉 Released in 0.57.0

This PR is now available in the latest release. See the release notes for details.

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.

Discriminator inside list items not snake-cased with --snake-case-field + --collapse-root-models

1 participant