gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:40:40 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com