Files
dtf-system/tests/test_db_pool.py
Cauê Faleiros 5b7e95ad86 feat: a database connection pool behind DB_POOL (off in production)
Every db.connect() opened a new Postgres connection; with DB_POOL=on each
process keeps a psycopg_pool pool (DB_POOL_SIZE, default 20, 10 s
acquisition timeout, dropped connections replaced) with the same
commit/rollback contract. Production stays off until switched in Portainer;
the local stack and CI run with it on. Two nested acquisitions that ran on
every board load and in audits now reuse the caller's connection.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:57:42 -03:00

94 lines
4.0 KiB
Python

"""The DB_POOL switch in app/core/db.py (Critical Corrections item 4).
Run from repository root: python3 -m unittest tests.test_db_pool -v.
The host validation runner has no psycopg; small stand-ins are installed before
importing the module, then mocked in each test.
"""
import os
import sys
import types
import unittest
from unittest import mock
try:
import psycopg # noqa: F401
except ModuleNotFoundError:
psycopg = types.ModuleType('psycopg')
psycopg.connect = mock.MagicMock()
rows = types.ModuleType('psycopg.rows')
rows.dict_row = object()
psycopg.rows = rows
sys.modules['psycopg'] = psycopg
sys.modules['psycopg.rows'] = rows
try:
import psycopg_pool # noqa: F401
except ModuleNotFoundError:
psycopg_pool = types.ModuleType('psycopg_pool')
psycopg_pool.ConnectionPool = mock.MagicMock()
sys.modules['psycopg_pool'] = psycopg_pool
from app.core import db
class DatabasePoolTests(unittest.TestCase):
def setUp(self):
db._pool = None
self.addCleanup(lambda: setattr(db, '_pool', None))
def test_pool_is_off_by_default(self):
with mock.patch.dict(os.environ, {'DATABASE_HOST': '',
'DATABASE_URL': 'postgresql://env/dtf'}, clear=True), \
mock.patch.object(db.psycopg, 'connect') as connect, \
mock.patch.object(db, 'ConnectionPool') as pool_class:
connection = db.connect()
connect.assert_called_once_with('postgresql://env/dtf', row_factory=db.dict_row)
self.assertIs(connection, connect.return_value)
pool_class.assert_not_called()
def test_off_uses_a_direct_connection(self):
with mock.patch.dict(os.environ, {'DB_POOL': 'off', 'DATABASE_HOST': '',
'DATABASE_URL': 'postgresql://env/dtf'}), \
mock.patch.object(db.psycopg, 'connect') as connect, \
mock.patch.object(db, 'ConnectionPool') as pool_class:
connection = db.connect()
connect.assert_called_once_with('postgresql://env/dtf', row_factory=db.dict_row)
self.assertIs(connection, connect.return_value)
pool_class.assert_not_called()
def test_on_returns_the_pool_connection_and_builds_the_pool_once(self):
with mock.patch.dict(os.environ, {'DB_POOL': 'on', 'DB_POOL_SIZE': '7',
'DATABASE_HOST': '',
'DATABASE_URL': 'postgresql://env/dtf'}), \
mock.patch.object(db, 'ConnectionPool') as pool_class:
first = db.connect()
second = db.connect()
pool_class.assert_called_once()
args, kwargs = pool_class.call_args
self.assertEqual(args, ('postgresql://env/dtf',))
self.assertEqual(kwargs['kwargs'], {'row_factory': db.dict_row})
self.assertEqual(kwargs['min_size'], 1)
self.assertEqual(kwargs['max_size'], 7)
self.assertIs(kwargs['open'], True)
self.assertEqual(kwargs['timeout'], 10)
self.assertIs(kwargs['check'], pool_class.check_connection)
self.assertEqual(pool_class.return_value.connection.call_count, 2)
self.assertIs(first, pool_class.return_value.connection.return_value)
self.assertIs(second, first)
def test_on_uses_the_host_settings_and_default_size(self):
with mock.patch.dict(os.environ, {'DB_POOL': 'on', 'DATABASE_HOST': 'db',
'DATABASE_NAME': 'dtf', 'DATABASE_USER': 'app',
'DATABASE_PASSWORD': 'secret'}, clear=True), \
mock.patch.object(db, 'ConnectionPool') as pool_class:
db.connect()
args, kwargs = pool_class.call_args
self.assertEqual(args, ('',))
self.assertEqual(kwargs['max_size'], 20)
self.assertEqual(kwargs['kwargs'], {'host': 'db', 'dbname': 'dtf', 'user': 'app',
'password': 'secret', 'row_factory': db.dict_row})
if __name__ == '__main__':
unittest.main()