Skip to content

Commit 9d9e32e

Browse files
committed
refactor!: remove deprecated elements (#703)f
1 parent c7a7b44 commit 9d9e32e

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,
@@ -116,7 +114,7 @@ class BaseFactory(ABC, Generic[T]):
116114
The model for the factory.
117115
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.
118116
"""
119-
__check_model__: bool = False
117+
__check_model__: bool = True
120118
"""
121119
Flag dictating whether to check if fields defined on the factory exists on the model or not.
122120
If 'True', checks will be done against Use, PostGenerated, Ignore, Require constructs fields only.
@@ -202,7 +200,7 @@ class BaseFactory(ABC, Generic[T]):
202200
_extra_providers: dict[Any, Callable[[], Any]] | None = None
203201
"""Used to copy providers from once base factory to another dynamically generated factory for a class"""
204202

205-
def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: # noqa: C901, PLR0912
203+
def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
206204
super().__init_subclass__(*args, **kwargs)
207205

208206
if not hasattr(BaseFactory, "_base_factories"):
@@ -216,36 +214,10 @@ def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: # noqa: C901, PL
216214

217215
if cls.__min_collection_length__ > cls.__max_collection_length__:
218216
msg = "Minimum collection length shouldn't be greater than maximum collection length"
219-
raise ConfigurationException(
220-
msg,
221-
)
217+
raise ConfigurationException(msg)
222218

223219
if "__is_base_factory__" not in cls.__dict__ or not cls.__is_base_factory__:
224-
model: type[T] | None = getattr(cls, "__model__", None) or cls._infer_model_type()
225-
if not model:
226-
msg = f"required configuration attribute '__model__' is not set on {cls.__name__}"
227-
raise ConfigurationException(
228-
msg,
229-
)
230-
cls.__model__ = model
231-
if not cls.is_supported_type(model):
232-
for factory in BaseFactory._base_factories:
233-
if factory.is_supported_type(model):
234-
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__}"
235-
raise ConfigurationException(
236-
msg,
237-
)
238-
msg = f"Model type {model.__name__} is not supported. To support it, register an appropriate base factory and subclass it for your factory."
239-
raise ConfigurationException(
240-
msg,
241-
)
242-
if is_attribute_overridden(BaseFactory, cls, "__check_model__"):
243-
warn_deprecation(
244-
"v2.22.0",
245-
deprecated_name="__check_model__",
246-
kind="default",
247-
alternative="set to `False` explicitly to keep existing behaviour",
248-
)
220+
cls._init_model()
249221
if cls.__check_model__:
250222
cls._check_declared_fields_exist_in_model()
251223
else:
@@ -258,6 +230,27 @@ def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: # noqa: C901, PL
258230
if cls.__set_as_default_factory_for_type__ and hasattr(cls, "__model__"):
259231
BaseFactory._factory_type_mapping[cls.__model__] = cls
260232

