python - pytest assert_used_with 不适用于 Django 管理命令

标签 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,但测试找不到该方法调用。似乎缺少上下文。你能帮忙吗?

最佳答案

您正在断言类本身,而不是类实例。示例:

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

关于python - pytest assert_used_with 不适用于 Django 管理命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56732294/

相关文章:

python - 为什么 -1/2 在 C++ 中评估为 0,但在 Python 中评估为 -1?

python - 为什么每次我在这个特定数据集上运行 train-test split 时我的内核都会死掉?

html - 将 Django 模板与 Div 导航栏链接起来

django - 如何在django admin中显示多行文本?

python - 如何分两个阶段进行 xpath 搜索?

python 3 : Does mysql db connection need to be explicitly closed in function?

python - Django 不加载静态文件 ValueError ("Missing staticfiles manifest entry for ' %s'"% clean_name)

python - 匹配多列值的函数

python - 在django和python中上传文件?

python - PyAudio 不会安装