Flask-Celery-Helper
Flask-Celery-Helper copied to clipboard
Test request context for unit tests
When using this helper library to unit test some celery tasks with eager_mode (I know this is not recommended but it fits my case), it can happen that SQLAlchemy model instances become unpersistent due to a new application context. The typical scenario is:
- code creates a model instance and commits it
- a celery task is called in eager_mode
- the remaining non-celery code now has a detached model instance and can fail with
DetachedInstanceError: Instance <SomeClass at 0x...> is not bound to a Session; attribute refresh operation cannot proceed
After banging my head for a whole afternoon I found some who had a similar problem https://blog.fossasia.org/detachedinstanceerror-dealing-with-celery-flasks-app-context-and-sqlalchemy/
In brief that this could be easily avoided if the ContextTask
is created as:
# Add Flask app context to celery instance.
class ContextTask(task_base):
"""Celery instance wrapped within the Flask app context."""
def __call__(self, *_args, **_kwargs):
if app.config['TESTING']:
with app.test_request_context():
return task_base.__call__(self, *_args, **_kwargs)
with app.app_context():
return task_base.__call__(self, *_args, **_kwargs)
Would this modification be sensible for this helper package? If so, I will gladly make a PR.