Search code examples
djangodjango-modelsdjango-rest-frameworkpytestfactory-boy

Cannot generate instances of abstract factory UserFactory ( Factory boy)


factory.errors.FactoryError: Cannot generate instances of abstract factory UserFactory; Ensure UserFactory.Meta.model is set and UserFactory.Meta.abstract is either not set or False. Im using factory boy library To test my functions

my class UserFactory Here UserFactory image

import factory
import factory.django
from users.models import Users
from django.contrib.auth.hashers import make_password
from django.db import models   

     class UserFactory(factory.django.DjangoModelFactory):
        
            username = factory.Sequence(lambda n: f"user_{n:004}")
            email = factory.LazyAttribute(lambda user: f"{user.username}@example")
            password = factory.LazyFunction(make_password("password"))
        
            class Meta:
                model: Users
            abstract = True

Here Model User I'm inheritance from class abstract user User Class Image

from django.db import models

# Create your models here.
from django.contrib.auth.models import AbstractUser

class Users(AbstractUser):
    bio = models.CharField(max_length=256, blank=True)

I added class meta abstract and still not working


Solution

  • The error message says it all: factory_boy will only allow you to instantiate from a factory if said factory has a Meta.model and is not marked Meta.abstract = True.

    Typically, one would use:

    class MyFactory(...):
      class Meta:
        model = SomeModel
    

    In advanced cases, some projects might have abstract factories; in which case that abstractness must be disabled:

    class SomeAbstractFactory(...):
      class Meta:
        model = MyModel
        abstract = True
    
    class MyFactory(SomeAbstractFactory):
      class Meta:
        abstract = False
    

    In your code example, you have written model: User instead of model = User; it can easily be fixed with:

    class UserFactory(factory.django.DjangoModelFactory):
      class Meta:
        model = User
        # (No "abstract = " clause)