[英]How to test if a function gets called when another function executes in django test?
我在管理器中有一个方法,此方法调用从不同模块导入的 function 现在我正在尝试编写一个测试,以确保在执行管理器方法时调用 function。 我已经尝试了一些方法,但它不起作用,这里是代码示例。 提示:我使用 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()
我假设您要测试的 function 是items_bulk_updated
。
由于您正在测试ItemsManager.bulk_update()
并且您想要验证是否在该方法内调用了items_bulk_updated
,因此@mock.patch
中的路径应该是导入 function 的文件路径,而不是其来源。 这意味着您需要更新
@mock.patch("items.signals.items_bulk_updated", autospec=True)
到
@mock.patch("<path-to-items-manager-file>.items_bulk_updated", autospec=True)
根据建议, <path-to-items-manager-file>
是ItemsManager
class 的路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.