Skip to content

Commit

Permalink
fix: Adjust min/max items to valid lengths for Set[Enum] fields
Browse files Browse the repository at this point in the history
For `Set[Enum]` fields with a limited maximum length, adjust `min_items`
and `max_items` to be within the range of valid lengths.
  • Loading branch information
adrianeboyd committed Jul 19, 2024
1 parent 67c5720 commit 7cd5a7e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
6 changes: 6 additions & 0 deletions polyfactory/value_generators/constrained_collections.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from enum import EnumMeta
from typing import TYPE_CHECKING, Any, Callable, List, Mapping, TypeVar, cast

from polyfactory.exceptions import ParameterException
Expand Down Expand Up @@ -39,6 +40,11 @@ def handle_constrained_collection(
min_items = abs(min_items if min_items is not None else (max_items or 0))
max_items = abs(max_items if max_items is not None else min_items + 1)

if isinstance(field_meta.annotation, EnumMeta):
max_items = len(field_meta.annotation)
if min_items > max_items:
min_items = max_items

if max_items < min_items:
msg = "max_items must be larger or equal to min_items"
raise ParameterException(msg)
Expand Down
19 changes: 19 additions & 0 deletions tests/test_complex_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,25 @@ class MyFactory(ModelFactory):
assert result.animal_list


def test_complex_typing_with_enum_set() -> None:
class Animal(str, Enum):
DOG = "Dog"
CAT = "Cat"
MONKEY = "Monkey"

class MyModel(BaseModel):
animal_list: Set[Animal]

class MyFactory(ModelFactory):
__model__ = MyModel
__randomize_collection_length__ = True
__min_collection_length__ = len(Animal) + 1
__min_collection_length__ = len(Animal) + 2

result = MyFactory.build()
assert len(result.animal_list) == len(Animal)


def test_union_literal() -> None:
class MyModel(BaseModel):
x: Union[int, Literal["a", "b", "c"]]
Expand Down

0 comments on commit 7cd5a7e

Please sign in to comment.