0

Code for celery task:

import logging

from celery_once import QueueOnce
from celery import shared_task, current_task
from test.set_data import set_data_in_db

logger = logging.getLogger("celery")


@shared_task(base=QueueOnce, once={"graceful": True}, ignore_result=False)
def set_data_task():
    try:
        logger.info("Set data in db initiated")
        set_data_in_db(value=None)

    except Exception:
        logger.error("data could not be set", exc_info=True)

My unittest case is covering everything which is in the try block. How can I force my unittest to cover except block as well ?

ninjacode
  • 318
  • 2
  • 18

1 Answers1

0

When you call the method set_data_task , there could be only one situation out of two, either method executes normally (try block) or it throw some exception (except block).

If you need to test your except block , you need to configure your method to throw exception so that it could be caught and assert in your test

You will be in need to configure set_data_in_db method to throw exception to be caught

For testing exception, you can read pytest.raises

John Byro
  • 674
  • 3
  • 13
  • `set_data_task` function is a periodic task which is scheduled using django celery beat. This function will just execute the `set_data_in_db` task, except block is just to log the the errors in case task fails. I don't want to raise any exception. – ninjacode Nov 08 '21 at 08:16
  • 1
    if you wont raise any exception , then how would you test it?? You have to raise exception to test it – John Byro Nov 08 '21 at 08:24