0

I am having trouble mocking a certain function I can't get the asserts to work, here is my setup

in some_package.some_file.py

import SomeClass

def init_some_class(credentials)
    return SomeClass(
        username=credentials['username'], 
        password=credentials['password']
    )

In the main script package I use the above code as follows

from some_package.some_file import init_some_class

def business_logic(credentials, dict):
   api = init_some_class(credentials)
   try: 
       res = api.add_dict_to_db(dict)
       return True
   except ClientError:
      print("Something went wrong")
      return False

Now in the unit tests is where my troubles are

In test_main_script.py

from main import main
from unittest import mock
import mock

class MockSomeClass:
    def add_dict_to_db(self, dict):
        return {}

class TestMain(unittest.TestCase):

    @mock.patch('main.main.init_some_class')
    def test_business_logic(self, mock_init_some_class):
        mock_init_some_class.return_value = MockSomeClass()
        fake_dict = { 'key' : 'value' }
        fake_credentials = { 'username' : 'fake_user' , 'password' : '1234'}
        main.business_logic(fake_credentials, fake_dict)
        mock_init_some_class.return_value.add_dict_to_db.assert_called_once_with(fake_dict)

When I run my unit tests I get

>       mock_init_some_class.return_value.add_participant_to_entry.assert_called_once_with(fake_dict)
E       AttributeError: 'function' object has no attribute 'assert_called_once_with'
Ahmed Zaki
  • 23
  • 5
  • 1
    As the message says: your function does not have that attribute. You can only call that on a mock class (e.g. an instance of `Mock` or `MagicMock`). Is there a reason why you need your own mock class? It would probably work if you just removed that first line in the test. – MrBean Bremen Apr 27 '21 at 17:16
  • @MrBeanBremen you're awesome, thank you so much, it worked as you said ❤️ – Ahmed Zaki Apr 27 '21 at 17:26

0 Answers0