Flask-Celery-Helper icon indicating copy to clipboard operation
Flask-Celery-Helper copied to clipboard

Test request context for unit tests

Open dojeda opened this issue 5 years ago • 0 comments

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:

  1. code creates a model instance and commits it
  2. a celery task is called in eager_mode
  3. 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.

dojeda avatar Jan 14 '19 19:01 dojeda