Using factory_boy with SQLAlchemy and class methods

I am working on a Pyramid application with SQLAlchemy as an ORM. I am trying to test a model using a class method:

# this is essentially a global used by all the models Session = scoped_session(sessionmaker(autocommit=False)) class Role(Base): __tablename__ = 'role' id = sa.Column(sa.types.Integer, primary_key=True) name = sa.Column(sa.types.Text, unique=True, nullable=False) def __init__(self, **kwargs): super(Role, self).__init__(**kwargs) @classmethod def find_all(self): return Session.query(Role).order_by(Role.name).all() 

I use factory_boy for testing, and here is how I try to set up my factory testing:

 import factory from factory.alchemy import SQLAlchemyModelFactory from sqlalchemy.orm import scoped_session, sessionmaker from zk.model.meta import Base from zk.model.role import Role session = scoped_session(sessionmaker()) engine = create_engine('sqlite://') session.configure(bind=engine) Base.metadata.create_all(engine) class RoleFactory(SQLAlchemyModelFactory): FACTORY_FOR = Role FACTORY_SESSION = session 

However, when I try to call RoleFactory.find_all() in the test, I get the error message: E UnboundExecutionError: could not find the binding configured on mapper Mapper | Role | role, SQL expression, or this session

I tried monkeypatching meta and replaced this global session with my session, but then I get this error: E AttributeError: object type 'RoleFactory' does not have attribute 'find_all'

I tried calling RoleFactory.FACTORY_FOR.find_all() , but then got the same UnboundExecutionError.

Do I need to do something for factory_boy to find out about the class method?

+7
python class-method sqlalchemy factory-boy
source share
1 answer

It may be too obvious, but it seems that you have an instance of RoleFactory, when you need an instance of Role, the factory will not have access to any classes, since it is not a child of the class, try to do this and see what happens :

 role = RoleFactory.build() roles = role.find_all() 
+2
source share

All Articles