1
# Copyright 2010 Canonical Ltd. This software is licensed under the
2
# GNU Affero General Public License version 3 (see the file LICENSE).
5
from psycopg2 import DatabaseError
8
class MockConnection(object):
9
def __init__(self, connection, psycopg):
10
self.connection = connection
11
self.psycopg = psycopg
14
if self.psycopg.fail_next_N_connections > 0:
15
self.psycopg.fail_next_N_connections -= 1
16
raise DatabaseError('Mock error.')
17
return self.connection.cursor()
19
def __getattr__(self, attr):
20
if attr in self.__dict__:
21
return self.__dict__[attr]
23
return getattr(self.connection, attr)
26
class MockPsycopg(object):
28
self.fail_next_N_connections = 0
31
def connect(self, *args, **kwargs):
32
if self.fail_next_N_connections > 0:
33
self.fail_next_N_connections -= 1
34
raise DatabaseError('Mock error.')
35
if self.dsn is not None:
37
kwargs = {'dsn': self.dsn}
38
return MockConnection(psycopg2.connect(*args, **kwargs), self)
40
def fixate_connection(self, dsn):
41
""" Fixate the database connection information.
43
This function ensures that further connections will be
44
attempted always using the same DSN, so that we can play
45
around with the DATABASE_* settings during tests and still
46
keep connecting to our only test database. """
49
def release_connection(self):
50
""" Release the database connection information.
52
Forget about stored connection information, so that next
53
call to connect() really connects to the database you ask
58
connect = mock.connect
59
fixate_connection = mock.fixate_connection
60
release_connection = mock.release_connection
63
def fail_next_N_connections(n):
64
mock.fail_next_N_connections = n