7

我正在开发一个以 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: Could not locate a bind configuration on mapper Mapper|Role|role, SQL expression or this Session

我尝试meta用我的会话进行monkeypatching并替换该全局会话,但随后出现此错误:E AttributeError: type object 'RoleFactory' has no attribute 'find_all'

我试着打电话RoleFactory.FACTORY_FOR.find_all(),但后来我得到了同样的 UnboundExecutionError。

我是否需要为 factory_boy 做其他事情才能了解类方法?

4

1 回答 1

4

这可能太明显了,但似乎您拥有的是一个 RoleFactory 实例,当您需要一个 Role 实例时,工厂将无法访问任何类方法,因为它不是该类的子类。尝试这样做,看看会发生什么:

role = RoleFactory.build()
roles = role.find_all()
于 2013-07-17T06:56:45.703 回答