【问题标题】:Using factory_boy with SQLAlchemy and class methods将 factory_boy 与 SQLAlchemy 和类方法一起使用
【发布时间】:2013-07-09 05:54:48
【问题描述】:

我正在开发一个以 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 并用我的会话替换那个全局会话,但后来我得到这个错误:E AttributeError: type object 'RoleFactory' has no attribute 'find_all'

我尝试调用 RoleFactory.FACTORY_FOR.find_all(),但随后我得到相同的 UnboundExecutionError。

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

【问题讨论】:

    标签: python sqlalchemy class-method factory-boy


    【解决方案1】:

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

    role = RoleFactory.build()
    roles = role.find_all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 2015-07-30
      • 2020-06-14
      • 1970-01-01
      • 2015-01-05
      相关资源
      最近更新 更多