Skip to content

Fix crash when parsing enum containing only null value#2674

Merged
koxudaxi merged 1 commit intomainfrom
fix/null-only-enum-crash
Dec 17, 2025
Merged

Fix crash when parsing enum containing only null value#2674
koxudaxi merged 1 commit intomainfrom
fix/null-only-enum-crash

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented Dec 17, 2025

Summary

  • Fix black.parsing.InvalidInput crash when parsing OpenAPI schema with enum: [null] and nullable: true
  • Generate RootModel[None] instead of empty Enum class for null-only enums

Fixes #1969

Summary by CodeRabbit

  • New Features

    • Added support for null-only and empty enums in OpenAPI schemas, generating appropriate nullable type models.
  • Tests

    • Added test coverage for empty enum parsing and OpenAPI null-only enum code generation scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 17, 2025

Walkthrough

This change adds support for empty enum schemas in OpenAPI/JSON Schema by modifying the enum parsing logic to generate either a null type reference or a synthetic model with a null-type root field, preventing the generation of invalid empty Enum classes that cause Black parsing failures.

Changes

Cohort / File(s) Summary
Empty enum handling logic
src/datamodel_code_generator/parser/jsonschema.py
Modified parse_enum to branch on empty enum_fields: returns Types.null if not nullable, or creates a synthetic enum-like model with null-type root field if nullable/openable.
Expected output and OpenAPI spec
tests/data/expected/main/openapi/null_only_enum.py, tests/data/openapi/null_only_enum.yaml
Added new OpenAPI schema definition with null-only enum and corresponding expected Pydantic model output featuring __root__: None = None field.
Test coverage
tests/main/openapi/test_main_openapi.py, tests/parser/test_jsonschema.py
Added two new test functions: end-to-end OpenAPI generation test and unit test for empty non-nullable enum parsing.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

  • Focus areas: Verify the conditional logic in parse_enum correctly differentiates between nullable and non-nullable empty enums; confirm the synthetic model creation produces valid output; validate test assertions match expected behavior for the edge case.

Poem

🐰 An enum that's empty, quite strange indeed,
Now generates code that won't make Black bleed!
A null-type model, so clever and neat,
Makes edge cases tidy—the fix is complete! ✨

Pre-merge checks and finishing touches

✅ 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 crash when parsing enum containing only null value' directly and specifically describes the main fix: preventing crashes when handling null-only enums in OpenAPI schemas.
Linked Issues check ✅ Passed The PR addresses all coding requirements from issue #1969: fixes the crash by generating valid RootModel[None] code instead of empty enums, and includes test coverage for the fix.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing null-only enum parsing: core logic changes in jsonschema.py, test input file, expected output file, and corresponding test cases.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/null-only-enum-crash

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.

@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 17, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.51%. Comparing base (f42c49f) to head (7b77df6).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2674   +/-   ##
=======================================
  Coverage   99.51%   99.51%           
=======================================
  Files          79       79           
  Lines       10986    11001   +15     
  Branches     1316     1318    +2     
=======================================
+ Hits        10933    10948   +15     
  Misses         32       32           
  Partials       21       21           
Flag Coverage Δ
unittests 99.51% <100.00%> (+<0.01%) ⬆️

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.

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Dec 17, 2025

CodSpeed Performance Report

Merging #2674 will not alter performance

Comparing fix/null-only-enum-crash (7b77df6) with main (f42c49f)

Summary

✅ 50 untouched
⏩ 3 skipped1

Footnotes

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

@koxudaxi koxudaxi marked this pull request as ready for review December 17, 2025 07:52
Copy link
Copy Markdown

@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)
tests/parser/test_jsonschema.py (1)

926-931: Good test coverage for the non-nullable empty enum case.

The test correctly validates that an empty enum with no nullable flag returns a None type. Consider adding a complementary test for the nullable case to ensure both branches are unit-tested:

def test_parse_enum_empty_enum_nullable() -> None:
    """Test parse_enum creates root model when enum_fields is empty and nullable."""
    parser = JsonSchemaParser("")
    obj = JsonSchemaObject.parse_obj({"type": "string", "enum": [None], "nullable": True})
    result = parser.parse_enum("NullEnum", obj, ["NullEnum"])
    assert result.reference is not None
    assert len(parser.results) == 1
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f42c49f and 7b77df6.

📒 Files selected for processing (5)
  • src/datamodel_code_generator/parser/jsonschema.py (1 hunks)
  • tests/data/expected/main/openapi/null_only_enum.py (1 hunks)
  • tests/data/openapi/null_only_enum.yaml (1 hunks)
  • tests/main/openapi/test_main_openapi.py (1 hunks)
  • tests/parser/test_jsonschema.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/parser/test_jsonschema.py (1)
src/datamodel_code_generator/parser/jsonschema.py (2)
  • JsonSchemaObject (186-450)
  • parse_enum (2507-2689)
src/datamodel_code_generator/parser/jsonschema.py (3)
src/datamodel_code_generator/parser/openapi.py (1)
  • get_data_type (381-390)
src/datamodel_code_generator/model/types.py (1)
  • get_data_type (100-106)
src/datamodel_code_generator/reference.py (2)
  • reference (77-79)
  • add (787-841)
🪛 Checkov (3.2.334)
tests/data/openapi/null_only_enum.yaml

[high] 1-14: Ensure that the global security field has rules defined

(CKV_OPENAPI_4)

🔇 Additional comments (4)
tests/data/expected/main/openapi/null_only_enum.py (1)

1-11: LGTM!

The expected output correctly generates a RootModel with __root__: None = None for the null-only enum case. This avoids the Black parsing error that occurred with empty Enum classes and properly represents a type that only accepts None.

src/datamodel_code_generator/parser/jsonschema.py (1)

2570-2608: Well-structured fix for the null-only enum crash.

The implementation correctly handles two cases:

  1. Empty enum that is not nullable → returns a simple None type
  2. Empty enum that is nullable → creates a synthetic root model with a null-type field

This prevents the generation of empty Enum classes that caused Black parsing failures.

tests/data/openapi/null_only_enum.yaml (1)

1-12: LGTM!

This test fixture correctly reproduces the minimal case from issue #1969 - a schema with type: string, enum: [null], and nullable: true. The Checkov warning about missing security rules is irrelevant for a test fixture focused on schema parsing.

tests/main/openapi/test_main_openapi.py (1)

4177-4185: LGTM! Well-structured regression test for null-only enum handling.

The test appropriately validates the fix for issue #1969 by ensuring that OpenAPI schemas with enum: [null] and nullable: true no longer cause a crash and generate the expected output (RootModel[None] instead of an empty Enum class).

@koxudaxi koxudaxi merged commit 599ae84 into main Dec 17, 2025
41 checks passed
@koxudaxi koxudaxi deleted the fix/null-only-enum-crash branch December 17, 2025 07:56
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.

Code generation crashes with "black.parsing.InvalidInput: Cannot parse"

1 participant