Reputation: 2563
i have a function x
in main.applications.handlers
package
from main.config import get_db
def x(company_name):
db = get_db('my_db')
apps = []
for x in company_db.applications.find():
print(x)
apps.append(x)
return apps
now i want to write unittest for this method .
from unittest.mock import Mock,patch, MagicMock
@mock.patch('main.applications.handlers.get_db')
def test_show_applications_handler(self, mocked_db):
mocked_db.applications.find = MagicMock(return_value=[1,2,3])
apps = x('test_company') # apps should have [1,2,3] but its []
print(apps)
but company_db.applications.find()
inside main.applications.handlers
is not returning anything .it should return [1,2,3]
what could be wrong with this code?
Upvotes: 0
Views: 5976
Reputation: 23004
Assuming that company_db
is a typo and should be db
, then to mock the return value of find()
, you would do:
mocked_db.return_value.applications.find = MagicMock(return_value=[1,2,3])
mocked_db
requires a return_value
because get_db
is called with the database name.
You could also drop the MagicMock
and set the return_value
of find
directly:
mocked_db.return_value.applications.find.return_value = [1, 2, 3]
Upvotes: 2