# pytest . && docker-compose -f docker/airflow-cluster/docker-compose-CeleryExecutor.yml up -d
# && sleep 30 && docker-compose -f docker/airflow-cluster/docker-compose-CeleryExecutor.yml down

# TODO
# 1: need some way to trigger a dag
# 2: need to cleanup rds resources in event of failure

from subprocess import check_output
import docker
from time import sleep

END_STRING = "Finished tests"


def remove_rds_instances():
    identifier = "zenyatta-smoke-tests-etl-20"
    remove_rds = check_output(['python', 'scripts/remove_rds_instances.py', '-p',
                               'twitch-web-dev', '-n', identifier])
    print(remove_rds.decode())


def shut_down_containers():
    smoke_tests_end = check_output(['/usr/local/bin/docker-compose', '-f',
                                    'docker/airflow-cluster/docker-compose-CeleryExecutor.yml',
                                    'down'])


def test_unit():
    initial_tests = check_output(['pytest', '.']).decode().split('\n')
    assert 'errors in' not in initial_tests[-2]
    assert initial_tests[-2].startswith('========================')


def test_smoke():
    shut_down_containers()
    smoke_tests_start = check_output(['/usr/local/bin/docker-compose', '-f',
                                      'docker/airflow-cluster/docker-compose-CeleryExecutor.yml',
                                      'up', '-d'])
    attempts = 20
    attempt = 0
    try:
        while attempt < attempts:
            attempt += 1
            client = docker.from_env()
            test_container = next(c for c in client.containers.list() if c.name.endswith('_tests_1'))
            logs = test_container.logs().decode()
            split_logs = logs.split('\n')
            if END_STRING in logs:
                # tests are done, ensure they succeed
                assert any('errors in' in log for log in split_logs) is False
                break
            else:
                test_container.restart()
                sleep(90)

    finally:
        # bring down docker
        # remove all zenyatta-smoke-tests-etl instances
        shut_down_containers()
        remove_rds_instances()
