2026-11-25 22:36:13 -05:00
|
|
|
"""Database connection handling and migrations, with a fake PyMySQL connection."""
|
|
|
|
|
import pymysql
|
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
|
|
from thor.config import DatabaseSettings
|
|
|
|
|
from thor.db import MIGRATIONS, Database, DatabaseError, Store, _statements
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class FakeCursor:
|
|
|
|
|
def __init__(self, conn):
|
|
|
|
|
self.conn = conn
|
|
|
|
|
self.lastrowid = 0
|
|
|
|
|
self.rowcount = 0
|
|
|
|
|
self._rows = []
|
|
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
def __exit__(self, *a):
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
def execute(self, sql, params=()):
|
|
|
|
|
if self.conn.fail_execute:
|
|
|
|
|
raise pymysql.err.OperationalError(2013, 'Lost connection')
|
|
|
|
|
self.conn.executed.append((' '.join(sql.split()), params))
|
|
|
|
|
if 'MAX(version)' in sql:
|
|
|
|
|
self._rows = [{'v': self.conn.version}]
|
|
|
|
|
elif sql.startswith('SELECT v FROM state'):
|
|
|
|
|
self._rows = [{'v': self.conn.state_value}] if self.conn.state_value is not None else []
|
|
|
|
|
else:
|
|
|
|
|
self._rows = []
|
|
|
|
|
self.rowcount = 1
|
|
|
|
|
self.lastrowid = 7 if sql.lstrip().startswith('INSERT') else 0
|
|
|
|
|
|
|
|
|
|
def fetchall(self):
|
|
|
|
|
return self._rows
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class FakeConn:
|
|
|
|
|
def __init__(self):
|
|
|
|
|
self.executed = []
|
|
|
|
|
self.fail_execute = False
|
|
|
|
|
self.fail_ping = False
|
|
|
|
|
self.closed = False
|
|
|
|
|
self.version = 0
|
|
|
|
|
self.state_value = None
|
|
|
|
|
|
|
|
|
|
def cursor(self):
|
|
|
|
|
return FakeCursor(self)
|
|
|
|
|
|
|
|
|
|
def ping(self, reconnect=False):
|
|
|
|
|
assert reconnect is False # deprecated in PyMySQL 1.2
|
|
|
|
|
if self.fail_ping:
|
|
|
|
|
raise pymysql.err.OperationalError(2006, 'gone away')
|
|
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
|
self.closed = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def make_db():
|
|
|
|
|
conns = []
|
|
|
|
|
|
|
|
|
|
def connect():
|
|
|
|
|
c = FakeConn()
|
|
|
|
|
conns.append(c)
|
|
|
|
|
return c
|
|
|
|
|
return Database(DatabaseSettings(host='h', password='p'), connect=connect), conns
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_reuses_connection_and_reconnects_after_failed_ping():
|
|
|
|
|
db, conns = make_db()
|
|
|
|
|
db.execute('SELECT 1')
|
|
|
|
|
db.execute('SELECT 2')
|
|
|
|
|
assert len(conns) == 1
|
|
|
|
|
conns[0].fail_ping = True
|
|
|
|
|
db.execute('SELECT 3')
|
|
|
|
|
assert len(conns) == 2 and conns[0].closed
|
|
|
|
|
assert conns[1].executed == [('SELECT 3', ())]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_mysql_errors_become_database_errors_and_drop_the_connection():
|
|
|
|
|
db, conns = make_db()
|
|
|
|
|
db.execute('SELECT 1')
|
|
|
|
|
conns[0].fail_execute = True
|
|
|
|
|
with pytest.raises(DatabaseError, match='Lost connection'):
|
|
|
|
|
db.query('SELECT 1')
|
|
|
|
|
db.execute('SELECT 2')
|
|
|
|
|
assert len(conns) == 2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_connect_failure_is_database_error():
|
|
|
|
|
def connect():
|
|
|
|
|
raise pymysql.err.OperationalError(2003, "Can't connect")
|
|
|
|
|
with pytest.raises(DatabaseError):
|
|
|
|
|
Database(DatabaseSettings(), connect=connect).query('SELECT 1')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_migrate_applies_pending_migrations_once():
|
|
|
|
|
db, conns = make_db()
|
|
|
|
|
assert db.migrate() == len(MIGRATIONS)
|
|
|
|
|
executed = [sql for sql, _ in conns[0].executed]
|
2026-11-25 23:13:59 -05:00
|
|
|
applied = [s for s in executed if 'schema_version' not in s]
|
|
|
|
|
assert len(applied) == sum(len(list(_statements(m))) for m in MIGRATIONS)
|
|
|
|
|
assert any(s.startswith('INSERT INTO known_conditions') for s in applied)
|
2026-11-25 22:36:13 -05:00
|
|
|
assert any(s.startswith('INSERT INTO schema_version') for s in executed)
|
|
|
|
|
conns[0].executed.clear()
|
|
|
|
|
conns[0].version = len(MIGRATIONS)
|
|
|
|
|
assert db.migrate() == len(MIGRATIONS)
|
|
|
|
|
assert not any(s.startswith('INSERT INTO schema_version') for s in (x for x, _ in conns[0].executed))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_store_state_json_and_bad_json():
|
|
|
|
|
db, conns = make_db()
|
|
|
|
|
store = Store(db)
|
|
|
|
|
store.set_state('k', {'a': 1}, 1795575600.0)
|
|
|
|
|
sql, params = conns[0].executed[-1]
|
|
|
|
|
assert sql.startswith('INSERT INTO state') and params[1] == '{"a": 1}'
|
|
|
|
|
conns[0].state_value = '{"a": 1}'
|
|
|
|
|
assert store.get_state('k') == {'a': 1}
|
|
|
|
|
conns[0].state_value = 'not json'
|
|
|
|
|
assert store.get_state('k', 'dflt') == 'dflt'
|
|
|
|
|
conns[0].state_value = None
|
|
|
|
|
assert store.get_state('k', 'dflt') == 'dflt'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def test_store_writes_pass_utc_datetimes_and_truncate():
|
|
|
|
|
db, conns = make_db()
|
|
|
|
|
store = Store(db)
|
|
|
|
|
assert store.record_cycle(started=1795575600.0, finished=1795575602.0, window_start=1795575480.0,
|
|
|
|
|
window_end=1795575600.0, ok=True, blind=['loki', 'gandalf']) == 7
|
|
|
|
|
_sql, params = conns[0].executed[-1]
|
|
|
|
|
assert params[0].isoformat() == '2026-11-25T03:00:00'
|
|
|
|
|
assert params[5] == 'gandalf,loki'
|
|
|
|
|
assert params[6] is None
|
|
|
|
|
store.open_blind_period('loki', 1795575600.0, 'x' * 5000)
|
|
|
|
|
assert len(conns[0].executed[-1][1][2]) == 2000
|