我正在使用SQLAlchemy作为ORM开发Pyramid应用程序。我试图用类方法测试模型:
# 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()
我正在使用factory_boy进行测试,以下是我尝试设置测试工厂的方法:
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
但是,当我尝试在测试中调用RoleFactory.find_all()
时,出现错误: E UnboundExecutionError:无法找到在映射器Mapper | Role | role,SQL表达式或此Session上配置的绑定
我尝试了monkeypatching meta
并用我的会话替换了这个全局Session,但后来我收到了这个错误: E AttributeError:type object'RoleFactory'没有属性'find_all'
我尝试调用RoleFactory.FACTORY_FOR.find_all()
,但后来我得到了相同的UnboundExecutionError。
我是否需要为factory_boy做其他事情以了解类方法?
答案 0 :(得分:3)
这可能太明显了,但似乎你所拥有的是一个RoleFactory实例,当你需要一个Role实例时,工厂将无法访问任何classmethods,因为它不是该类的子类。尝试这样做,看看会发生什么:
role = RoleFactory.build()
roles = role.find_all()