Skip to content
This repository has been archived by the owner on Dec 13, 2020. It is now read-only.

Test request context for unit tests #23

Open
dojeda opened this issue Jan 14, 2019 · 0 comments
Open

Test request context for unit tests #23

dojeda opened this issue Jan 14, 2019 · 0 comments

Comments

@dojeda
Copy link

dojeda commented Jan 14, 2019

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant