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

Automated testing of routes using Python Bottle framework

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

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

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

我建议您查看其中一个或两个,然后尝试一下。如果您发现自己对如何正确集成其中之一有更多疑问,post 另一个问题。

祝你好运!

我推荐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()