Example #1
0
 def _render(self, result):
     document = Document()
     testsuite = document.createElement('testsuite')
     testsuite.setAttribute('name', 'avocado')
     testsuite.setAttribute('tests', self._escape_attr(result.tests_total))
     testsuite.setAttribute('errors', self._escape_attr(result.errors + result.interrupted))
     testsuite.setAttribute('failures', self._escape_attr(result.failed))
     testsuite.setAttribute('skipped', self._escape_attr(result.skipped + result.cancelled))
     testsuite.setAttribute('time', self._escape_attr(result.tests_total_time))
     testsuite.setAttribute('timestamp', self._escape_attr(datetime.datetime.now()))
     document.appendChild(testsuite)
     for test in result.tests:
         testcase = self._create_testcase_element(document, test)
         status = test.get('status', 'ERROR')
         if status in ('PASS', 'WARN'):
             pass
         elif status == 'SKIP':
             testcase.appendChild(Element('skipped'))
         elif status == 'FAIL':
             element, system_out = self._create_failure_or_error(document,
                                                                 test,
                                                                 'failure')
             testcase.appendChild(element)
             testcase.appendChild(system_out)
         elif status == 'CANCEL':
             testcase.appendChild(Element('skipped'))
         else:
             element, system_out = self._create_failure_or_error(document,
                                                                 test,
                                                                 'error')
             testcase.appendChild(element)
             testcase.appendChild(system_out)
         testsuite.appendChild(testcase)
     return document.toprettyxml(encoding='UTF-8')
Example #2
0
	def send_server_status(self, status):
		doc = Document()
		rootNode = doc.createElement('server')
		rootNode.setAttribute("status", status)
		doc.appendChild(rootNode)
		response = self.send_packet("/server/status", doc)
		if response is False:
			Logger.warn("SMRequest::send_server_status Unable to send packet")
			return False
		
		document = self.get_response_xml(response)
		if document is None:
			Logger.warn("SMRequest::send_server_status response not XML")
			return False
		
		rootNode = document.documentElement
		
		if rootNode.nodeName != "server":
			Logger.error("SMRequest::send_server_status response not valid %s"%(rootNode.toxml()))
			return False
		
		if not rootNode.hasAttribute("name") or rootNode.getAttribute("name") != self.name:
			Logger.error("SMRequest::send_server_status response invalid name")
			return False
		
		if not rootNode.hasAttribute("status") or rootNode.getAttribute("status") != status:
			Logger.error("SMRequest::send_server_status response invalid status")
			return False
		
		return True
