在测试中捕获烧瓶中止状态代码? [英] Catching Flask abort status code in tests?

查看:45
本文介绍了在测试中捕获烧瓶中止状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在基于flask类的视图中有一个abort().我可以断言已经调用了异常终止,但是我无法在上下文管理器中访问406代码.

I have an abort() in my flask class based view. I can assert that an abort has been called, but I cannot access the 406 code in my context manager.

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,所以我错过了它.这是正确的答案:

Ok so I'm an idiot. Can't believe I didn't notice this before. There is an exception object inside the http_error. In my tests I was calling the http_error before calling validate_request, so I missed it. Here is the correct answer:

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.孩子们,当你累了的时候就不要编码.:(

P.S. Kids, never code when you're dead tired. :(

这篇关于在测试中捕获烧瓶中止状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