import gc

from ewoksjob.client.celery.utils import get_not_finished_futures

from .. import testing


@testing.integration_fixture(autouse=True)
def cleanup_celery_jobs():
    yield
    futures = get_not_finished_futures()
    if futures:
        testing.print_message(
            f"{len(futures)} workflows are still running: abort them.", "warning"
        )
    for future in futures:
        _ = future.abort()
        try:
            _ = future.result(timeout=5)
        except Exception as ex:
            testing.print_message(f"Aborted workflow: {ex}", "warning")


@testing.integration_fixture
def gc_collect():
    while gc.collect():
        pass
    yield
    while gc.collect():
        pass
