The following function is supposed to make a PostgreSQL connection and handle the possible exceptions:
def connectToDB():
try:
conn = psycopg2.connect(
"dbname=" + dbName + " host=" + host + " user=" + user + " password=" + password)
except OperationalError as err:
print(err.pgcode)
print(err.pgerror)
# set the connection to 'None' in case of error
conn = None
return conn
In order to test the function above, I need to make a fake database connection. How can I build a fake database connection with a deisired pgcode (or/and pgerror)? I need this to replace with the real database connection (using patch in Unit-Test) and observe the behaviour of my function. That means, I need to test via mocking if the function can handle the exceptions well.