pytest assert_call_with不适用于Django管理命令

时间:2019-06-24 08:05:40

标签: python django python-3.x mocking pytest

Django管理命令: my_custom_command.py

from django.core.management.base import BaseCommand

from services.external import ExternalApi


class Command(BaseCommand):
    def handle(self, *args, **options):
        api = ExternalApi()
        api.my_custom_method("param")

测试代码:

from django.core.management import call_command

from myapp.management.commands import my_custom_command


def test_custom_command(mocker):
    mocker.patch.object(my_custom_command, 'ExternalApi')
    call_command('my_custom_command')
    my_custom_command.ExternalApi.my_custom_method.assert_called_with('param')

结果:

    def test_custom_command(mocker):
        mocker.patch.object(my_custom_command, 'ExternalApi')
        call_command('my_custom_command')
>       my_custom_command.ExternalApi.my_custom_method.assert_called_with('param')
E       AssertionError: Expected call: my_custom_method('param')
E       Not called

尽管my_custom_method已被调用,但是测试找不到方法调用。似乎缺少上下文。你能帮忙吗?

1 个答案:

答案 0 :(得分:1)

您要声明类本身,而不是类实例。示例:

api_cls_mock = mocker.patch.object(my_custom_command, 'ExternalApi')
# this line will get the method mock of ExternalApi's instances:
meth_mock = api_mock.return_value.my_custom_method
call_command('my_custom_command')
# method mock will track the calls
meth_mock.assert_called_with('param')