繁体   English   中英

使用factory_boy和SQLAlchemy以及类方法

[英]Using factory_boy with SQLAlchemy and class methods

我正在使用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做其他事情以了解类方法?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM