用Flas测试异常返回码

2024-10-01 04:59:53 发布

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

我有以下代码块

class APITests(unittest.TestCase):

    def setUp(self):
        app.config['TESTING'] = True
        self.app = app.test_client()
        app.config['SECRET_KEY'] = 'kjhk'

    def test_exn(self, query):
        query.all.side_effect = ValueError('test')
        rv = self.app.get('/exn/')
        assert rv.status_code == 400

我想检查self.app.get('/exn/)的返回代码。但是,我注意到query.all()将异常传播到测试用例,而不是捕获它并返回错误代码。在

在Flask中抛出异常时,如何检查无效输入的返回代码?在


Tags: 代码testselfconfigappgetdefunittest
1条回答
网友
1楼 · 发布于 2024-10-01 04:59:53

您可以assertRaise来自werkzeug的异常。在

示例:

from werkzeug import exceptions
def test_bad_request(self):
    with self.app as c:
        rv = c.get('/exn/',
                   follow_redirects=True)
        self.assertRaises(exceptions.BadRequest)    

相关问题 更多 >