Example #3
0
    def storeToFile(self, suffix=""):
        if not self.dataToStore:
            return

        doc = Document()
        results = doc.createElement("results")
        doc.appendChild(results)
        for a in self.dataToStore:
            item = doc.createElement("item")
            for k, d in a.items():
                tag = doc.createElement(k)
                if k == "author":
                    tag2 = doc.createElement("name")
                    data = doc.createTextNode(d)
                    tag2.appendChild(data)
                    tag.appendChild(tag2)
                else:
                    data = doc.createTextNode(" ".join(d.split()))
                    tag.appendChild(data)
                item.appendChild(tag)
            results.appendChild(item)

        timestamp = time.strftime("%H%M%S_")
        f = open("output/" + timestamp + self.board + "_" + self.section + "_" + str(suffix) + ".xml", "w")
        f.write(doc.toprettyxml(indent="    ", encoding="utf-8"))
        f.close()
        self.dataToStore = []
    def testTaxes3(self):
        doc = Document()
        parent_node = doc.createElement('parent_node')
        doc.appendChild(parent_node)
        data = {
                'default-tax-table': {
                        'tax-rules': [
                            {
                                'shipping-taxed': False,
                                'rate': 0.08375,
                                'tax-area': {
                                    'us-zip-area': ['100*'],
                                 }
                            },
                            {
                                'shipping-taxed': True,
                                'rate': 0.04,
                                'tax-area': {
                                    'us-state-area': ['NY'],
                                 }
                            }
                        ]
                    }
        }
        self.gc._taxes(doc, parent_node, data)
        xml1 = "<parent_node><tax-tables><default-tax-table>\
<tax-rules><default-tax-rule><shipping-taxed>false</shipping-taxed>\
<rate>0.08375</rate><tax-area><us-zip-area><zip-pattern>100*</zip-pattern>\
</us-zip-area></tax-area></default-tax-rule>\
<default-tax-rule><shipping-taxed>true</shipping-taxed>\
<rate>0.04</rate><tax-area><us-state-area><state>NY</state></us-state-area>\
</tax-area></default-tax-rule>\
</tax-rules></default-tax-table></tax-tables></parent_node>"
        doc_good = parseString(xml1)
        self.assertEquals(doc.toxml(), doc_good.toxml())
    def testShippingExclude(self):
        doc = Document()
        parent_node = doc.createElement('parent_node')
        doc.appendChild(parent_node)
        data = {
            'us-state-area': ['AK','HI'],
            'us-zip-area': ['90210', '04005', '04092'],
            'us-country-area': 'CONTINENTAL_48',
            'world-area': True,
            'postal-area': [{
                'country-code': 'US',
                'postal-code-pattern': ['94043', '90211'],
                },
            ],
        }
        self.gc._shipping_allowed_excluded(doc, parent_node, data)
        xml1 = "<parent_node><us-state-area><state>AK</state></us-state-area>\
<us-state-area><state>HI</state></us-state-area>\
<us-zip-area><zip-pattern>90210</zip-pattern></us-zip-area>\
<us-zip-area><zip-pattern>04005</zip-pattern></us-zip-area>\
<us-zip-area><zip-pattern>04092</zip-pattern></us-zip-area>\
<us-country-area country-area='CONTINENTAL_48'/>\
<world-area/>\
<postal-area><country-code>US</country-code>\
<postal-code-pattern>94043</postal-code-pattern>\
<postal-code-pattern>90211</postal-code-pattern></postal-area>\
</parent_node>"
        doc_good = parseString(xml1)
        self.assertEquals(doc.toxml(), doc_good.toxml())
Example #6
0
def consoleElement(deviceType, port):
    """
    Creates a character device element, a <console> element, as a child
    of L{device element<devicesElement>}, that specifies the console character
    device to be used. Examples from libvirt.org:

    Domain Logfile: This disables all input on the character device, and
    sends output into the virtual machine's logfile.
        - type: stdio
        - port: 1

    @param deviceType: device type
    @type deviceType: String

    @param port: port number
    @type port: String

    @return: <console> element
    @rtype: String
    """
    document = Document()
    deviceElem = document.createElement('console')
    deviceElem.setAttribute('type', deviceType)
    portElem = document.createElement('target')
    portElem.setAttribute('port', port)
    deviceElem.appendChild(portElem)
    return deviceElem
Example #7
0
def questions_to_aiml(questions):
    punctuation = "\"`[email protected]#$%^&()-_=+[{]}\|;:',<.>/?"
    _puncStripRE = re.compile("[" + re.escape(punctuation) + "]")

    # Create the minidom document
    doc = Document()
    
    # Create the <aiml> base element
    aiml = doc.createElement("aiml")
    doc.appendChild(aiml)
    

    for question, answer in questions:        
        patterns = (re.sub(_puncStripRE, "", question), re.sub(_puncStripRE, "*", question))
        
        for p in patterns:
            category = doc.createElement("category") 
            pattern = doc.createElement("pattern") 
            pattern.appendChild(doc.createTextNode(p.upper()))  
            
            template = doc.createElement("template") 
            template.appendChild(doc.createTextNode(answer))
        
            category.appendChild(pattern)
            category.appendChild(template)
    
            aiml.appendChild(category)

    # Print our newly created XML
    return doc.toxml()
Example #8
0
def test_handle_repr_set(self):
    ''' '''
    emotionml = Document()
    repset_name = 'dimension-set'
    repset = Representation(name='fear', representation='dimension')
    emotionml = handle_repr_set(repset_name, repset, emotionml)
    print emotionml.toprettyxml()
