gpt4 book ai didi

Python:模拟在 celery 任务中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:04 25 4
gpt4 key购买 nike

<分区>

我想使用 python mock 库来测试我的 Django 应用程序发送电子邮件。

测试代码:

# tests.py
from django.test import TestCase

class MyTestCase(TestCase):

@mock.patch('django.core.mail.mail_managers')
def test_canceled_wo_claiming(self, mocked_mail_managers):
client = Client()
client.get('/')
print(mocked_mail_managers.called)
mocked_mail_managers.assert_called_with('Hi, managers!', 'Message Body')

第一个例子——没有任务

# views.py
from django.views.generic import View
from django.core.mail import mail_managers

class MyView(View):

def get(self, request):
mail_managers('Hi, managers!', 'Message Body')
return HttpResponse('Hello!')

第二个例子 - 有任务

# views.py
from django.views.generic import View
from . import tasks

class MyView(View):
def get(self, request):
tasks.notify.apply_async()
return HttpResponse('Hello!')


# tasks.py
from celery import shared_task
from django.core.mail import mail_managers

@shared_task
def notify():
mail_managers('Hi, managers!', 'Message Body')

第一个例子正常,第二个例子失败,出现Not called异常。

我的设置:

# Celery
BROKEN_URL = 'memory://'
BROKER_BACKEND = 'memory'

CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'

是否可以执行这样的集成测试,或者解决此问题的唯一方法是将测试拆分为两个?

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