您可以轻松地覆盖此行为并使用相同的处理程序强制处理异常。
def run_test(path=None,check_func=None,*args,**kwargs):
with app.test_request_context(path,*args,**kwargs):
try:
data=app.dispatch_request()
if check_func is not None:
check_func()
else:
print data
except Exception as e:
print app.handle_exception(e)
run_test('/')
run_test('/other')
def current_test(data):
assert 'has some content' in data
run_test('/should_be_checked',check_func=current_test)
还有一句话。
您的方法不起作用,因为您只是不使用 Flask 的那部分,它实际上捕获了异常。您正在直接调用上下文。
从文档中引用:
如果你研究一下 Flask WSGI 应用程序的内部工作原理,你会发现一段代码看起来很像这样:
def wsgi_app(self, environ):
with self.request_context(environ):
try:
response = self.full_dispatch_request()
except Exception, e:
response = self.make_response(self.handle_exception(e))
return response(environ, start_response)
但!以下是正确的方法,因为每个级别的所有 Flask 方法都将以适当的方式调用:
with app.test_request_context():
with app.test_client() as client:
resp = client.get('/')
#and if you need content of response: print resp.data
---