在单元测试中没有创建多对多辅助表

时间:2013-04-22 04:16:02

标签: python sqlalchemy flask

我有一个使用SQLAlchemy的Flask应用程序,但是在使用我的单元测试时遇到了很多关系。

在我的setUp方法中,我创建了我的应用并初始化我的数据库:

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy()

def setUp(self):
    self.app = create_app(env='test')
    self.app.logger.disabled = True
    db.init_app(self.app)
    with self.app.app_context():
        db.create_all()

在我的models.py中,我定义了这样的多对多:

contact_buying_categories = db.Table('contact_buying_category',
    db.Column('contact_id', db.Integer, db.ForeignKey('contact.id')),
    db.Column('category_id', db.Integer, db.ForeignKey('buying_categories.id'))
)

class Contact(db.Model):

    __tablename__ = 'contact'
    __bind_key__ = 'db1'

    id = db.Column(db.Integer, primary_key=True)

    buying_categories = db.relationship('BuyingCategory',
                                        secondary=contact_buying_categories)


      ...

class BuyingCategory(db.Model):

    __tablename__ = 'buying_categories'
    __bind_key__ = 'db2'

    id = db.Column(db.Integer, primary_key=True)
    ...

当我运行单元测试时,出现以下错误:

OperationalError: (OperationalError) no such table: contact_buying_category 
u'SELECT buying_categories.id AS buying_categories_id, buying_categories.name AS 
buying_categories_name \nFROM buying_categories, contact_buying_category \nWHERE ? = 
contact_buying_category.contact_id AND buying_categories.id = 
contact_buying_category.category_id' (1,)

如果我在create_all()中进行setUp调用后进入IPDB并执行db.metadata.tables,则会有表格定义:

'contact_buying_category': Table('contact_buying_category', MetaData(bind=None), 
Column('contact_id', Integer(), ForeignKey('contact.id'), table=
<contact_buying_category>), Column('category_id', Integer(), 
ForeignKey('buying_categories.id'), table=<contact_buying_category>), schema=None),

我很困惑,为什么app不能找到contact_buying_category表?如何检查它是否真的被创建了?

1 个答案:

答案 0 :(得分:0)

我需要在Flask-SQLAlchemy的多对多关系上设置一个bind_key,以便在调用db.create_all()时注意它。

contact_buying_categories = db.Table('contact_buying_category',
    db.Column('contact_id', db.Integer, db.ForeignKey('contact.id')),
    db.Column('category_id', db.Integer, db.ForeignKey('buying_categories.id')),
    info={'bind_key': 'wdl'}
)
相关问题