在测试中捕获Flask中止状态码?

2024-03-28 11:09:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在基于flask类的视图中有一个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)

在测试.py在

^{pr2}$

Tags: 代码frompyimportselfview视图flask
2条回答

在werkzeug库中,http错误代码保存在HTTPException.None中。您可以在sourcecode中看到这一点(对于非None代码,请参见BadRequest异常)。在

好吧,所以我是个白痴。不敢相信我以前没注意到。在http\u错误中有一个异常对象。在我的测试中,我在调用validate_请求之前调用了http_错误,因此我错过了它。以下是正确答案:

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)

p.S.孩子们,当你累得要死的时候,千万不要编码。:(

相关问题 更多 >