Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/assertical/fake/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,14 @@ def generate_class_instance( # noqa: C901
f"Type {t} has property {member.name} with type {member.declared_type} that cannot be generated"
)

if member.collection_type in (CollectionType.REQUIRED_DICT, CollectionType.OPTIONAL_DICT):
if member.second_type_to_generate is None and not (
optional_is_none and member.collection_type == CollectionType.OPTIONAL_DICT
):
raise Exception(
f"Type {t} has property {member.name} with type {member.declared_type} that cannot be generated"
)

generated_value: Any = None
empty_collection: bool = False
collection_type: Optional[CollectionType] = member.collection_type
Expand Down
21 changes: 20 additions & 1 deletion tests/fake/test_generator_dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys
from dataclasses import dataclass, field
from datetime import datetime, time
from typing import Generator, Optional
from typing import Any, Generator, Optional
from pathlib import Path

import pytest
Expand Down Expand Up @@ -104,6 +104,25 @@ class DataclassWithUngeneratableType:
generate_class_instance(DataclassWithUngeneratableType, optional_is_none=True)


def test_dataclass_with_ungeneratable_dict_value_type():
"""dict[str, Any] has an unresolvable value type - should raise a clear error, not crash cryptically."""

@dataclass
class DataclassWithUngeneratableDict:
d: dict[str, Any]

with pytest.raises(Exception, match="cannot be generated"):
generate_class_instance(DataclassWithUngeneratableDict, generate_relationships=True)

# Optional dict with optional_is_none=True should be bypassed (set to None) without raising
@dataclass
class DataclassWithOptionalUngeneratableDict:
d: Optional[dict[str, Any]]

result = generate_class_instance(DataclassWithOptionalUngeneratableDict, optional_is_none=True)
assert result.d is None


def test_collections_dataclass():
_ = generate_class_instance(CollectionsDataclass, seed=1, generate_relationships=True)

Expand Down
Loading