0

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?

5
  • what do you get if you replace the x in apps = x('test_company') with find? Commented Dec 19, 2018 at 11:33
  • @Nick find is not defined error Commented Dec 19, 2018 at 11:35
  • @Nick i get <MagicMock name='get_db().applications.find()' id='140565332675720'> when i do print (company_db.applications.find()) inside x Commented Dec 19, 2018 at 11:37
  • i also tried this mocked_db.return_value.applications.return_value.find.return_value = [1,2,3] but same result Commented Dec 19, 2018 at 11:39
  • Is company_db a typo? I can't see where that is defined. Presumably it should be db? Commented Dec 19, 2018 at 17:44

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

@WillKeeping it worked when i used mocked_db().return_value.applications.find = MagicMock(return_value=[1,2,3]) but not with mocked_db.return_value.applications.find = MagicMock(return_value=[1,2,3])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.