Skip to content

Commit

Permalink
fix: treat nullable property as optional
Browse files Browse the repository at this point in the history
  • Loading branch information
janne-slamcore committed May 16, 2024
1 parent 72ac143 commit da209b0
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/generators/python/presets/Pydantic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ const PYTHON_PYDANTIC_CLASS_PRESET: ClassPresetType<PythonOptions> = {
type = `Union[${unionTypes.join(', ')}]`;
}

if (!params.property.required) {
const isOptional =
!params.property.required ||
params.property.property.options.isNullable === true;
if (isOptional) {
type = `Optional[${type}]`;
}

Expand All @@ -40,7 +43,7 @@ const PYTHON_PYDANTIC_CLASS_PRESET: ClassPresetType<PythonOptions> = {
`description='''${params.property.property.originalInput['description']}'''`
);
}
if (!params.property.required) {
if (isOptional) {
decoratorArgs.push('default=None');
}
if (
Expand Down
29 changes: 29 additions & 0 deletions test/generators/python/presets/Pydantic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,33 @@ describe('PYTHON_PYDANTIC_PRESET', () => {
const models = await generator.generate(doc);
expect(models.map((model) => model.result)).toMatchSnapshot();
});

test('should render nullable union', async () => {
const doc = {
title: 'NullableUnionTest',
type: 'object',
required: ['nullableUnionTest'],
properties: {
nullableUnionTest: {
anyOf: [
{
title: 'Union1',
type: 'object',
properties: {
testProp1: {
type: 'string'
}
}
},
{
type: 'null'
}
]
}
}
};

const models = await generator.generate(doc);
expect(models.map((model) => model.result)).toMatchSnapshot();
});
});
13 changes: 13 additions & 0 deletions test/generators/python/presets/__snapshots__/Pydantic.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`PYTHON_PYDANTIC_PRESET should render nullable union 1`] = `
Array [
"class NullableUnionTest(BaseModel):
nullableUnionTest: Optional[Union[Union1]] = Field(default=None)
additionalProperties: Optional[dict[Any, Any]] = Field(default=None)
",
"class Union1(BaseModel):
testProp1: Optional[str] = Field(default=None)
additionalProperties: Optional[dict[Any, Any]] = Field(default=None)
",
]
`;

exports[`PYTHON_PYDANTIC_PRESET should render pydantic for class 1`] = `
"class Test(BaseModel):
prop: Optional[str] = Field(description='''test
Expand Down

0 comments on commit da209b0

Please sign in to comment.