Skip to content

Commit 01a864c

Browse files
instanceofmelfrancoisfreitag
authored andcommitted
Allow functions as FactoryOptions.model
Facilitates the use of a factory function, that may create several related objects at once.
1 parent d6349de commit 01a864c

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

docs/changelog.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ ChangeLog
1616

1717
- :issue:`1031`: Do not require :attr:`~factory.alchemy.SQLAlchemyOptions.sqlalchemy_session` when
1818
:attr:`~factory.alchemy.SQLAlchemyOptions.sqlalchemy_session_factory` is provided.
19+
- :issue:`1072`: Allow using functions as models for a :attr:`~factory.FactoryOptions.model`.
1920

2021
*Removed:*
2122

factory/base.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33

44
import collections
5+
import inspect
56
import logging
67
import warnings
78
from typing import Generic, List, Type, TypeVar
@@ -243,6 +244,7 @@ def _get_counter_reference(self):
243244
if (self.model is not None
244245
and self.base_factory is not None
245246
and self.base_factory._meta.model is not None
247+
and inspect.isclass(self.model)
246248
and issubclass(self.model, self.base_factory._meta.model)):
247249
return self.base_factory._meta.counter_reference
248250
else:

tests/test_base.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,22 @@ class Meta:
281281
ones = {x.one for x in (parent, alt_parent, sub, alt_sub)}
282282
self.assertEqual(4, len(ones))
283283

284+
def test_inheritance_with_function_as_meta_model(self):
285+
def make_test_object(**kwargs):
286+
return TestObject(**kwargs)
287+
288+
class TestObjectFactory(base.Factory):
289+
class Meta:
290+
model = make_test_object
291+
292+
one = "foo"
293+
294+
class TestSubFactory(TestObjectFactory):
295+
one = "bar"
296+
297+
sub = TestSubFactory.build()
298+
self.assertEqual(sub.one, "bar")
299+
284300

285301
class FactorySequenceTestCase(unittest.TestCase):
286302
def setUp(self):

0 commit comments

Comments
 (0)