如何在Bottle应用中注入Sqlite以进行Webtest?

0 投票
1 回答
924 浏览
提问于 2025-04-17 21:25

这是我的应用程序(使用bottle框架):

import bottle
app = bottle.Bottle()
@app.get('/')
def home(db):
  return bottle.template('Hi!')
if __name__ == '__main__':
  bottle.install(bottle_sqlite.SQLitePlugin(dbfile='data.db'))
  bottle.run()

这是一个单元测试(使用webtestunittest库):

import webtest
def test_home():
  app = webtest.TestApp(example.app)
  assert app.get('/').status == '200 OK'

它不能正常工作,因为在测试时找不到data.db这个文件。我们的目标是想办法在运行测试之前,把这个db注入到应用程序中。应该怎么做呢?

1 个回答

1

你可以选择创建一个SQLitePlugin的模拟版本,这个模拟版本用一个Python字典来假装成一个数据库,或者在每组测试之前和之后创建和销毁一个SQLite数据库(这个数据库里的数据要和你的测试匹配)。

简单来说,你可以这样做:

import webtest
def test_home():
  plugin = bottle_sqlite.SQLitePlugin(dbfile='my_test_data_set.db')
  example.app.install(plugin)
  app = webtest.TestApp(example.app)
  assert app.get('/').status == '200 OK'
  example.app.uninstall(plugin)

或者

import webtest
def test_home():
  plugin = bottle_sqlite.SQLitePluginMockup(dataset)
  example.app.install(plugin)
  app = webtest.TestApp(example.app)
  assert app.get('/').status == '200 OK'
  example.app.uninstall(plugin)

这里的dataset就是一个“手工制作”的字典,用来模拟你应用程序的数据集。

或者你也可以在测试脚本的全局上下文中一次性完成这个操作。

希望这对你有帮助!

撰写回答