使用 Python Bottle 框架自动测试路由



我想在我的 Python/Bottle Web 应用程序中构建一种测试所有路由的自动化方法,因为我目前有大约 100 条路由。 最好的方法是什么?

我推荐WebTest;它功能齐全,非常易于使用。下面是一个完整的工作示例,演示了一个简单的测试:

from bottle import Bottle, response
from webtest import TestApp
# the real webapp
app = Bottle()

@app.route('/rest/<name>')
def root(name):
'''Simple example to demonstrate how to test Bottle routes'''
response.content_type = 'text/plain'
return ['you requested "{}"'.format(name)]

def test_root():
'''Test GET /'''
# wrap the real app in a TestApp object
test_app = TestApp(app)
# simulate a call (HTTP GET)
resp = test_app.get('/rest/roger')
# validate the response
assert resp.body == 'you requested "roger"'
assert resp.content_type == 'text/plain'

# run the test
test_root()

Bottle的创建者建议使用WebTest,这是一个专门为单元测试Python WSGI应用程序而设计的框架。

此外,还有Boddle,一个专门用于Bottle的测试工具。我自己没有使用过这个软件,所以我不能说它的效果如何,但是,截至发布本答案时,它似乎得到了积极的维护。

我建议查看其中的一个或两个,然后尝试一下。如果您发现自己对如何正确与其中一个集成还有其他疑问,请发布另一个问题。

祝你好运!

最新更新