Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask unit tests with SQLAlchemy and PostgreSQL exhausts db connections

I'm running a suite of fairly straightforward test cases using Flask, SQLAlchemy, and PostgreSQL. Using an application factory, I've defined a base unit test class like so:

class BaseTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app()
        self.app.config.from_object('app.config.test')
        self.api_base = '/api/v1'

        self.ctx = self.app.test_request_context()
        self.ctx.push()

        self.client = self.app.test_client()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all(app=self.app)
        print db.engine.pool.status()
        if self.ctx is not None:
            self.ctx.pop()

All goes well for a few unit tests, up until:

OperationalError: (OperationalError) FATAL:  remaining connection slots are reserved for non-replication superuser connections

It seems that there is only 1 connection in the pool (db.engine.pool.status() for each test shows: Pool size: 5 Connections in pool: 1 Current Overflow: -4 Current Checked out connections: 0), but somehow the app never disconnects. Clearly a new app instance is created for each test case, which seems fine according to the documentation. If I move the app creation to the module level it works fine.

Does anyone know why this is happening?

Thanks

like image 226
Dick Avatar asked Jan 25 '26 03:01

Dick


1 Answers

Add db.get_engine(self.app).dispose() after db.drop_all()

like image 124
Adam P Avatar answered Jan 26 '26 16:01

Adam P