pytest assert_called_with не работает с командами управления Django - PullRequest
1 голос
/ 24 июня 2019

Команда управления 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 Ответ

1 голос
/ 24 июня 2019

Вы утверждаете сам класс, а не его экземпляры. Пример:

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