I'm getting an error building factories with subfactories to test django models. With models:
class Space(ExportModelOperationsMixin('space'), models.Model):
name = models.CharField(max_length=128, default='Default')
class ShoppingListEntry(models.Model):
food = models.ForeignKey(Food)
space = models.ForeignKey(Space)
class Food(models.Model):
name = models.CharField(max_length=128)
description = models.TextField(default='', blank=True)
space = models.ForeignKey(Space)
and fixtures:
class SpaceFactory(factory.django.DjangoModelFactory):
name = factory.LazyAttribute(lambda x: faker.word())
class FoodFactory(factory.django.DjangoModelFactory):
name = factory.LazyAttribute(lambda x: faker.sentence(nb_words=3))
description = factory.LazyAttribute(lambda x: faker.sentence(nb_words=10))
space = factory.SubFactory(SpaceFactory)
class ShoppingListEntryFactory(factory.django.DjangoModelFactory):
food = factory.SubFactory(FoodFactory, space=factory.SelfAttribute('..space'))
space = factory.SubFactory(SpaceFactory)
and test
register(SpaceFactory, 'space_1')
register(ShoppingListEntryFactory, 'shopping_list_entry', space=LazyFixture('space_1'))
def test_list_space(shopping_list_entry):
assert 1 == 1
throws the following error
Failed with Error: [undefined]failed on setup with
def test_list_space(sle_1):
file <string>, line 2: source code not available
file <string>, line 2: source code not available
E fixture 'food__name' not found
I'm struggling to figure out how to troubleshoot this.
Replacing the register factory register(ShoppingListEntryFactory, ...) with a pytest fixture resolved the issue.
@pytest.fixture
def shopping_list_entry(space_1):
return ShoppingListEntryFactory.create(space=space_1)