233+
@classmethod
234+
def _init_model(cls) -> None:
235+
model: type[T] | None = getattr(cls, "__model__", None) or cls._infer_model_type()
236+
if not model:
237+
msg = f"required configuration attribute '__model__' is not set on {cls.__name__}"
238+
raise ConfigurationException(
239+
msg,
240+
)
241+
cls.__model__ = model
242+
if not cls.is_supported_type(model):
243+
for factory in BaseFactory._base_factories:
244+
if factory.is_supported_type(model):
245+
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__}"
246+
raise ConfigurationException(
247+
msg,
248+
)
249+
msg = f"Model type {model.__name__} is not supported. To support it, register an appropriate base factory and subclass it for your factory."
250+
raise ConfigurationException(
251+
msg,
252+
)
253+
261254
@classmethod
262255
def _get_build_context(cls, build_context: BuildContext | None) -> BuildContext:
263256
"""Return a BuildContext instance.
@@ -323,7 +316,7 @@ def _get_async_persistence(cls) -> AsyncPersistenceProtocol[T]:
323316
)
324317

325318
@classmethod
326-
def _handle_factory_field( # noqa: PLR0911
319+
def _handle_factory_field(
327320
cls,
328321
field_value: Any,
329322
build_context: BuildContext,
@@ -350,9 +343,6 @@ def _handle_factory_field( # noqa: PLR0911
350343
if isinstance(field_value, Use):
351344
return field_value.to_value()
352345

353-
if isinstance(field_value, Fixture):
354-
return field_value.to_value()
355-
356346
if callable(field_value):
357347
return field_value()
358348

@@ -387,9 +377,6 @@ def _handle_factory_field_coverage(
387377
if isinstance(field_value, Use):
388378
return field_value.to_value()
389379

390-
if isinstance(field_value, Fixture):
391-
return CoverageContainerCallable(field_value.to_value)
392-
393380
return CoverageContainerCallable(field_value) if callable(field_value) else field_value
394381

395382
@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.normalize_type import normalize_type
2019
from polyfactory.utils.predicates import is_annotated, is_optional, is_safe_subclass, is_union
@@ -90,7 +89,6 @@
9089

9190
if TYPE_CHECKING:
9291
from collections import abc
93-
from random import Random
9492
from typing import Callable, Sequence
9593

9694
from typing_extensions import NotRequired, TypeGuard
@@ -120,7 +118,6 @@ def __init__(
120118
*,
121119
name: str,
122120
annotation: type,
123-
random: Random | None = None,
124121
default: Any = ...,
125122
children: list[FieldMeta] | None = None,
126123
constraints: PydanticConstraints | None = None,
@@ -129,7 +126,6 @@ def __init__(
129126
super().__init__(
130127
name=name,
131128
annotation=annotation,
132-
random=random,
133129
default=default,
134130
children=children,
135131
constraints=constraints,
@@ -142,32 +138,15 @@ def from_field_info(
142138
field_name: str,
143139
field_info: FieldInfo,
144140
use_alias: bool,
145-
random: Random | None = None,
146-
randomize_collection_length: bool | None = None,
147-
min_collection_length: int | None = None,
148-
max_collection_length: int | None = None,
149141
) -> PydanticFieldMeta:
150142
"""Create an instance from a pydantic field info.
151143
152144
:param field_name: The name of the field.
153145
:param field_info: A pydantic FieldInfo instance.
154146
:param use_alias: Whether to use the field alias.
155-
:param random: A random.Random instance.
156-
:param randomize_collection_length: Whether to randomize collection length.
157-
:param min_collection_length: Minimum collection length.
158-
:param max_collection_length: Maximum collection length.
159147
160148
:returns: A PydanticFieldMeta instance.
161149
"""
162-
check_for_deprecated_parameters(
163-
"2.11.0",
164-
parameters=(
165-
("randomize_collection_length", randomize_collection_length),
166-
("min_collection_length", min_collection_length),
167-
("max_collection_length", max_collection_length),
168-
("random", random),
169-
),
170-
)
171150
field_info = FieldInfo.merge_field_infos(
172151
field_info, FieldInfo.from_annotation(normalize_type(field_info.annotation))
173152
)
@@ -240,32 +219,14 @@ def from_model_field( # pragma: no cover
240219
cls,
241220
model_field: ModelField, # pyright: ignore[reportGeneralTypeIssues]
242221
use_alias: bool,
243-
randomize_collection_length: bool | None = None,
244-
min_collection_length: int | None = None,
245-
max_collection_length: int | None = None,
246-
random: Random | None = None,
247222
) -> PydanticFieldMeta:
248223
"""Create an instance from a pydantic model field.
249224
:param model_field: A pydantic ModelField.
250225
:param use_alias: Whether to use the field alias.
251-
:param randomize_collection_length: A boolean flag whether to randomize collections lengths
252-
:param min_collection_length: Minimum number of elements in randomized collection
253-
:param max_collection_length: Maximum number of elements in randomized collection
254-
:param random: An instance of random.Random.
255226
256227
:returns: A PydanticFieldMeta instance.
257228
258229
"""
259-
check_for_deprecated_parameters(
260-
"2.11.0",
261-
parameters=(
262-
("randomize_collection_length", randomize_collection_length),
263-
("min_collection_length", min_collection_length),
264-
("max_collection_length", max_collection_length),
265-
("random", random),
266-
),
267-
)
268-
269230
if model_field.default is not Undefined:
270231
default_value = model_field.default
271232
elif callable(model_field.default_factory):
@@ -410,8 +371,9 @@ class PaymentFactory(ModelFactory[Payment]):
410371
"__use_examples__",
411372
)
412373

413-
def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None:
414-
super().__init_subclass__(*args, **kwargs)
374+
@classmethod
375+
def _init_model(cls) -> None:
376+
super()._init_model()
415377

416378
model = getattr(cls, "__model__", None)
417379
if model is None:

0 commit comments

Comments
 (0)