如何正确测试基于sqlalchemydeclarati的PythonFlask系统

2024-04-25 08:19:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个项目我已经做了一段时间了,它是用Flask编写的,它使用SQLAlchemy和声明性扩展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()

不幸的是,我所能得到的最好结果,会导致以下错误。在

^{pr2}$

如果有任何帮助,我们将不胜感激。如果有人曾经经历过这一切,并且成功了,我想要一些提示!提前谢谢。在


Tags: 项目orgselfhttpflaskdocsbasemodels
2条回答

根据我的发现以及我是如何让它工作的,这里有一个模板解决方案,它使用声明性扩展测试底层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()

再次实例化declarative_base,应该使用与模型基类相同的实例。另外,您似乎在使用两个不同的session实例,self.session和一些模块globalsession。试着把它清理干净。在

相关问题 更多 >