Monday, 28 October 2019

How to mock a imported object with pytest-mock or magicmock

I am trying to understand the mock/monkeypatch/pytest-mock capabilties. Let me know if this is possible and if not then suggestions on how I can test my existing code. My code structure:

/
./app
../__init__.py
../some_module1
.../__init__.py
../some_module2
.../__init__.py
./tests
../test_db.py

The /app/init.py is where my application (a flask application if it helps) is started along with initialing a db connection object:

...

def create_app():
  ...
  return app

db_conn = DB()

The "some_modlue1" and "some_module2" import the "db_conn" object and use it as part of their functions:

## some_module1/__init__.py
from app import db_conn

...
db = db_conn.db_name2.db_collection2

def some_func1():
  data = db.find()
  check and do something with data
  return true or false

...

## some_module2/__init__.py
from app import db_conn

...
db = db_conn.db_name1.db_collection1

def some_func2():
  data = db.find()
  check something with data
  return true or false
...

In my tests I want to test my code where based on the data I receive from db if my code reacts properly. I want to mock the database (using a mongo database), more specifically the "db_conn" object since I don't want to use a real database (lot of work setting and maintain the up environment, ...). Any suggestions on how I can emulate the db_conn? I've been exploring the pytest-mock, magicmock but I don't think or know how to mock the db_conn in my test. Any suggestions?



from How to mock a imported object with pytest-mock or magicmock

No comments:

Post a Comment