Example #9
0
def createDoc(path):
    file = open(path, "w")
    doc = Document()
    wml = doc.createElement("data")
    doc.appendChild(wml)
    file.write(doc.toprettyxml(indent=" "))
    file.close()            
    def __init__(self, mlist, addPic, featurelist):
		#def __init__(self, mlist):
		Document.__init__(self)
		self.mlist=mlist
		self.addPic=addPic
		self.featurelist=featurelist
		self.generateXML()
	def __init__(self, data=None):
		Document.__init__(self)

		if data is not None:
			self.__dict__ = parseString(data).__dict__

		self.annotations = { }
Example #12
0
class pythonbits_config:
	"""Class for holding pythonbits config strings. read() or create_dom() must be called before first use. Access strings through obj.strings[key]"""
	def __init__(self):
		self.strings={}
		self.file=tempdir()+"config.xml"
		if not os.path.exists(self.file):
			update_url = "https://github.com/Ichabond/Pythonbits/raw/master/config.xml"
			opener = _MyOpener()
			nconf = opener.open(update_url)
			if (nconf.info()["Status"]=="200 OK"):
				open(tempdir()+"config.xml", "w").write(nconf.read())
			else:
				__logerror("Cannot update config file.")
			
		
	def __del__(self):
		self.file.close()

	def read(self, file=0):
		if(file==0):
			file=self.file
		self.xml = parse(file)
		self.load_strings()

	def write(self, file=0):
		if(file==0):
			file=self.file
		location = self.file.name
		file.close()
		file = open(location, "w")
		file.write(self.xml.toprettyxml())
		file.close()
		self.file = open(location, "r")

	def set_location(self, location):
		try:
			self.file = open(location, "r")
		except IOError:
			self.file = open(location, "w")

	def load_strings(self):
		for node in self.xml.getElementsByTagName("string"):
			self.strings[node.getAttribute("name")]=node.firstChild.data.replace('\n','').replace('\t','')

	def add_string(self, name, data):
		container = self.xml.getElementsByTagName("pythonbits")[0]
		stringtag = self.xml.createElement("string")
		stringtag.setAttribute("name", name)
		stringtag.appendChild(self.xml.createTextNode(data))
		container.appendChild(stringtag)
		self.load_strings()
	def del_string(self, name):
		del self.strings[name]
		###Horrible hack. Write real code.
		self.create_dom()
		for (name, entry) in self.strings.items():
			self.add_string(name, entry)
	def create_dom(self):
		self.xml = Document()
		self.xml.appendChild(self.xml.createElement("pythonbits"))
Example #13
0
def exportXacroRobot(robot):
    global output
    global name
    doc = Document()
    root = doc.createElement("robot")
    doc.appendChild(root)
    root.setAttribute("xmlns:xacro","http://www.ros.org/wiki/xacro")
    root.setAttribute("name",robot.name)
    if name == 'nao':
        root.appendChild(ur.short(doc,'xacro:include','filename',output[output.rfind('/')+1:output.find('.')]+ 'Transmission.xacro'))
        root.appendChild(ur.short(doc,'xacro:include','filename',output[output.rfind('/')+1:output.find('.')]+ 'Gazebo.xacro'))    
        root.appendChild(ur.short(doc,'xacro:include','filename',output[output.rfind('/')+1:output.find('.')]+ 'hands.xacro'))
    includeVisualCollision(robot)
    for i in dicXacro.keys():
        print "exporting " +str(dicXacro[i]) + ' xacro' 
        exportXacroRobotChain(robot,i)
        if output.find('/') != -1:
            filenamerobot = output[output.rfind('/')+1:output.find('.')]+ i + '.xacro'
        else : 
            filenamerobot = output[0:output.find('.')]+ i + str('.xacro')
        root.appendChild(ur.short(doc,'xacro:include','filename',filenamerobot))
