在Flask中使用请求上下文进行正确的测试

时间:2015-12-14 21:37:29

标签: python python-2.7 flask

我正在尝试显式调用路由函数执行一些测试。

from flask import Flask
app = Flask(__name__)


@app.route("/")
def index():
    myfunc()
    return "Index!"

@app.route("/a")
def hello():
    return "hello"

def myfunc():
    with app.test_request_context('/', method='POST'):
        app.hello()


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

但它失败了:

Traceback (most recent call last):
  File "python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "test.py", line 9, in index
    myfunc()
  File "test.py", line 18, in myfunc
    app.hello()
AttributeError: 'Flask' object has no attribute 'hello'

是否可以通过这种方式测试路由功能?

是的例子有点难看,但我需要弄清楚它有什么问题。

2 个答案:

答案 0 :(得分:1)

要执行"内部重定向"或从另一个视图调用视图,您使用正确的url和任何其他所需数据推送新请求上下文,然后让Flask调度请求。您可以在外部视图中从内部视图或您自己的响应中返回值。

http://127.0.0.1/?name=davidism

导航至Hello, davidism!返回hellowith app.test_client() as c: r = c.get('/a') assert r.data.decode() == 'hello' 视图的回复。

您不会通过从这样的正在运行的应用程序中调用视图来测试视图。要测试Flask应用程序,您可以使用单元测试和测试客户端as described in the docs

{{1}}

答案 1 :(得分:0)

hello是一个常规函数,用app.route装饰它不会将它添加到app对象中。您是否意味着只需调用hello函数,如下所示:

with ...:
    hello()