在Flask中设置测试数据库
我正在开发我的第一个Flask应用。这是我一个副项目,所以我专注于好的实践和设计,并且慢慢来。我在测试方面遇到了一些困难——我在文档和这里的StackOverflow上找了一些例子,但它们要么不适用于我的应用,要么看起来不够Pythonic(即不符合Python的优雅风格)或者设计得不好。
相关的代码片段是:
# application module __init__.py
def create_app(config):
app = Flask(__name__)
app.config.from_object('config.%s' % config.title())
return app
config = os.getenv('CONFIG', 'development')
app = create_app(config)
db = SQLAlchemy(app)
# config.py
class Testing(Base):
TESTING = True
SQLALCHEMY_DATABASE_URI = \
'sqlite:///' + os.path.join(_basedir, 'testing.sqlite')
# models.py
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(60), unique=True, nullable=False)
password_hash = db.Column(db.String(60), nullable=False)
# testing.py
class TestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
# TODO: create connection to testing db
def tearDown(self):
# TODO: abort transaction
pass
我的问题是:如何实现setUp
和tearDown
,这样我在测试中就可以使用我的模型和连接到测试数据库?如果我只是导入db
,那它会在开发数据库上运行。
如果这有帮助,我不需要从头创建测试数据库,我使用Flask-Migrate,测试可以假设测试数据库已经初始化并且是空的。
欢迎任何评论,如果我的设计有问题,我不介意进行重构。
1 个回答
6
看起来你只需要运行 CONFIG=Testing python -m unittest discover
这个命令,所有东西就应该能正常工作。你可能唯一想要改变的就是,不要在测试中调用 create_app
,而是直接从 __init__.py 文件中导入它:
# testing.py
from . import config, db
class TestCase(unittest.TestCase):
def setUp(self):
self.app = create_app(config)
# db is properly set up to use the testing config
# but any *changes* you make to the db object
# (e. g. monkey-patching) will persist between tests
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
想要查看一个例子,可以点击 这里。