I am trying to create unittests for my flask application which should assert exceptions properly.
I am attaching simplified code sample on what i want to test. The below test should finish as success.
def my_function():
abort(400,"error")
import unittest
from werkzeug import exceptions
class Tests(unittest.TestCase):
def test_event_link(self):
self.assertRaises(exceptions.BadRequest,my_function)
unittest.main(argv=[''], verbosity=2, exit=False)
I would simply patch the Flask abort
function and ensure it is called with the correct value, this is preferable as it only tests your code not the behaviour of Flasks abort
function which could change with future versions of Flask and break your tests.
See below example based on your code which also includes examples of testing the exception if this is what you would prefer to do.
# code.py
from flask import abort
def my_function():
abort(400, "error")
# test.py
import unittest
from unittest.mock import patch
from werkzeug import exceptions
import code # Your code file code.py
class Tests(unittest.TestCase):
@patch('code.abort')
def test_one(self, mock_abort):
code.my_function()
mock_abort.assert_called_once_with(400, 'error')
def test_two(self):
with self.assertRaises(exceptions.BadRequest):
code.my_function()
def test_three(self):
with self.assertRaisesRegexp(exceptions.BadRequest, '400 Bad Request: error'):
code.my_function()
unittest.main(argv=[''], verbosity=2, exit=False)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.