I'm trying to use pytest-mock
for mocking. This library is essentially a plugin/wrapper for mock
and patch
.
My problem is defined as:
I have an application (mymodule.py
) that uses SQL Alchemy. Basically, there's a function that defines some objects from SQL Alchemy and returns a dictionary with those objects.
def some_function1():
# some code
from sqlalchemy import create_engine, MetaData, Table
engine = create_engine(f"mysql+pymysql://{username}:{password}@{host}:{port}")
meta = MetaData(engine)
my_table = Table(
'my_table',
meta,
autoload=True,
schema="some_schema"
)
db_tools = {"engine": engine, "table": my_table}
return db_tools
Then, a second function takes that output dictionary as input and uses them:
def some_function2(db_tools, data):
sql_query = db_tools["table"].insert().values(data)
db_tools["engine"].execute(sql_query)
# some more code
So now I'm writing unit tests, and I don't want to actually communicate with the real database. So I just need to mock everything sqlalchemy
related. So far, I've managed to mock create_engine
, MetaData
and Table
by doing:
mocker.patch(
'my_module.create_engine',
return_value=True
)
mocker.patch(
'my_module.MetaData',
return_value=True
)
mocker.patch(
'my_module.Table',
return_value=True
)
That allows me to test some_function1
. But now I need to test some_function2
, which uses the methods or attributes .insert()
, .values
and .execute()
. How can I patch that?