我有一个项目,我已经工作了一段时间,用Flask编写,并使用SQLAlchemy和Declarative扩展名http://flask.pocoo.org/docs/patterns/sqlalchemy/。我最近决定开始对我的项目进行单元测试,但对于我的生活,我似乎无法弄清楚如何使它工作。
我看了http://flask.pocoo.org/docs/testing/,但我似乎无法使其发挥作用。
我尝试了来自不同网站的混合内容,但无法找到正常运行的内容。
class StopsTestCase(unittest.TestCase):
def setUp(self):
self.engine = create_engine('sqlite:///:memory:')
self.session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=self.engine))
models.Base = declarative_base()
models.Base.query = self.session.query_property()
models.Base.metadata.create_all(bind=self.engine)
def test_empty_db(self):
stops = session.query(models.Stop).all()
assert len(stops) == 0
def tearDown(self):
session.remove()
if __name__ == '__main__':
unittest.main()
不幸的是,我似乎得到的最好的,导致以下错误。
OperationalError: (OperationalError) no such table: stops u'SELECT stops.agency_id AS stops_agency_id, stops.id AS stops_id, stops.name AS stops_name, stops."desc" AS stops_desc, stops.lat AS stops_lat, stops.lon AS stops_lon, stops.zone_id AS stops_zone_id \nFROM stops' ()
----------------------------------------------------------------------
Ran 1 test in 0.025s
FAILED (errors=1)
对此的任何帮助将不胜感激。如果有人曾经经历过这个并且让它发挥作用,我想要一些指示!提前谢谢。
答案 0 :(得分:1)
您再次实例化declarative_base
,您应该使用您用作模型基类的相同实例。此外,您似乎使用了两个不同的session
个实例,self.session
和一些模块全局session
。尝试清理它。
答案 1 :(得分:1)
根据我发现的内容以及我如何使用它,这里有一个模板解决方案,可以使用Declarative扩展来测试底层的SQLAlchemy系统。**
import unittest
from database import Base
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
import models
class StopsTestCase(unittest.TestCase):
def setUp(self):
self.engine = create_engine('sqlite:///:memory:')
self.session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=self.engine))
Base.query = self.session.query_property()
Base.metadata.create_all(bind=self.engine)
#Create objects here
#These will likely involve something like the following for one of my stops
# stop1 = models.Stop(id=1, name="Stop 1")
# self.session.add(stop1)
# self.session.commit()
# But adding a stop to the database here will break the test below. Just saying.
def test_empty_db(self):
stops = self.session.query(models.Stop).all()
assert len(stops) == 0
def tearDown(self):
self.session.remove()