Search code examples
pythonfactory-boy

Reset Factory Iterator in Factoryboy


Since the factory assigns the value to the factory attribute it's not possible to call reset on it.

This however works:

CODE2_ITERATOR = Iterator(['PH', 'CN', 'SE', 'ES', 'DK' ])

class CountryFactory(DjangoModelFactory):
    class Meta:
    model = Country

    name = 'The Philippines'
    code2 = CODE2_ITERATOR
    phone = "63"

Then in your tearDown method:

def tearDown(self):
    CODE2_ITERATOR.reset()

But surely there must be a better way to do this?


Solution

  • The field declaration stays available through the class:

    CountryFactory.code2.reset()
    

    You can also access the declaration objects of a factory through the class' _meta attribute:

    CountryFactory._meta.declarations['code2'].reset()