from __future__ import with_statement

def run_test_suite(suite, stdout):
    
    import subprocess
    from datetime import datetime
    
    start = datetime.now()

    process = subprocess.Popen(
        ( "phaser.regression", suite, "-o", "html" ),
        stdout = stdout,
        stderr = subprocess.STDOUT,
        )
    
    process.communicate()
    
    return ( process.returncode, datetime.now() - start )


if __name__ == "__main__":
    import argparse
    from phaser import test_runner
    ( tests_root, tests_in ) = test_runner.phaser_regression_tests()
    
    parser = argparse.ArgumentParser(
        description = "Run regression suite and package results" 
        )
    parser.add_argument(
        "--outfile",
        help = "output file",
        default = "phaser_test.pkl.gz"
        )
    parser.add_argument(
        "suite",
        choices = tests_in.keys(),
        nargs = "+",
        default = [],
        help = "test suites to run"
        )
    
    params = parser.parse_args()
    
    import platform
    architecture = "%s-%s-%s-%s" % (
        platform.machine(),
        platform.system(),
        platform.release(),
        platform.architecture()[0]
        )
    
    import gzip
    import pickle
    import tempfile
    import os.path
    
    with gzip.GzipFile( params.outfile, "w" ) as dataout:
        pickle.dump( architecture, dataout )
        
        for suite in params.suite:
            print "Running suite %s" % suite
            
            with tempfile.NamedTemporaryFile() as stdout:
                print "  Temporary file for log output: %s" % stdout.name
                ( returncode, runtime ) = run_test_suite( suite = suite, stdout = stdout )
                stdout.seek( 0 )
                pickle.dump( ( suite, returncode, runtime, stdout.read() ), dataout )
                print "  Output saved, removing temporary file"
            
            print "  Tests finished with return code %s" % returncode
            print "  Runtime: %s s" % runtime
            print
