简体   繁体   English

当另一个 function 在 django 测试中执行时,如何测试 function 是否被调用?

[英]How to test if a function gets called when another function executes in django test?

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.我在管理器中有一个方法,此方法调用从不同模块导入的 function 现在我正在尝试编写一个测试,以确保在执行管理器方法时调用 function。 I've tried some methods by it didn't work here is the code example.我已经尝试了一些方法,但它不起作用,这里是代码示例。 hint: I'm using pytest as testrunner提示:我使用 pytest 作为 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()

I assume the function that you want to test is items_bulk_updated .我假设您要测试的 function 是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.由于您正在测试ItemsManager.bulk_update()并且您想要验证是否在该方法内调用了items_bulk_updated ,因此@mock.patch中的路径应该是导入 function 的文件路径,而不是其来源。 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.根据建议, <path-to-items-manager-file>ItemsManager class 的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM