Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make _setup_next_sequence usable with DictFactory subclasses #1056

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions factory/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,8 +664,23 @@ def create(cls, **kwargs):
raise errors.UnsupportedStrategy()


class DictFactoryOptions(FactoryOptions):

def _get_counter_reference(self):
"""Identify which factory should be used for a shared counter."""

# When _setup_next_sequence is overridden in the factory, it should get a new counter
if '_setup_next_sequence' in self.factory.__dict__:
return self
else:
return super()._get_counter_reference()


class BaseDictFactory(Factory):
"""Factory for dictionary-like classes."""

_options_class = DictFactoryOptions

class Meta:
abstract = True

Expand Down
34 changes: 34 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,40 @@ class Meta:
self.assertEqual(enums.CREATE_STRATEGY, TestModelFactory._meta.strategy)


class DictFactoryTestCase(unittest.TestCase):
def setUp(self):
super().setUp()
pet_sequence_offset = 10

class Pet(base.DictFactory):
@classmethod
def _setup_next_sequence(cls) -> int:
return pet_sequence_offset

pet_id = declarations.Sequence(lambda n: n)

class Cat(Pet):
pass

class Dog(Pet):
pass

self.Pet = Pet
self.Cat = Cat
self.Dog = Dog
self.pet_sequence_offset = pet_sequence_offset

def test_override_setup_next_sequence(self):
result = self.Pet()
self.assertEqual(result['pet_id'], self.pet_sequence_offset)

def test_descendants_share_counter(self):
cat_result = self.Cat()
dog_result = self.Dog()
results = [cat_result['pet_id'], dog_result['pet_id']]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure why this list is necessary? Why not directly assert the cat_result['pet_id'] and dog_result['pet_id'] ?

self.assertEqual(results, [self.pet_sequence_offset, self.pet_sequence_offset + 1])


class FactoryCreationTestCase(unittest.TestCase):
def test_factory_for(self):
class TestFactory(base.Factory):
Expand Down