## Transmission elements not available from Aldebaran libraries yet
#    exportXacroRobotElementList(robot,'Transmission')
## Plugin not implemented yet : neither mimic joints, camera or ros_control
#    exportXacroRobotElementList(robot,'Gazebo')
    root.appendChild(ur.short(doc,'xacro:include','filename',output[output.rfind('/')+1:output.find('.')]+ 'sensors.xacro'))
    exportSensorsXacro(robot,output[output.rfind('/')+1:output.find('.')]+ 'sensors.xacro')   
    root.appendChild(ur.short(doc,'xacro:include','filename',output[output.rfind('/')+1:output.find('.')]+ 'visual_collisions.xacro'))

    filename = output[0:output.find('.')]+ 'robot' + str('.xacro')
    print filename
    writeCommentedXacro(doc,filename)
Example #14
0
def exportXacroRobotElementList(robot,element):
    global output
    doc = Document()
    root = doc.createElement("robot")
    doc.appendChild(root)
    root.setAttribute("xmlns:xacro","http://www.ros.org/wiki/xacro")
    print 'create element file'
    for i in robot.elements:
        try:
            if element == 'Transmission':
                if i.name.find(element) != -1:
                    root.appendChild(i.to_xml(doc))
            elif element == 'Gazebo':
                if i.reference != None:
                    root.appendChild(i.to_xml(doc))
                elif i.plugins != []:
                    root.appendChild(i.to_xml(doc))
            elif element == 'material':
                if type(i) == romeo_description.urdf.Material:
                    root.appendChild(i.to_xml(doc))
        except AttributeError:
            pass
    filename = output[0:output.find('.')]+ str(element) + '.xacro'
    print filename
    writeCommentedXacro(doc, filename)   
Example #15
0
def devicesElement(*devices):
    """
    Creates a <devices> element, a child of L{domain element
    <domainElement>}, is the parent element for all devices.

    Devices:
    ========

    -L{<Emulator<emulatorElement>}
    -L{<Disk<diskElement>}
    -L{<Network<networkElement>}
    -L{<Input<inputElement>}
    -L{<Graphics<graphicsElement>}

    @param devices: tuple of Libvirt devices
    @type devices: DOM Element tuple

    @return: <devices> element
    @rtype: DOM Element
    """
    document = Document()
    deviceElem = document.createElement('devices')
    addDevice(deviceElem, devices)

    return deviceElem
Example #16
0
    def do_call_exit(self):
        if d.sessionProperties["persistent"]:
            mode = "suspend"
        else:
            mode = "logout"

        document = Document()
        rootNode = document.createElement("logout")
        rootNode.setAttribute("mode", mode)
        document.appendChild(rootNode)

        url = "%s/logout.php" % (self.base_url)
        request = urllib2.Request(url)
        request.add_header("Content-type", "text/xml; charset=UTF-8")
        request.add_data(document.toxml())

        try:
            url = self.urlOpener.open(request)

        except urllib2.HTTPError, exc:
            if exc.code == 500:
                Logger.warn("Service failurek")
                return False

            Logger.debug("HTTP request return code %d (%s)" % (exc.code, exc.msg))
            Logger.debug(" * return: %s" % (str(exc.read())))
            return False
Example #17
0
def graphicsElement(graphicsType, listen=None, port=None):
    """
    Creates a <graphics> element, a child of L{device element<devicesElement>},
    that specifies the graphics framebuffer device, either on the host or
    through a VNC server.

    @param graphicsType: frame buffer type: sdl or vnc
    @type graphicsType: String

    @param listen: IP address for VNC server
    @type listen: String

    @param port: port for VNC server
    @type port: String

    @return: <graphics> element
    @rtype: DOM Element
    """
    document = Document()
    elem = document.createElement('graphics')
    elem.setAttribute('type', graphicsType)
    if(listen != None):
        elem.setAttribute('listen', listen)
    if(port != None):
        elem.setAttribute('port', port)
    return elem
