6

I have a Flask app that is using Flask-SQLAlchemy. In my unit tests, I initialise the app and the DB, then call db.create_all() and for some reason it looks like it's not picking up any of my models so isn't creating any tables.

I'm using both __tablename__ and __bind_key__ in my models as I have two databases.

My config:

SQLALCHEMY_DATABASE_URI = 'sqlite://'

SQLALCHEMY_BINDS = {
    'db1': SQLALCHEMY_DATABASE_URI,
    'db2': SQLALCHEMY_DATABASE_URI
}

Cut down version of my setUp() method in my unit tests:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

class APITestCase(unittest.TestCase):

    app = Flask(__name__)
    db = SQLAlchemy(app)
    db.create_all()

Here's an example of two of my models, one from each bind type:

class Contact(db.Model):

    __tablename__ = 'contact'
    __bind_key__ = 'db1'

    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(255))
    last_name = db.Column(db.String(255))
    ...

    def __init__(first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
        ...

class BaseUser(db.Model):

    __tablename__ = 'User__GeneralUser'
    __bind_key__ = 'db2'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column('Username', db.String(100))
    first_name = db.Column('FirstName', db.String(100))
    last_name = db.Column('Surname', db.String(100))
    ...

    def __init__(username, first_name, last_name):
        self.username = username
        self.first_name = first_name
        self.last_name = last_name
        ...

Have I missed something glaringly obvious? How does Flask-SQLAlchemy know where to look for my models to create the associated tables?

2
  • 1
    Have you imported your model classes? Commented Feb 25, 2013 at 14:18
  • Yes, I've tried both with and without importing my models. Commented Feb 25, 2013 at 15:08

1 Answer 1

13

In your unit tests you shouldn't create a new instance of the SQLAlchemy object ('db'), you should import the instance from which your models descend:

models.py:

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

class Contact(db.Model):
    ...

tests.py:

from models import db
from flask import Flask
import unittest

class TestExample(unittest.TestCase):

    def setUp(self):
        self.app = Flask(__name__)
        db.init_app(self.app)
        with self.app.app_context():
            db.create_all()
Sign up to request clarification or add additional context in comments.

1 Comment

What are some good ways to make sure all models declarations get executed if they are implemented in many modules?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.