我想了解如何在仅对调用方法的测试中使用HTTPException
引发的方法。flask.abort
test_request_context
# example.py
import flask
@api.route('/', methods=['POST'])
def do_stuff():
param_a = get_param()
return jsonify(a=param_a)
# check if request is json, return http error codes otherwise
def get_param():
if flask.request.is_json():
try:
data = flask.request.get_json()
a = data('param_a')
except(ValueError):
abort(400)
else:
abort(405)
# test_example.py
from app import app # where app = Flask(__name__)
from example import get_param
import flask
def test_get_param(app):
with app.test_request_context('/', data=flask.json.dumps(good_json), content_type='application/json'):
assert a == get_param()
在上面的get_param
方法中,我尝试abort
如果失败is_json()
或get_json()
失败。为了测试这一点,我test_request_context
没有通过content_type
,并且基于这个博客和这个答案,我尝试添加一个嵌套的上下文管理器,如下所示:
# test_example.py
from app import app # where app = Flask(__name__)
from example import get_param
from werkzeug.exceptions import HTTPException
import flask
def test_get_param_aborts(app):
with app.test_request_context('/', data=flask.json.dumps('http://example', 'nope'), content_type=''):
with pytest.raises(HTTPException) as httperror:
get_param()
assert 405 == httperror
但我得到一个assert 405 == <ExceptionInfo for raises contextmanager>
断言错误。
有人可以解释一下并建议一种方法来测试abort
这种get_param
方法吗?
更新: 根据@tmt 的回答,我修改了测试。然而,即使测试通过了,在调试时我注意到这两个断言从未达到!
# test_example.py
from app import app # where app = Flask(__name__)
from example import get_param
from werkzeug.exceptions import HTTPException
import flask
def test_get_param_aborts(app):
with app.test_request_context('/', data=flask.json.dumps('http://example', 'nope'), content_type=''):
with pytest.raises(HTTPException) as httperror:
get_param() # <-- this line is reached
assert 405 == httperror.value.code
assert 1 ==2