I'm trying to write unit test for some_func function in some_func.py below. I do not want to connect to any database during this tests and I want to mock out any calls to DB.
Since the actual db calls are somewhat nested, i'm not able to get this to work. How do i patch any db interaction in this case?
db_module.py
import MySQLdb
from random_module.config.config_loader import config
from random_module.passwd_util import get_creds
class MySQLConn:
_conn = None
def __init__(self):
self._conn = self._get_rds_connection()
def get_conn(self):
return self._conn
def _get_rds_connection(self):
"""
Returns a conn object after establishing connection with the MySQL database
:return: obj: conn
"""
try:
logger.info("Establishing connection with MySQL")
username, password = get_creds(config['mysql_dev_creds'])
connection = MySQLdb.connect(
host=config['host'],
user=username,
passwd=password,
db=config['db_name'],
port=int(config['db_port']))
connection.autocommit = True
except Exception as err:
logger.error("Unable to establish connection to MySQL")
raise ConnectionAbortedError(err)
if (connection):
logger.info("Connection to MySQL successful")
return connection
else:
return None
db_mysql = MySQLConn()
some_func.py
from random_module.utils.db_module import db_mysql
def some_func():
try:
db_conn = db_mysql.get_conn()
db_cursor = db_conn.cursor()
results = db_cursor.execute("SELECT * FROM some_table")
results = db_cursor.fetchall()
result_set = []
for row in results:
result_set.insert(i, row['x'])
result_set.insert(i, row['y'])
except Exception:
logger.error("some error")
return result_set
dir struct -
src
├──pkg
| ├── common
| |___ some_func.py
| |___ __init__.py
|
| ├── utils
| |___ db_module.py
| |___ __init__.py
|
| __init__.py