#!/usr/bin/env python
"""Run a bunch of threading programs with line tracing
to make sure we don't hang tracing them."""

import os, time

def run_test(test, wait_period):
    """Run the test 'test' in a separate process and sleep for 'wait_period'
    seconds. 'wait_period' should specify an optimal amount of time for
    'test' to finish. If the process hasn't finished by the time 
    'wait_period' seconds have passed, we assume that the test is hung.
    If the test has hung False is returned, otherwise True is returned.
    """
    pid = os.spawnlp(os.P_NOWAIT, 'python', 'python', 'tpdb.py', '--trace',
                    test)
    time.sleep(wait_period)
    ret = os.waitpid(pid, os.WNOHANG)
    if ret == (0,0):
        import signal
        os.kill(pid, signal.SIGKILL)
        return False
    else:
        return True
    
def main():
    # The way that I got the times  below was by timing each file on
    # my AMD64 machine and adding 5 seconds on to it. We may find that
    # these times are way too short.
    tests = [('t2.py', 5.0), ('q.py', 15.0), ('thread1.py',10.0)]
    failed_tests = []

    # Construct a test command suitable for passing to run_test
    for test in tests:
        filename = os.path.realpath(test[0])
        result = run_test(filename, test[1])
        if not result:
            failed_tests.append(test)
        
    if failed_tests:
        print '=' * 60
        print 'Failed Tests:\n'
        for failed in failed_tests:
            print failed[0]
        print '=' * 60
    else:
        print '=' * 60
        print 'All tests passed\n'
        print '=' * 60
        
if __name__ == '__main__':
    main()
