UPDATE : tested and fixed
Instead of creating a new connection and re-creating your database every time (slowly), you can use subheadings and rollbacks after each test.
The connection is reused, so this will also fix the problem you are having.
class TestCase(Base): @classmethod def setUpClass(cls): cls.app = create_app(MyConfig()) cls.client = cls.app.test_client() cls._ctx = cls.app.test_request_context() cls._ctx.push() db.create_all() @classmethod def tearDownClass(cls): db.session.remove() db.drop_all() db.get_engine(cls.app).dispose() def setUp(self): self._ctx = self.app.test_request_context() self._ctx.push() db.session.begin(subtransactions=True) def tearDown(self): db.session.rollback() db.session.close() self._ctx.pop()
If you also need to make an instance of the application for each test, just add it to the setUp method, but leave it in setUpClass as setUpClass .
For a complete test case below, flask_sqlalchemy and psycopg2 are required. Create a test database named "test" and set the connection limit to 15.
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from unittest import TestCase as Base db = SQLAlchemy() def create_app(config=None): app = Flask(__name__) app.config.from_object(config) db.init_app(app) return app class MyConfig(object): SQLALCHEMY_DATABASE_URI = "postgresql://localhost/test" TESTING = True class TestCase(Base): @classmethod def setUpClass(cls): cls.app = create_app(MyConfig()) cls.client = cls.app.test_client() cls._ctx = cls.app.test_request_context() cls._ctx.push() db.create_all() @classmethod def tearDownClass(cls): db.session.remove() db.drop_all() def setUp(self): self._ctx = self.app.test_request_context() self._ctx.push() db.session.begin(subtransactions=True) def tearDown(self): db.session.rollback() db.session.close() self._ctx.pop() class TestModel(TestCase): def test_01(self): pass def test_02(self): pass def test_03(self): pass def test_04(self): pass def test_05(self): pass def test_06(self): pass def test_07(self): pass def test_08(self): pass def test_09(self): pass def test_10(self): pass def test_11(self): pass def test_12(self): pass def test_13(self): pass def test_14(self): pass def test_15(self): pass def test_16(self): pass if __name__ == "__main__": import unittest unittest.main()
source share