Skip to content

Commit

Permalink
feat: copy mutable args (#529)
Browse files Browse the repository at this point in the history
Co-authored-by: guacs <126393040+guacs@users.noreply.github.com>
  • Loading branch information
adhtruong and guacs committed May 12, 2024
1 parent 3da64f6 commit e4695a7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
8 changes: 6 additions & 2 deletions polyfactory/factories/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
ClassVar,
Collection,
Generic,
Hashable,
Iterable,
Mapping,
Sequence,
Expand Down Expand Up @@ -289,7 +290,7 @@ def _get_async_persistence(cls) -> AsyncPersistenceProtocol[T]:
)

@classmethod
def _handle_factory_field(
def _handle_factory_field( # noqa: PLR0911
cls,
field_value: Any,
build_context: BuildContext,
Expand Down Expand Up @@ -319,7 +320,10 @@ def _handle_factory_field(
if isinstance(field_value, Fixture):
return field_value.to_value()

return field_value() if callable(field_value) else field_value
if callable(field_value):
return field_value()

return field_value if isinstance(field_value, Hashable) else copy.deepcopy(field_value)

@classmethod
def _handle_factory_field_coverage(
Expand Down
19 changes: 18 additions & 1 deletion tests/test_factory_fields.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import random
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any, Optional, Union
from typing import Any, ClassVar, List, Optional, Union

import pytest

from pydantic import BaseModel

from polyfactory.decorators import post_generated
from polyfactory.exceptions import ConfigurationException, MissingBuildKwargException
from polyfactory.factories.dataclass_factory import DataclassFactory
from polyfactory.factories.pydantic_factory import ModelFactory
from polyfactory.fields import Ignore, PostGenerated, Require, Use

Expand Down Expand Up @@ -202,3 +204,18 @@ class NoFieldModel(BaseModel):
match="unknown_field is declared on the factory NoFieldModelFactory but it is not part of the model NoFieldModel",
):
ModelFactory.create_factory(NoFieldModel, bases=None, __check_model__=True, unknown_field=factory_field)


def test_mutable_defaults() -> None:
@dataclass
class A:
a: List[str]

class AFactory(DataclassFactory[A]):
a: ClassVar[List[str]] = []

AFactory.build().a.append("a")
assert AFactory.build().a == []

next(iter(AFactory.coverage())).a.append("value")
assert next(iter(AFactory.coverage())).a == []

0 comments on commit e4695a7

Please sign in to comment.