Python 用Flask测试异常返回码
我有以下代码块Python 用Flask测试异常返回码,python,flask,python-unittest,Python,Flask,Python Unittest,我有以下代码块 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 = Value
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()
将异常传播到测试用例,而不是捕获异常并返回错误代码
当异常被抛出到烧瓶中时,如何检查返回代码中的无效输入?您可以
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)
您必须执行以下操作才能捕获异常
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')
with self.assertRaises(ValueError):
rv = self.app.get('/exn/')
assert rv.status_code == 400
为了让assertRaises工作,函数调用必须包含在某种包装器中,以捕获异常
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')
with self.assertRaises(ValueError):
rv = self.app.get('/exn/')
assert rv.status_code == 400
如果它只是像您那样运行,它只是自己执行,不会捕获异常,测试用例反而会变成错误
通过将函数调用包装在“with语句”中,将异常传递回子句中的“assertRaises”。“assertRaises”函数现在可以对异常进行比较
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')
with self.assertRaises(ValueError):
rv = self.app.get('/exn/')
assert rv.status_code == 400
要了解更多信息,请发布控制器代码。