是否可以对芹菜定期任务进行单元测试?

时间:2017-07-14 14:08:54

标签: python django python-3.x unit-testing 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)

任何帮助将不胜感激!

由于

2 个答案:

答案 0 :(得分:1)

你可以apply()你的芹菜任务同步执行它:

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)

答案 1 :(得分:0)

我认为您正在寻找CELERY_ALWAYS_EAGER设置。如果设置为True,它将同步运行您的任务。您可以在测试设置中进行设置,也可以仅使用@override_settings(CELERY_ALWAYS_EAGER=True)

修饰该测试