import json
import sys
from pprint import pprint
import xml.etree.cElementTree as ET
"""Small script to convert the JSON output from html-angular-validate-report
to a valid XML Testsuite File, so that Jenkins is able to parse it"""

reload(sys)
sys.setdefaultencoding('utf8')

with open('html-angular-validate-report.json') as data_file:
    data = json.load(data_file)

root = ET.Element("testsuite", {'name': 'html-angular-validate',
                               'tests': str(data['fileschecked']), 
                               'failures': str(data['filesfailed']),
                               'errors': '0' })

if not data['allpassed']:
    for err in data['failed']:
        case = ET.SubElement(root, "testcase", {'name': str(err['filepath'])})
        failure = ET.SubElement(case, "failure",{'message': 
                                str(len(err['errors'])) + ' Failure(s)' })
        errmsg = []
        
        for fail in err['errors']:
            errmsg.append('At line ' + str(fail['line']) 
                          + ': ' + str(fail['msg']) + '\n')
        
        failure.text = "".join(errmsg)

tree = ET.ElementTree(root)
ET.dump(tree)