gpt4 book ai didi

python - 是否可以对 celery 周期性任务进行单元测试?

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

我正在尝试对我设置为每天运行的 celery 任务运行单元测试。
我已经尝试导入该函数并在我的测试中调用它,但这不起作用。

任务是:

@shared_task

def create_a_notification_if_a_product_is_in_or_out_of_season():
"""
Send a notification if a product is now in or out of season
"""
julian_date = date.today().timetuple().tm_yday + 1
active_products = Product.objects.filter(status='ACTIVE')

for products in active_products:
in_season_prd = ProductDescription.objects.filter(
product=products,
early_start_julian=julian_date
)
for prd in in_season_prd:
notification = Notification()
notification.type = notification_choices.PRODUCT_IN_SEASON
notification.description = str(prd.product.name) + " will be in season from tomorrow."
notification.save()

这是我的一个测试示例:

def test_when_product_is_about_to_come_in_to_seasonality(self):
"""
Make a notification when a product is due to come in to seasonality tomorrow
"""
p = Product.objects.first()
p.status = "ACTIVE"
today = date.today().timetuple().tm_yday
p.early_start_julian = today + 1
create_a_notification_if_a_product_is_in_or_out_of_season()
updated_notifications = Notification.objects.all().count()
self.assertNotEqual(self.current_notifications, updated_notifications)

如有任何帮助,我们将不胜感激!

谢谢

最佳答案

您可以 apply()你的 celery 任务同步执行:

def test_when_product_is_about_to_come_in_to_seasonality(self):
"""
Make a notification when a product is due to come in to seasonality tomorrow
"""
p = Product.objects.first()
p.status = "ACTIVE"
today = date.today().timetuple().tm_yday
p.early_start_julian = today + 1
create_a_notification_if_a_product_is_in_or_out_of_season.apply()
updated_notifications = Notification.objects.all().count()
self.assertNotEqual(self.current_notifications, updated_notifications)

关于python - 是否可以对 celery 周期性任务进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45105046/

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