# Path: database.py
# def init_db():


import os
import sys
import time
import settings
from datetime import datetime
from sqlalchemy import func
from database import db_session
from models import *
    db_session.commit()


def do_running(version):
    query_base = db_session.query(func.count(TestRun.id))\
                           .filter(TestRun.version_id == version.id)\
                           .filter(TestRun.phase == version.phase)
    total = query_base.scalar()
    success = query_base.filter(TestRun.status == 'passed').scalar()
    failure = query_base.filter(~TestRun.status.in_(['pending', 'running', 'passed'])).scalar()

    if success + failure == total:
        print 'set next phase for version {0.id}, phase {0.phase}, status {0.status}'.format(version)
        if success == total:
            idx = settings.TEST_PHASES.index(version.phase)
            if idx == len(settings.TEST_PHASES) - 1:
                version.phase = 'end'
                version.status = 'passed'
            else:
                version.phase = settings.TEST_PHASES[idx+1]
                version.status = 'pending'
        else:
            version.status = 'failed'
        db_session.commit()


def main():
    print 'testrun_watcher started'
    while True:
        handler = {'running': do_running, 'pending': do_pending}

# Path: database.py
# def init_db():


# Path: core/testrun_watcher.py
import os
import sys
import time
import settings
from datetime import datetime
from sqlalchemy import func
from database import db_session
from models import *

    db_session.commit()


def do_running(version):
    query_base = db_session.query(func.count(TestRun.id))\
                           .filter(TestRun.version_id == version.id)\
                           .filter(TestRun.phase == version.phase)
    total = query_base.scalar()
    success = query_base.filter(TestRun.status == 'passed').scalar()
    failure = query_base.filter(~TestRun.status.in_(['pending', 'running', 'passed'])).scalar()

    if success + failure == total:
        print 'set next phase for version {0.id}, phase {0.phase}, status {0.status}'.format(version)
        if success == total:
            idx = settings.TEST_PHASES.index(version.phase)
            if idx == len(settings.TEST_PHASES) - 1:
                version.phase = 'end'
                version.status = 'passed'
            else:
                version.phase = settings.TEST_PHASES[idx+1]
                version.status = 'pending'
        else:
            version.status = 'failed'
        db_session.commit()


def main():
    print 'testrun_watcher started'
    while True:
        handler = {'running': do_running, 'pending': do_pending}

        versions = db_session.query(Version)\