我在基于 Flask 类的视图中有一个 abort() 。我可以断言已调用中止,但我无法在上下文管理器中访问 406 代码。
views.py
from flask.views import View
from flask import abort
class MyView(View):
def validate_request(self):
if self.accept_header not in self.allowed_types:
abort(406)
tests.py
from werkzeug.exceptions import HTTPException
def test_validate_request(self):
# Ensure that an invalid accept header type will return a 406
self.view.accept_header = 'foo/bar'
with self.assertRaises(HTTPException) as http_error:
self.view.validate_request()
self.assertEqual(http_error.???, 406)
好吧,所以我是个白痴。不敢相信我之前没有注意到这一点。 http_error 内部有一个异常对象。在我的测试中,我在调用 validate_request 之前调用了 http_error,所以我错过了它。这是正确的答案:
from werkzeug.exceptions import HTTPException
def test_validate_request(self):
# Ensure that an invalid accept header type will return a 406
self.view.accept_header = 'foo/bar'
with self.assertRaises(HTTPException) as http_error:
self.view.validate_request()
self.assertEqual(http_error.exception.code, 406)
附:孩子们,当你累得精疲力竭时,永远不要编码。 :(
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)