Skip to content

Commit

Permalink
Fix optional field doesn't include None (#1411)
Browse files Browse the repository at this point in the history
* Fix optional field doesn't include `None`

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
koxudaxi and pre-commit-ci[bot] authored Jul 6, 2023
1 parent 5d44bf2 commit f172a5a
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class {{ class_name }}({{ base_class }}):{% if comment is defined %} # {{ comme
{%- else %}
{{ field.name }}: {{ field.type_hint }}
{%- endif %}
{%- if not (field.required or (field.represented_default == 'None' and field.strip_default_none))
{%- if not field.required or field.data_type.is_optional or field.nullable
%} = {{ field.represented_default }}
{%- endif -%}
{%- endif %}
Expand Down
17 changes: 17 additions & 0 deletions tests/data/expected/main/main_null_and_array_v2/output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# generated by datamodel-codegen:
# filename: null_and_array.json
# timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Any, List, Optional

from pydantic import BaseModel


class MyObjItem(BaseModel):
items: Optional[List[Any]] = None


class Model(BaseModel):
my_obj: List[MyObjItem]
19 changes: 17 additions & 2 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,8 +432,21 @@ def test_main_json_array_include_null():
)


@pytest.mark.parametrize(
'output_model,expected_output',
[
(
'pydantic.BaseModel',
'main_null_and_array',
),
(
'pydantic_v2.BaseModel',
'main_null_and_array_v2',
),
],
)
@freeze_time('2019-07-26')
def test_main_null_and_array():
def test_main_null_and_array(output_model, expected_output):
with TemporaryDirectory() as output_dir:
output_file: Path = Path(output_dir) / 'output.py'
return_code: Exit = main(
Expand All @@ -444,12 +457,14 @@ def test_main_null_and_array():
str(output_file),
'--input-file-type',
'jsonschema',
'--output-model',
output_model,
]
)
assert return_code == Exit.OK
assert (
output_file.read_text()
== (EXPECTED_MAIN_PATH / 'main_null_and_array' / 'output.py').read_text()
== (EXPECTED_MAIN_PATH / expected_output / 'output.py').read_text()
)


Expand Down

0 comments on commit f172a5a

Please sign in to comment.