def _testElementReprAndStrUnicode():
    dom = Document()
    el = dom.appendChild(dom.createElement(u"abc"))
    string1 = repr(el)
    string2 = str(el)
    confirm(string1 == string2)
    dom.unlink()
Example #19
0
def parallalElement(deviceType, path, port):
    """
    Creates a character device element, a <parallel> element, as a child
    of L{device element<devicesElement>}, that specifies the parallel character
    device to be used.

    @param deviceType: device type
    @type deviceType: String

    @param path: source path
    @type path: String

    @param port: port number
    @type port: String

    @return: <parallel> element
    @rtype: DOM Element
    """
    document = Document()
    deviceElem = document.createElement('parallel')
    deviceElem.setAttribute('type', deviceType)
    portElem = document.createElement('source')
    portElem.setAttribute('path', path)
    portElem = document.createElement('target')
    portElem.setAttribute('port', port)
    deviceElem.appendChild(portElem)
    return deviceElem
def testAttributeRepr():
    dom = Document()
    el = dom.appendChild(dom.createElement(u"abc"))
    node = el.setAttribute("abc", "def")
    confirm(str(node) == repr(node))
    dom.unlink()
    confirm(len(Node.allnodes) == 0)
    def testTaxes2(self):
        doc = Document()
        parent_node = doc.createElement('parent_node')
        doc.appendChild(parent_node)
        data = {
                'default-tax-table': {
                    'tax-rules': [
                            {
                                'shipping-taxed': True,
                                'rate': 0.06,
                                'tax-area': {
                                    'us-state-area': ['CT'],
                                 }
                            },
                            {
                                'rate': 0.05,
                                'tax-area': {
                                    'us-state-area': ['MD'],
                                 }
                            }
                        ]
                    }
        }
        self.gc._taxes(doc, parent_node, data)
        xml1 = "<parent_node><tax-tables><default-tax-table><tax-rules>\
<default-tax-rule><shipping-taxed>true</shipping-taxed><rate>0.06</rate>\
<tax-area><us-state-area><state>CT</state></us-state-area></tax-area>\
</default-tax-rule><default-tax-rule><shipping-taxed>false</shipping-taxed>\
<rate>0.05</rate><tax-area><us-state-area><state>MD</state></us-state-area>\
</tax-area></default-tax-rule></tax-rules></default-tax-table></tax-tables>\
</parent_node>"
        doc_good = parseString(xml1)
        self.assertEquals(doc.toxml(), doc_good.toxml())
Example #22
0
def _note2musicxml(note):
    doc = Document()
    note_node = doc.createElement("note")
    if note==None:
        #note is a rest
        rest = doc.createElement("rest")
        note_node.appendChild(rest)
    else:
        #add pitch info
        pitch = doc.createElement("pitch")
        step = doc.createElement("step")
        step.appendChild(doc.createTextNode(note.name[:1]))
        pitch.appendChild(step)
        octave = doc.createElement("octave")
        octave.appendChild(doc.createTextNode(str(note.octave)))
        pitch.appendChild(octave)
        #check for alterations
        count = 0
        for i in note.name[1:]:
            if   i=="b": count-=1
            elif i=="#": count +=1
        if count != 0:
            alter = doc.createElement("alter")
            alter.appendChild(doc.createTextNode(str(count)))
            pitch.appendChild(alter)
            
        note_node.appendChild(pitch)

    return note_node
    def testTaxes7(self):
        doc = Document()
        parent_node = doc.createElement('parent_node')
        doc.appendChild(parent_node)
        data = {
                'default-tax-table': {
                        'tax-rules': [
                            {
                                'shipping-taxed': True,
                                'rate': 0.175,
                                'tax-area': {
                                    'postal-area': [
                                        {'country-code': 'DE'},
                                        {'country-code': 'ES'},
                                        {'country-code': 'GB'},
                                    ],
                                 },
                            },
                        ]
                    },
        }
        self.gc._taxes(doc, parent_node, data)
        xml1 = "<parent_node><tax-tables>\
<default-tax-table><tax-rules><default-tax-rule>\
<shipping-taxed>true</shipping-taxed><rate>0.175</rate>\
<tax-areas><postal-area><country-code>DE</country-code>\
</postal-area><postal-area><country-code>ES</country-code>\
</postal-area><postal-area><country-code>GB</country-code>\
</postal-area></tax-areas></default-tax-rule></tax-rules>\
</default-tax-table></tax-tables></parent_node>"
        doc_good = parseString(xml1)
        self.assertEquals(doc.toxml(), doc_good.toxml())
