Home > Blockchain >  How to test if a function gets called when another function executes in django test?
How to test if a function gets called when another function executes in django test?

Time:12-01

I've a method inside a manager, this method calls a function imported from different module now I'm trying to write a test that make sure the function gets called, when the manager method executes. I've tried some methods by it didn't work here is the code example. hint: I'm using pytest as testrunner

from unittest import mock

# Customer Manager class
class ItemsManager(models.Manager):

    def bulk_update(self, *args, **kwargs):
        result = super().bulk_update(*args, **kwargs)
        items_bulk_updated(*args, **kwargs)
        return result


# signals.py file
def items_bulk_updated(*args, **kwargs):
    print("items bulk updated")


# test file
# Base TestCase Inherits from APITestCase
class TestItems(BaseTestCase):

    @mock.patch("items.signals.items_bulk_updated",autospec=True)
    def test_bulk_update_items_triggers_signal(self, mock_function):
        items_qs = Items.objects.all()
        result = Items.objects.bulk_update(items_qs, ['item_name'])
        mock_function.assert_called()

CodePudding user response:

I assume the function that you want to test is items_bulk_updated.

Since you are testing ItemsManager.bulk_update() and you want to verify that items_bulk_updated is being called inside that method, the path in your @mock.patch should be the file path where the function is being imported in instead of its origin. This means you need to update

@mock.patch("items.signals.items_bulk_updated", autospec=True)

to

@mock.patch("<path-to-items-manager-file>.items_bulk_updated", autospec=True)

where <path-to-items-manager-file> as suggested, is the path to your ItemsManager class.

  • Related