Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this alternative to the deprecated Factory.set_creation_function working with nosetests?

Factory Boy deprecated set_creation_function (see ChangeLog 2.6.1) and recommends that developers

Replace factory.set_creation_function(SomeFactory, creation_function) with an override of the _create() method of SomeFactory

I have i) a number of derivative factory classes and ii) my db session instantiated in another module so I tried replacing the working example from https://github.com/mattupstate/overholt with the second code block below. PyCharm is warning me that the "db" import is not being used, so I suspect it might not be being dereferenced properly when I set sqlalchemy_session?

Working with nosetests 1.3.7 (but FactoryBoy's set_creation_function is now deprecated):

from myapp.core import db

def create_sqlalchemy_model_function(class_to_create, *args, **kwargs):
    entity = class_to_create(**kwargs)
    db.session.add(entity)
    db.session.commit()
    return entity

Factory.set_creation_function(create_sqlalchemy_model_function)

Not working with nosetests 2.x (looking like db is not being referenced properly?)

from factory.alchemy import SQLAlchemyModelFactory as Factory
from myapp.core import db

class Factory():
    class Meta:
        sqlalchemy_session = db.session

    def _create(cls, model_class, *args, **kwargs):
        entity = model_class(*args, **kwargs)
        db.session.add(entity)
        db.session.commit()
        return entity
like image 513
Patrick Avatar asked Feb 14 '16 19:02

Patrick


1 Answers

Two major issues with your sample not-working code:

  • the class should be derived from SQLAlchemyModelFactory class
  • the _create() method should be defined as classmethod

Fixed version:

from factory.alchemy import SQLAlchemyModelFactory as Factory
from myapp.core import db

class MyFactory(Factory):
    class Meta:
        sqlalchemy_session = db.session

    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        entity = model_class(*args, **kwargs)
        db.session.add(entity)
        db.session.commit()
        return entity

Here is also a sample of the model factory overriding the _create() method.

like image 138
alecxe Avatar answered Nov 15 '22 15:11

alecxe