jeudi 31 mars 2016

flask/sqlalchemy unittest OperationalError: (sqlite3.OperationalError) no such table, but was able to query table previously

I'm trying to write unittests for my Flask api app. I am able to insert an object into my table in one test method, but then in the next test method I get the following error:

OperationalError: (sqlite3.OperationalError) no such table

database.py

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    import models
    Base.metadata.create_all(bind=engine)

models.py

from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.orm import validates
from validate_email import validate_email

from database import db_session, Base

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    first_name = Column(String(50))
    last_name =Column(String(50))
    email = Column(String(120), unique=True)


    def __init__(self, first_name=None, email=None):
        self.first_name = first_name
        self.email = email

    def __repr__(self):
        return '<User %r>' % (self.first_name)

@validates('email')
def validate_email(self, key, email):
    if email is None:
        raise ValueError(
            'Email is required')
    if not validate_email(email):
        raise ValueError(
            "Invalid Email Address")
    if User.query.filter(User.email==email).first():
        raise ValueError(
            "Email exists")
    return email

Lines that run fine:

        user = User(first_name=fname, email=email)
        db_session.add(user)
        db_session.commit()

Subsequent line that is causing error:

        user = User.query.filter(User.id == user_id).first()

my api.py starts with

app = Flask(__name__)
api = Api(app)
init_db()

Does anyone have any ideas for me?

Aucun commentaire:

Enregistrer un commentaire