gpt4 book ai didi

python - 如何基于 SQLAlchemy Declarative 正确测试 Python Flask 系统

转载 作者:行者123 更新时间:2023-11-28 16:47:08 31 4
gpt4 key购买 nike

我有一个我已经工作了一段时间的项目,它是用 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()

不幸的是,我似乎能得到最好的,导致以下错误。

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)

如有任何帮助,我们将不胜感激。如果有人曾经经历过这个,并让它发挥作用,我想要一些指示!提前致谢。

最佳答案

根据我的发现及其工作原理,这里有一个模板解决方案,可用于使用声明式扩展测试底层 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()

关于python - 如何基于 SQLAlchemy Declarative 正确测试 Python Flask 系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12766078/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com