def test_reconnect(self): """ If a query fails, make sure it wasn't just closed, reconnect and retry if it was. """ class BadConn(object): def __init__(self): self.called = [] def runQuery(self, *args): self.called.append(args) return defer.fail(Exception('foo')) c1 = BadConn() c2 = MagicMock() c2.runQuery.return_value = defer.succeed('success') pool = ConnectionPool() pool.add(c1) pool.setConnect(lambda:c2) result = yield pool.runQuery('something', 'ran') self.assertEqual(len(c1.called), 2) self.assertIn(('something', 'ran'), c1.called) c2.runQuery.assert_any_call('something', 'ran') self.assertEqual(pool.pool.list(), [c2], "Should have the new conn " "in the pool") self.assertEqual(result, 'success', "Should have eventually succeeded")
def test_setConnect(self): """ You can tell the connection pool how to make connections. """ called = [] def mkConnection(arg): called.append(arg) return 'connection' pool = ConnectionPool() pool.setConnect(mkConnection, 'foo') d = pool.makeConnection() self.assertEqual(self.successResultOf(d), 'connection') self.assertEqual(called, ['foo'])
def _makeBlockingPostgres(parsed, connections=1): import psycopg2 from psycopg2.extras import DictCursor connstr = mkConnStr(parsed) def connect(): return PostgresRunner(psycopg2.connect(connstr, cursor_factory=DictCursor)) pool = ConnectionPool() pool.db_scheme = 'postgres' pool.setConnect(connect) for i in xrange(connections): pool.add(connect()) return defer.succeed(pool)
def _makeTxPostgres(parsed, connections=1): from norm.tx_postgres import DictConnection connstr = mkConnStr(parsed) def connect(): conn = DictConnection() d = conn.connect(connstr) return d.addCallback(lambda _: conn) pool = ConnectionPool() pool.db_scheme = 'postgres' pool.setConnect(connect) dlist = [] for i in xrange(connections): d = connect() d.addCallback(pool.add) dlist.append(d) ret = defer.gatherResults(dlist) return ret.addCallback(lambda _: pool)