我有一个要测试的命令。它打外部服务,我想模拟打打这些外部服务的函数调用,只检查是否使用正确的参数调用了它们。代码如下:
import mock
from django.core.management import call_command
from myapp.models import User
class TestCommands(TestCase):
def test_mytest(self):
import package
users = User.objects.filter(can_user_service=True)
with mock.patch.object(package, 'module'):
call_command('djangocommand', my_option=True)
package.module.assert_called_once_with(users)
但是,当我运行它时,我总是AssertionError: Expected to be called once. Called 0 times.
想这是因为我实际上没有在上下文中调用该模块,而是在中调用了它call_command('djangocommand', my_option=True)
,但是当上下文处于活动状态时,是否不应该模拟掉对该模块的所有调用?如果没有,是否有人建议如何进行这种测试?
您需要修补的参考是django.core.management中的“模块”属性参考。尝试模拟测试文件中的软件包引用不会更改django.core.management中的引用。
您需要做类似的事情
import mock
from django.core.management import call_command
import django.core.management
from myapp.models import User
class TestCommands(TestCase):
def test_mytest(self):
users = User.objects.filter(can_user_service=True)
with mock.patch.object(django.core.management, 'module'):
call_command('djangocommand', my_option=True)
django.core.management.module.assert_called_once_with(users)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句