Example #24
0
 def formXml(self):
     """Form the XML to be written to RssFeeds.xml"""
     #create the document
     doc = Document()
     #create root element
     rssfeedsTag = doc.createElement('rssfeeds')
     doc.appendChild(rssfeedsTag)
     #create comments
     c1Tag = doc.createComment('RSS feeds. To have multiple feeds, just add a feed to the set. You can also have multiple sets.')
     c2Tag = doc.createComment('To use different sets in your skin, each must be called from skin with a unique id.')
     rssfeedsTag.appendChild(c1Tag)
     rssfeedsTag.appendChild(c2Tag)
     for setNum in sorted(self.feedsList.keys()):
         #create sets
         setTag = doc.createElement('set')
         #create attributes
         setTag.setAttribute('id', self.feedsList[setNum]['attrs']['id'])
         #only write rtl tags if they've been explicitly set
         if 'rtl' in self.feedsList[setNum]['attrs']:
             setTag.setAttribute('rtl', self.feedsList[setNum]['attrs']['rtl'])
         rssfeedsTag.appendChild(setTag)
         #create feed elements
         for feed in self.feedsList[setNum]['feedslist']:
             feedTag = doc.createElement('feed')
             feedTag.setAttribute('updateinterval', feed['updateinterval'])
             feedUrl = doc.createTextNode(feed['url'])
             feedTag.appendChild(feedUrl)
             setTag.appendChild(feedTag)
     return doc.toprettyxml(indent = '  ', encoding = 'UTF-8')
Example #25
0
File: xml.py Project: disqus/mule
 def generate_reports(self, test_runner):
     "Generates the XML reports to a given XMLTestRunner object."
     from xml.dom.minidom import Document
     all_results = self._get_info_by_testcase()
     
     if type(test_runner.output) == str and not \
         os.path.exists(test_runner.output):
         os.makedirs(test_runner.output)
     
     for suite, tests in all_results.items():
         doc = Document()
         
         # Build the XML file
         testsuite = _XMLTestResult._report_testsuite(suite, tests, doc)
         for test in tests:
             _XMLTestResult._report_testcase(suite, test, testsuite, doc)
         _XMLTestResult._report_output(suite, tests, test_runner, testsuite, doc)
         xml_content = doc.toprettyxml(indent='\t')
         
         if type(test_runner.output) is str:
             report_file = open(os.path.join(test_runner.output, '%s.xml' % (suite,)), 'w')
             try:
                 report_file.write(xml_content)
             finally:
                 report_file.close()
         else:
             # Assume that test_runner.output is a stream
             test_runner.output.write(xml_content)
 def createGeneralUnknownResponse(self, message):
     doc = Document()
     root_response = doc.createElement('Response')
     root_response.setAttribute("creationSuccessful", str(False))
     root_response.setAttribute("reason", message)
     doc.appendChild(root_response)
     return doc.toxml(encoding='utf-8')
Example #27
0
    def generate_document(self):
        doc = Document()
        Element = doc.createElement
        Text = doc.createTextNode

        rss = doc.appendChild(Element('rss'))
        rss.setAttribute('version', '2.0')

        channel = rss.appendChild(Element('channel'))
        for key in ('title', 'description', 'link'):
            value = getattr(self, key)
            channel.appendChild(Element(key)).appendChild(Text(value))
        date = format_rss_date(self._last_update or datetime.utcnow())
        channel.appendChild(Element('pubDate')).appendChild(Text(date))

        for item in self.items:
            d = Element('item')
            for key in ('title', 'author', 'link', 'description'):
                d.appendChild(Element(key)).appendChild(Text(item[key]))
            pub_date = format_rss_date(item['pub_date'])
            d.appendChild(Element('pubDate')).appendChild(Text(pub_date))
            d.appendChild(Element('guid')).appendChild(Text(item['link']))
            channel.appendChild(d)

        return doc
