#!/usr/bin/env python

import os
import sys

def usage():
    print >> sys.stderr, """Usage:
\trostest-check-results test-file.xml
or
\trostest-check-results --rostest pkg-name test-file.xml
"""
    print sys.argv
    sys.exit(os.EX_USAGE)

## writes a test failure out to test file if it doesn't exist
if __name__ == '__main__':
    if len(sys.argv) < 2:
        usage()
    if '--rostest' in sys.argv[1:]:
        if len(sys.argv) != 4:
            usage()
        test_pkg, test_file = [a for a in sys.argv[1:] if a != '--rostest']
        # this logic derives the output filename that rostest uses

        import roslib; roslib.load_manifest('rostest')
        import roslib.packages
        import rostest.rostestutil
        pkg_dir, _ = roslib.packages.get_dir_pkg(test_file) 
        outname = rostest.rostestutil.rostest_name_from_path(pkg_dir, test_file)
            
        test_file = rostest.rostestutil.xmlResultsFile(test_pkg, outname, is_rostest=True)            
    else:
        if len(sys.argv) != 2:
            usage()
        test_file = sys.argv[1]
        
    print "Checking for test results in %s"%test_file
    if not os.path.exists(test_file):
        if not os.path.exists(os.path.dirname(test_file)):
            os.makedirs(os.path.dirname(test_file))
        print "Cannot find results, writing failure results to", test_file
        f = open(test_file, 'w')
        try:
            test_name = os.path.basename(test_file)
            d = {'test': test_name, 'test_file': test_file }
            f.write("""<?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="1" failures="1" time="1" errors="0" name="%(test)s">
  <testcase name="test_ran" status="run" time="1" classname="Results">
    <failure message="Unable to find test results for %(test)s, test did not run.\nExpected results in %(test_file)s" type=""/>
  </testcase>
</testsuite>"""%d)
        finally:
            f.close()
            
