繁体   English   中英

用Mock测试Django命令

[英]Testing Django Commands with Mock

我有一个我想测试的命令。 它命中外部服务,我想模拟出这些外部服务的函数调用,只检查它们是否使用正确的参数调用。 代码如下所示:

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. 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)

暂无
暂无

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

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