Skip to content

Commit 1eaede1

Browse files
authored
refactor!: remove deprecated elements (#703)f
1 parent d03aa1b commit 1eaede1

File tree

17 files changed

+60
-412
lines changed

17 files changed

+60
-412
lines changed

docs/examples/library_factories/sqlalchemy_factory/test_example_2.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,16 @@ class Book(Base):
2828
class AuthorFactory(SQLAlchemyFactory[Author]): ...
2929

3030

31-
class AuthorFactoryWithRelationship(SQLAlchemyFactory[Author]):
32-
__set_relationships__ = True
31+
class AuthorFactoryWithoutRelationship(SQLAlchemyFactory[Author]):
32+
__set_relationships__ = False
3333

3434

3535
def test_sqla_factory() -> None:
3636
author = AuthorFactory.build()
37-
assert author.books == []
38-
39-
40-
def test_sqla_factory_with_relationship() -> None:
41-
author = AuthorFactoryWithRelationship.build()
4237
assert isinstance(author, Author)
4338
assert isinstance(author.books[0], Book)
39+
40+
41+
def test_sqla_factory_without_relationship() -> None:
42+
author = AuthorFactoryWithoutRelationship.build()
43+
assert author.books == []

docs/examples/library_factories/sqlalchemy_factory/test_example_association_proxy.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@ class Keyword(Base):
4141
keyword: Mapped[str]
4242

4343

44-
class UserFactory(SQLAlchemyFactory[User]): ...
44+
class UserFactory(SQLAlchemyFactory[User]):
45+
__set_relationships__ = False
46+
__set_association_proxy__ = False
4547

4648

4749
class UserFactoryWithAssociation(SQLAlchemyFactory[User]):

docs/usage/library_factories/sqlalchemy_factory.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ SQLAlchemyFactory allows to override some configuration attributes so that a des
1919
Relationship
2020
++++++++++++
2121

22-
By default, ``__set_relationships__`` is set to ``False``. If it is ``True``, all fields with the SQLAlchemy `relationship() <relationship()_>`_ will be included in the result created by ``build`` method.
22+
By default, ``__set_relationships__`` is set to ``True``. If it is ``True``, all fields with the SQLAlchemy `relationship() <relationship()_>`_ will be included in the result created by ``build`` method.
2323

2424
.. literalinclude:: /examples/library_factories/sqlalchemy_factory/test_example_2.py
2525
:caption: Setting relationships
@@ -34,7 +34,7 @@ By default, ``__set_relationships__`` is set to ``False``. If it is ``True``, al
3434
Association Proxy
3535
+++++++++++++++++
3636

37-
By default, ``__set_association_proxy__`` is set to ``False``. If it is ``True``, all SQLAlchemy fields mapped to ORM `Association Proxy <Association Proxy_>`_ class will be included in the result created by ``build`` method.
37+
By default, ``__set_association_proxy__`` is set to ``True``. If it is ``True``, all SQLAlchemy fields mapped to ORM `Association Proxy <Association Proxy_>`_ class will be included in the result created by ``build`` method.
3838

3939
.. literalinclude:: /examples/library_factories/sqlalchemy_factory/test_example_association_proxy.py
4040
:caption: Setting association_proxy

polyfactory/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
from .exceptions import ConfigurationException
22
from .factories import BaseFactory
3-
from .fields import Fixture, Ignore, PostGenerated, Require, Use
3+
from .fields import Ignore, PostGenerated, Require, Use
44
from .persistence import AsyncPersistenceProtocol, SyncPersistenceProtocol
55

66
__all__ = (
77
"AsyncPersistenceProtocol",
88
"BaseFactory",
99
"ConfigurationException",
10-
"Fixture",
1110
"Ignore",
1211
"PostGenerated",
1312
"Require",

polyfactory/collection_extender.py

Lines changed: 0 additions & 91 deletions
This file was deleted.

polyfactory/factories/base.py

Lines changed: 27 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,7 @@
5454
)
5555
from polyfactory.exceptions import ConfigurationException, MissingBuildKwargException, ParameterException
5656
from polyfactory.field_meta import Null
57-
from polyfactory.fields import Fixture, Ignore, PostGenerated, Require, Use
58-
from polyfactory.utils._internal import is_attribute_overridden
59-
from polyfactory.utils.deprecation import warn_deprecation
57+
from polyfactory.fields import Ignore, PostGenerated, Require, Use
6058
from polyfactory.utils.helpers import (
6159
flatten_annotation,
6260
get_collection_type,
@@ -109,7 +107,7 @@ class BaseFactory(ABC, Generic[T]):
109107
The model for the factory.
110108
This attribute is required for non-base factories and an exception will be raised if it's not set. Can be automatically inferred from the factory generic argument.
111109
"""
112-
__check_model__: bool = False
110+
__check_model__: bool = True
113111
"""
114112
Flag dictating whether to check if fields defined on the factory exists on the model or not.
115113
If 'True', checks will be done against Use, PostGenerated, Ignore, Require constructs fields only.
@@ -195,7 +193,7 @@ class BaseFactory(ABC, Generic[T]):
195193
_extra_providers: dict[Any, Callable[[], Any]] | None = None
196194
"""Used to copy providers from once base factory to another dynamically generated factory for a class"""
197195

198-
def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: # noqa: C901, PLR0912
196+
def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
199197
super().__init_subclass__(*args, **kwargs)
200198

201199
if not hasattr(BaseFactory, "_base_factories"):
@@ -209,36 +207,10 @@ def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: # noqa: C901, PL
209207

210208
if cls.__min_collection_length__ > cls.__max_collection_length__:
211209
msg = "Minimum collection length shouldn't be greater than maximum collection length"
212-
raise ConfigurationException(
213-
msg,
214-
)
210+
raise ConfigurationException(msg)
215211

216212
if "__is_base_factory__" not in cls.__dict__ or not cls.__is_base_factory__:
217-
model: type[T] | None = getattr(cls, "__model__", None) or cls._infer_model_type()
218-
if not model:
219-
msg = f"required configuration attribute '__model__' is not set on {cls.__name__}"
220-
raise ConfigurationException(
221-
msg,
222-
)
223-
cls.__model__ = model
224-
if not cls.is_supported_type(model):
225-
for factory in BaseFactory._base_factories:
226-
if factory.is_supported_type(model):
227-
msg = f"{cls.__name__} does not support {model.__name__}, but this type is supported by the {factory.__name__} base factory class. To resolve this error, subclass the factory from {factory.__name__} instead of {cls.__name__}"
228-
raise ConfigurationException(
229-
msg,
230-
)
231-
msg = f"Model type {model.__name__} is not supported. To support it, register an appropriate base factory and subclass it for your factory."
232-
raise ConfigurationException(
233-
msg,
234-
)
235-
if is_attribute_overridden(BaseFactory, cls, "__check_model__"):
236-
warn_deprecation(
237-
"v2.22.0",
238-
deprecated_name="__check_model__",
239-
kind="default",
240-
alternative="set to `False` explicitly to keep existing behaviour",
241-
)
213+
cls._init_model()
242214
if cls.__check_model__:
243215
cls._check_declared_fields_exist_in_model()
244216
else:
@@ -251,6 +223,27 @@ def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: # noqa: C901, PL
251223
if cls.__set_as_default_factory_for_type__ and hasattr(cls, "__model__"):
252224
BaseFactory._factory_type_mapping[cls.__model__] = cls
253225

226+
@classmethod
227+
def _init_model(cls) -> None:
228+
model: type[T] | None = getattr(cls, "__model__", None) or cls._infer_model_type()
229+
if not model:
230+
msg = f"required configuration attribute '__model__' is not set on {cls.__name__}"
231+
raise ConfigurationException(
232+
msg,
233+
)
234+
cls.__model__ = model
235+
if not cls.is_supported_type(model):
236+
for factory in BaseFactory._base_factories:
237+
if factory.is_supported_type(model):
238+
msg = f"{cls.__name__} does not support {model.__name__}, but this type is supported by the {factory.__name__} base factory class. To resolve this error, subclass the factory from {factory.__name__} instead of {cls.__name__}"
239+
raise ConfigurationException(
240+
msg,
241+
)
242+
msg = f"Model type {model.__name__} is not supported. To support it, register an appropriate base factory and subclass it for your factory."
243+
raise ConfigurationException(
244+
msg,
245+
)
246+
254247
@classmethod
255248
def _get_build_context(cls, build_context: BuildContext | None) -> BuildContext:
256249
"""Return a BuildContext instance.
@@ -316,7 +309,7 @@ def _get_async_persistence(cls) -> AsyncPersistenceProtocol[T]:
316309
)
317310

318311
@classmethod
319-
def _handle_factory_field( # noqa: PLR0911
312+
def _handle_factory_field(
320313
cls,
321314
field_value: Any,
322315
build_context: BuildContext,
@@ -343,9 +336,6 @@ def _handle_factory_field( # noqa: PLR0911
343336
if isinstance(field_value, Use):
344337
return field_value.to_value()
345338

346-
if isinstance(field_value, Fixture):
347-
return field_value.to_value()
348-
349339
if callable(field_value):
350340
return field_value()
351341

@@ -380,9 +370,6 @@ def _handle_factory_field_coverage(
380370
if isinstance(field_value, Use):
381371
return field_value.to_value()
382372

383-
if isinstance(field_value, Fixture):
384-
return CoverageContainerCallable(field_value.to_value)
385-
386373
return CoverageContainerCallable(field_value) if callable(field_value) else field_value
387374

388375
@classmethod

polyfactory/factories/pydantic_factory.py

Lines changed: 3 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from polyfactory.factories.base import BaseFactory, BuildContext
1515
from polyfactory.factories.base import BuildContext as BaseBuildContext
1616
from polyfactory.field_meta import Constraints, FieldMeta, Null
17-
from polyfactory.utils.deprecation import check_for_deprecated_parameters
1817
from polyfactory.utils.helpers import unwrap_new_type, unwrap_optional
1918
from polyfactory.utils.predicates import is_optional, is_safe_subclass, is_union
2019
from polyfactory.utils.types import NoneType
@@ -89,7 +88,6 @@
8988

9089
if TYPE_CHECKING:
9190
from collections import abc
92-
from random import Random
9391
from typing import Callable, Sequence
9492

9593
from typing_extensions import NotRequired, TypeGuard
@@ -119,7 +117,6 @@ def __init__(
119117
*,
120118
name: str,
121119
annotation: type,
122-
random: Random | None = None,
123120
default: Any = ...,
124121
children: list[FieldMeta] | None = None,
125122
constraints: PydanticConstraints | None = None,
@@ -128,7 +125,6 @@ def __init__(
128125
super().__init__(
129126
name=name,
130127
annotation=annotation,
131-
random=random,
132128
default=default,
133129
children=children,
134130
constraints=constraints,
@@ -141,32 +137,15 @@ def from_field_info(
141137
field_name: str,
142138
field_info: FieldInfo,
143139
use_alias: bool,
144-
random: Random | None = None,
145-
randomize_collection_length: bool | None = None,
146-
min_collection_length: int | None = None,
147-
max_collection_length: int | None = None,
148140
) -> PydanticFieldMeta:
149141
"""Create an instance from a pydantic field info.
150142
151143
:param field_name: The name of the field.
152144
:param field_info: A pydantic FieldInfo instance.
153145
:param use_alias: Whether to use the field alias.
154-
:param random: A random.Random instance.
155-
:param randomize_collection_length: Whether to randomize collection length.
156-
:param min_collection_length: Minimum collection length.
157-
:param max_collection_length: Maximum collection length.
158146
159147
:returns: A PydanticFieldMeta instance.
160148
"""
161-
check_for_deprecated_parameters(
162-
"2.11.0",
163-
parameters=(
164-
("randomize_collection_length", randomize_collection_length),
165-
("min_collection_length", min_collection_length),
166-
("max_collection_length", max_collection_length),
167-
("random", random),
168-
),
169-
)
170149
if callable(field_info.default_factory):
171150
default_value = field_info.default_factory
172151
else:
@@ -228,32 +207,14 @@ def from_model_field( # pragma: no cover
228207
cls,
229208
model_field: ModelField, # pyright: ignore[reportGeneralTypeIssues]
230209
use_alias: bool,
231-
randomize_collection_length: bool | None = None,
232-
min_collection_length: int | None = None,
233-
max_collection_length: int | None = None,
234-
random: Random | None = None,
235210
) -> PydanticFieldMeta:
236211
"""Create an instance from a pydantic model field.
237212
:param model_field: A pydantic ModelField.
238213
:param use_alias: Whether to use the field alias.
239-
:param randomize_collection_length: A boolean flag whether to randomize collections lengths
240-
:param min_collection_length: Minimum number of elements in randomized collection
241-
:param max_collection_length: Maximum number of elements in randomized collection
242-
:param random: An instance of random.Random.
243214
244215
:returns: A PydanticFieldMeta instance.
245216
246217
"""
247-
check_for_deprecated_parameters(
248-
"2.11.0",
249-
parameters=(
250-
("randomize_collection_length", randomize_collection_length),
251-
("min_collection_length", min_collection_length),
252-
("max_collection_length", max_collection_length),
253-
("random", random),
254-
),
255-
)
256-
257218
if model_field.default is not Undefined:
258219
default_value = model_field.default
259220
elif callable(model_field.default_factory):
@@ -392,8 +353,9 @@ class PaymentFactory(ModelFactory[Payment]):
392353
"__use_examples__",
393354
)
394355

395-
def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
396-
super().__init_subclass__(*args, **kwargs)
356+
@classmethod
357+
def _init_model(cls) -> None:
358+
super()._init_model()
397359

398360
model = getattr(cls, "__model__", None)
399361
if model is None:

0 commit comments

Comments
 (0)