Skip to content

Commit

Permalink
fix: ValueError: mutable default <class 'list'> for field x is not al…
Browse files Browse the repository at this point in the history
…lowed: use default_factory
  • Loading branch information
Florian Bezannier committed Nov 18, 2023
1 parent eb62751 commit aafa50d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/autofaker/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,14 @@ def __init__(self, cls, use_fake_data: bool = False):
self.cls = cls

def generate(self):
args = []
fields = dataclasses.fields(self.cls)
for field in fields:
params = {}
for dataclass_field in fields:
generator = TypeDataGenerator.create(
field.type, field.name, use_fake_data=self.use_fake_data
dataclass_field.type, dataclass_field.name, use_fake_data=self.use_fake_data
)
args.append((field.name, field.type, generator.generate()))
name = self.cls.__module__ + "." + self.cls.__qualname__
instance = dataclasses.make_dataclass(name, args)
params[dataclass_field.name] = generator.generate()
instance = self.cls(**params)
return instance


Expand Down
4 changes: 4 additions & 0 deletions tests/test_create_anonymous_data_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
class DataClass:
id: int
text: str
list_of_str: list[str]
list_of_int: list[int]


class AnonymousDataClassTestCase(unittest.TestCase):
Expand All @@ -28,6 +30,8 @@ def test_create_many_data_class_returns_dataclass(self):
data = Autodata.create(DataClass)
self.assertNotEqual(0, data.id)
self.assertNotEqual("", data.text)
self.assertNotEqual("", data.list_of_str[0])
self.assertNotEqual(0, data.list_of_int[0])


@dataclass
Expand Down

0 comments on commit aafa50d

Please sign in to comment.