Skip to content

Commit b479e4a

Browse files
authored
fix: flatten_annotation behaviour for Optional (#440)
1 parent 1407f07 commit b479e4a

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

polyfactory/utils/helpers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,8 @@ def flatten_annotation(annotation: Any) -> list[Any]:
9494
if is_new_type(annotation):
9595
flat.extend(flatten_annotation(unwrap_new_type(annotation)))
9696
elif is_optional(annotation):
97-
flat.append(NoneType)
98-
flat.extend(flatten_annotation(arg) for arg in get_args(annotation) if arg not in (NoneType, None))
97+
for a in get_args(annotation):
98+
flat.extend(flatten_annotation(a))
9999
elif is_annotated(annotation):
100100
flat.extend(flatten_annotation(get_args(annotation)[0]))
101101
elif is_union(annotation):

tests/test_type_coverage_generation.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from dataclasses import dataclass, make_dataclass
55
from datetime import date
6-
from typing import Dict, FrozenSet, List, Literal, Set, Tuple, Union
6+
from typing import Dict, FrozenSet, List, Literal, Optional, Set, Tuple, Union
77
from uuid import UUID
88

99
import pytest
@@ -212,3 +212,18 @@ class Factory(DataclassFactory[Model]):
212212

213213
with pytest.raises(ParameterException):
214214
list(Factory.coverage())
215+
216+
217+
def test_coverage_optional_field() -> None:
218+
@dataclass
219+
class OptionalInt:
220+
i: Optional[int]
221+
222+
class OptionalIntFactory(DataclassFactory[OptionalInt]):
223+
__model__ = OptionalInt
224+
225+
results = list(OptionalIntFactory.coverage())
226+
assert len(results) == 2
227+
228+
assert isinstance(results[0].i, int)
229+
assert results[1].i is None

0 commit comments

Comments
 (0)