Example #28
0
    def generate_reports(self, test_runner):
        "Generates the XML reports to a given XMLTestRunner object."
        from xml.dom.minidom import Document
        all_results = self._get_info_by_testcase()

        if type(test_runner.output) == str and not \
            os.path.exists(test_runner.output):
            os.makedirs(test_runner.output)

        for suite, tests in all_results.items():
            doc = Document()

            # Build the XML file
            testsuite = _XMLTestResult._report_testsuite(suite, tests, doc)
            stdout, stderr = [], []
            for test in tests:
                _XMLTestResult._report_testcase(suite, test, testsuite, doc)
                if test.stdout:
                    stdout.extend(['*****************', test.get_description(), test.stdout])
                if test.stderr:
                    stderr.extend(['*****************', test.get_description(), test.stderr])
            _XMLTestResult._report_output(test_runner, testsuite, doc,
                                          '\n'.join(stdout), '\n'.join(stderr))
            xml_content = doc.toprettyxml(indent='\t')

            if type(test_runner.output) is str:
                report_file = open('%s%sTEST-%s.xml' % \
                    (test_runner.output, os.sep, suite), 'w')
                try:
                    report_file.write(xml_content)
                finally:
                    report_file.close()
            else:
                # Assume that test_runner.output is a stream
                test_runner.output.write(xml_content)
Example #29
0
 def generate_reports(self, test_runner):
     "Generates the XML reports to a given XMLTestRunner object."
     from xml.dom.minidom import Document
     all_results = self._get_info_by_testcase()
     
     if isinstance(test_runner.output, basestring) and not \
         os.path.exists(test_runner.output):
         os.makedirs(test_runner.output)
     
     for suite, tests in all_results.items():
         doc = Document()
         
         # Build the XML file
         testsuite = _XMLTestResult._report_testsuite(suite, tests, doc)
         for test in tests:
             _XMLTestResult._report_testcase(suite, test, testsuite, doc)
         _XMLTestResult._report_output(test_runner, testsuite, doc)
         xml_content = doc.toprettyxml(indent='\t', encoding="utf-8")
         
         if type(test_runner.output) in (str, unicode):
             report_file = file('%s%sTEST-%s.xml' % \
                 (test_runner.output, os.sep, suite), 'w')
             try:
                 report_file.write(xml_content)
             finally:
                 report_file.close()
         else:
             # Assume that test_runner.output is a stream
             test_runner.output.write(xml_content)
def export_robot_element(element):
    """
    Browse the 'elements' list of robot instance
    and export the ones related to the keyword 'element' given as a parameter

    :param : element, string in ['Transmission','Gazebo','material']

    The output file is <ROBOT>_<element>.xacro
    """
    global robot, OUTPUT
    doc = Document()
    root = doc.createElement("robot")
    doc.appendChild(root)
    root.setAttribute("xmlns:xacro","http://www.ros.org/wiki/xacro")
    for i in robot.elements:
        try:
            if element == 'Transmission':
                if i.name.find(element) != -1:
                    root.appendChild(i.to_xml(doc))
            elif element == 'Gazebo':
                if i.reference != None:
                    root.appendChild(i.to_xml(doc))
                elif i.plugins != []:
                    root.appendChild(i.to_xml(doc))
            elif element == 'material':
                if type(i) == naoqi_tools.urdf.Material:
                    root.appendChild(i.to_xml(doc))
        except AttributeError:
            pass
    filename = OUTPUT[0:OUTPUT.rfind('.')] + '_' + str(element) + '.xacro'
    print('exporting ' + element + ' xacro')
    write_comments_in_xacro(doc, filename)