Testing Exception Return Codes With Flask Testing Exception Return Codes With Flask flask flask

Testing Exception Return Codes With Flask


You would have to do the following to trap the exception.

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

For the assertRaises to work, the function call must be contained within some sort of wrapper to catch the exception.

If it is just ran like you did, it is just executed on its own, the exception is not caught and the test case becomes an error instead.

By wrapping the function call within a “with statement”, the exception is passed back to the “assertRaises” in the clause. The “assertRaises” function can now do the comparison on the exception.

To read up more on this, check this link


You can assertRaise the exception from werkzeug.

Example:

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