我的基于烧瓶类的视图中有一个 abort()。我可以断言已调用 abort,但我无法访问上下文管理器中的 406 代码。
视图.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)
Run Code Online (Sandbox Code Playgroud)
测试.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)
Run Code Online (Sandbox Code Playgroud)
好吧,所以我是个白痴。不敢相信我以前没有注意到这一点。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)
Run Code Online (Sandbox Code Playgroud)
PS 孩子们,当你累得筋疲力尽时永远不要编码。:(
| 归档时间: |
|
| 查看次数: |
2595 次 |
| 最近记录: |