def upgrade():
    query = db_utils.model_query(
        models.Test, db_api.get_session()).filter(
            models.Test.success > 0, models.Test.run_time == None).join(
                models.TestRun,
                models.Test.id == models.TestRun.test_id).filter_by(
                    status='success').values(models.Test.id,
                                             models.TestRun.start_time,
                                             models.TestRun.stop_time)

    results = {}
    for test_run in query:
        delta = read_subunit.get_duration(test_run[1], test_run[2])
        if test_run[0] in results:
            results[test_run[0]].append(delta)
        else:
            results[test_run[0]] = [delta]

    for test in results:
        avg = float(sum(results[test])) / float(len(results[test]))
        db_api.update_test({'run_time': avg}, test)
dataset/ETHPy150Open openstack-infra/subunit2sql/subunit2sql/migrations/versions/5332fe255095_populate_run_time_for_existing_tests.py/upgrade/original