Flask Testing with unittest
Throughout this book we used pytest for writing tests and I think it is the better choice, but some people might want to stick to the unittest library so for their sake I prepared an example using unittest:
from flask import Flask
myapp = Flask(__name__)
@myapp.route("/")
def main():
return '''
Main <a href="/add/23/19">add</a>
'''
@myapp.route("/add/<int:a>/<int:b>")
def api_info(a, b):
return str(a+b)
from with_unittest import myapp
import unittest
class TestMyApp(unittest.TestCase):
def setUp(self):
self.app = myapp.test_client()
def test_main(self):
rv = self.app.get('/')
assert rv.status == '200 OK'
assert b'Main' in rv.data
#assert False
def test_add(self):
rv = self.app.get('/add/2/3')
self.assertEqual(rv.status, '200 OK')
self.assertEqual(rv.data, b'5')
rv = self.app.get('/add/0/10')
self.assertEqual(rv.status, '200 OK')
self.assertEqual(rv.data, b'10')
def test_404(self):
rv = self.app.get('/other')
self.assertEqual(rv.status, '404 NOT FOUND')
Run with
python -m unittes test_app.py
Actually you could also use pytest to run these tests.
pytest