Example #1
0
    def makeXML(cls, name, memory, vcpu, *devices):
        
        if cls.domain_type is None:
            raise libvirt.libvirtError("%r can't be instanciated - no domain type" \
                                % cls)
            
        
        cfg = DomainConfig(name, memory, vcpu, devices)
        
        root = XMLBuilder('domain', type=cls.domain_type)

        cls.commonFields(root, cfg)
                    
        with root.os:
            cls.generateOS(root, cfg)
        
        root.clock(sync='localtime')
        
        cls.powerFeatures(root, cfg)
        
        with root.devices:
            cls.emulator(root, cfg)
            
            for dev in devices: 
                dev.toxml(root)
            
            cls.commonDevices(root, cfg)

        return root
Example #2
0
def pipeline_to_xml(p):
    """ Convert a Pipeline to XML

    :type p: Pipeline
    :param p:
    :return:
    """
    root = XMLBuilder(Constants.WORKFLOW_TEMPLATE_ROOT, id=p.idx)
    with getattr(root, Constants.ENTRY_POINTS):
        for eid, bid in p.entry_bindings:
            _d = {"id": eid, "in": bid}
            getattr(root, Constants.ENTRY_POINT)(**_d)
    with getattr(root, Constants.BINDINGS):
        for bout, bin_ in p.bindings:
            _d = {"out": bout, "in": bin_}
            getattr(root, Constants.BINDING)(**_d)

    # Engine level Options
    # for completeness write this element
    getattr(root, "options")

    # Task Options
    with getattr(root, "task-options"):
        for key, value in p.task_options.iteritems():
            _d = {"id": key}
            with getattr(root, 'option')(**_d):
                root.value(str(value))

    return root
Example #3
0
 def _generate_xml(self, exception,message = ""):
     _,_,trace = sys.exc_info()
     
     xml = XMLBuilder()
     
     tb_dict = {}
     tb = traceback.extract_tb(trace)
     
     with xml.notice(version = 2.0):
         xml << ('api-key', self.environment.api_key)
         with xml.notifier:
             xml << ('name', self.environment.name)
             xml << ('version', self.environment.version)
             xml << ('url', self.environment.url)
         with xml('server-environment'):
             xml << ('environment-name', self.environment.environment_name)
         with xml.error:
             xml << ('class', exception.__class__.__name__)
             if message == "":
                 xml << ('message', str(exception))
             else:
                 xml << ('message', str(exception) + '\n\n' + message)
             with xml.backtrace:
                 for trace in tb:
                     tb_dict['filename'] = trace[0]
                     tb_dict['line_number'] = trace[1]
                     tb_dict['function_name'] = trace[2]
                     xml << ('line', {
                         'file':tb_dict.get('filename', 'unknown'),
                         'number':tb_dict.get('line_number', 'unknown'),
                         'method':tb_dict.get('function_name', 'unknown')
                     })
             
     return str(xml)
Example #4
0
    def to_xml(self):
        """Return an XML instance of the suite"""

        x = XMLBuilder('testsuite', name=self.name, tests=str(self.ntests), errors=str(self.nerrors), failures=str(self.nfailure), skip=str(self.nskipped))

        for test_case in self.tests:
            classname = test_case.classname
            # sanitize for XML
            text = "" if test_case.text is None else test_case.text
            etype = "" if test_case.etype is None else test_case.etype

            with x.testcase(classname=classname, name=test_case.name,
                            result=test_case.result, etype=etype,
                            text=text):

                if test_case.result == 'failures':
                    x.error(type=test_case.etype, message=test_case.message)
                elif test_case.result == 'failure':
                    x.failure(type=test_case.etype, message=test_case.message)
                elif test_case.result == 'skipped':
                    x.skipped(type=test_case.etype, message=test_case.message)
                elif test_case.result == 'error':
                    x.error(type=test_case.etype, message=test_case.message)
                else:
                    # Successful testcase
                    pass
        return x
def checkstyle_xml(diags_set):

    def converted_severity(fauxpas_severity):
        # checkstyle severities: ignore, info, warning, error
        if (9 <= fauxpas_severity):
            return 'error'
        elif (5 <= fauxpas_severity):
            return 'warning'
        return 'info'

    x = XMLBuilder('checkstyle')
    diags_by_file = diags_set.grouped_diagnostics(by_property='file')
    for filepath, diags in diags_by_file.items():
        with x.file(name=filepath or diags_set.pbxproj_path):
            for diag in diags:
                message = diag.info
                if 0 < len(message):
                    message += ' '
                message += '(%s - %s)' % (diag.ruleName, diag.ruleDescription)
                x.error(severity=converted_severity(diag.severity),
                        source=diag.ruleShortName,
                        message=message,
                        line=str(diag.extent.start.line),
                        column=str(diag.extent.start.utf16Column)
                        )
    return str(x)
Example #6
0
 def testWith(self):
     xml = XMLBuilder()
     with xml.root(lenght = 12):
         pass
     self.assertEqual(str(xml),'<root lenght="12" />')
     
     xml = XMLBuilder()
     with xml.root():
         xml << "text1" << "text2" << ('some_node',)
     self.assertEqual(str(xml),"<root>text1text2<some_node /></root>")
Example #7
0
 def build_snapshot_xml(self, name=None, description=None):
     """
     :rtype : String
     :type name: String
     :type description: String
     """
     xml_builder = XMLBuilder('domainsnapshot')
     if not (name is None):
         xml_builder.name(name)
     if not (description is None):
         xml_builder.description(description)
     return str(xml_builder)
Example #8
0
def tree_to_xml(root):
    xml = XMLBuilder('map', version='0.9.0')
 
    def rec_tree(tree, xnode):
        if tree == {}:
            return
        xnode['folded'] = 'true'
        for key, subtree in tree.iteritems():
            rec_tree(subtree, xnode.node(text=key))
    xroot = xml.node(text='Categories')
    rec_tree(root, xroot)
    xroot['folded'] = 'false'
    return str(xml)
Example #9
0
 def testFormat(self):
     x = XMLBuilder('utf-8',format = True)
     with x.root():
         x << ('array',)
         with x.array(len = 10):
             with x.el(val = 0):
                 pass
             with x.el('xyz',val = 1):
                 pass
             x << ("el","abc",{'val':2}) << ('el',dict(val=3))
             x << ('el',dict(val=4)) << ('el',dict(val='5'))
             with x('sup-el',val = 23):
                 x << "test  "
     self.assertEqual(str(x),result1)
Example #10
0
def schema_options_to_xml(option_type_name, schema_options_d):
    """Option type name is the task-option or option"""

    x = XMLBuilder(Constants.WORKFLOW_TEMPLATE_PRESET_ROOT)

    # Need to do this getattr to get around how the API works
    with getattr(x, option_type_name):
        for option_id, schema in schema_options_d.iteritems():
            default_value = schema["properties"][option_id]["default"]
            if default_value is not None:
                with x.option(id=option_id):
                    default_value = schema["properties"][option_id]["default"]
                    x.value(str(default_value))

    return x
Example #11
0
    def toxml(self, hrn = None):
        xml = XMLBuilder(format = True, tab_step = "  ")
        with xml.RSpec(type="VINI"):
            if hrn:
                element = xml.network(name="Public_VINI", slice=hrn)
            else:
                element = xml.network(name="Public_VINI")
                
            with element:
                for site in self.getSites():
                    site.toxml(xml, hrn, self.nodes)
                for link in self.sitelinks:
                    link.toxml(xml)

        header = '<?xml version="1.0"?>\n'
        return header + str(xml)
Example #12
0
    def toxml(self):
        xml = XMLBuilder(format = True, tab_step = "  ")
        with xml.RSpec(type=self.type):
            if self.slice:
                element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
            else:
                element = xml.network(name=self.api.hrn)

            with element:
                if self.slice:
                    self.slice.toxml(xml)
                for site in self.getSites():
                    site.toxml(xml)
                for link in self.sitelinks:
                    link.toxml(xml)

        header = '<?xml version="1.0"?>\n'
        return header + str(xml)
Example #13
0
    def toxml(self):
        """
        Produce XML directly from the topology specification.
        """
        xml = XMLBuilder(format = True, tab_step = "  ")
        with xml.RSpec(type=self.type):
            if self.slice:
                element = xml.network(name=self.api.hrn, slice=self.slice.hrn)
            else:
                element = xml.network(name=self.api.hrn)
                
            with element:
                if self.slice:
                    self.slice.toxml(xml)
                for site in self.getSites():
                    site.toxml(xml)

        header = '<?xml version="1.0"?>\n'
        return header + str(xml)
Example #14
0
def export_to_xml(people, questions_to_export, user_id, can_view_email):
    response = HttpResponse(content_type = "application/xml")
    response['Content-Disposition'] = 'attachment; filename="sc4g-people.xml"'
    xml = XMLBuilder('volunteers')
    for person in people:
        with xml.volunteer:
            xml.firstName(person.user.first_name)
            xml.lastName(person.user.last_name)
            if (can_view_email):
                xml.email(person.user.email)
            with xml.form_responses:
                for key, value in get_card_fields_with_icons_together(person, user_id).items():
                    xml.form_response(value, question=key)

    response.content = str(xml)
    return response
Example #15
0
    def create_snapshot(self, domain, snapshot_name, \
                        snapshot_description):
        """Create VM snapshot
           connection: object with a connection to the Hypervisor
           domain: VM name
           snapshot_name
           snapshot_description
        """
        try:
            libvirt_domain = self.libvirt_connection.lookupByName(domain)
            xml_base = XMLBuilder('domainsnapshot')
            xml_base.name(snapshot_name)
            xml_base.description(snapshot_description)
            xml = str(xml_base)
            libvirt_domain.snapshotCreateXML(xml)
        except:
            print 'Unable to create snapshot'
            sys.exit(1)

        print 'Snapshot has been created successfully.'
Example #16
0
 def _generate_xml(self, exception):
     _,_,trace = sys.exc_info()
     
     xml = XMLBuilder()
     with xml.notice(version = 2.0):
         xml << ('api-key', self.environment.api_key)
         with xml.notifier:
             xml << ('name', self.environment.name)
             xml << ('version', self.environment.version)
             xml << ('url', self.environment.url)
         with xml('server-environment'):
             xml << ('environment-name', self.environment.environment_name)
         with xml.error:
             xml << ('class', exception.__class__.__name__)
             xml << ('message', str(exception))
             with xml.backtrace:
                 [xml << ('line', {'file':filename, 'number':line_number, 'method':function_name}) \
                 for filename, line_number, function_name, _ in traceback.extract_tb(trace)]
             
     return str(xml)
Example #17
0
 def _generate_xml(self, exception, additional_information=None):
     _,_,trace = sys.exc_info()
     
     xml = XMLBuilder()
     
     tb_dict = {}
     tb = traceback.extract_tb(trace)
     
     if tb:
         tb = tb[0]
         tb_dict['filename'] = tb[0]
         tb_dict['line_number'] = tb[1]
         tb_dict['function_name'] = tb[2]
     
     message = str(exception)
     if additional_information:
         message = 'error: %s, additional info: %s' % (message, additional_information)
     
     with xml.notice(version = 2.0):
         xml << ('api-key', self.api_key)
         with xml.notifier:
             xml << ('name', self.name)
             xml << ('version', self.version)
             xml << ('url', self.url)
         with xml('server-environment'):
             xml << ('environment-name', self.environment_name)
         with xml.error:
             xml << ('class', exception.__class__.__name__)
             xml << ('message', message)
             with xml.backtrace:
                 xml << ('line', {
                     'file':tb_dict.get('filename', 'unknown'),
                     'number':tb_dict.get('line_number', 'unknown'),
                     'method':tb_dict.get('function_name', 'unknown')
                 })
             
     return str(xml)
Example #18
0
    def _generate_xml(self, exception=None, request=None):
        _, _, trace = sys.exc_info()

        xml = XMLBuilder()

        tb_dict = {}
        tb = traceback.extract_tb(trace)

        if tb:
            tb = tb[0]
            tb_dict["filename"] = tb[0]
            tb_dict["line_number"] = tb[1]
            tb_dict["function_name"] = tb[2]

        site = Site.objects.get_current()
        with xml.notice(version=2.0):
            xml << ("api-key", self.settings["API_KEY"])
            with xml.notifier:
                xml << ("name", site.name)
                xml << ("version", "0.0.1")
                xml << ("url", site.domain)
            if request:
                with xml.request:
                    if request.is_secure():
                        scheme = "https"
                    else:
                        scheme = "http"
                    url = "%s://%s%s" % (scheme, request.get_host(), request.get_full_path())
                    xml << ("url", url)

                    cb, _, _ = resolve(request.path)
                    xml << ("component", cb.__module__)
                    xml << ("action", cb.__name__)

                    if len(request.POST):
                        with xml.params:
                            for key, val in request.POST.items():
                                xml << ("var", str(val), {"key": key})

                    session = request.session.items()
                    if len(session):
                        with xml.session:
                            for key, val in session.items():
                                xml << ("var", str(val), {"key": key})

                    with xml("cgi-data"):
                        for key, val in request.META.items():
                            xml << ("var", str(val), {"key": key})

            with xml("server-environment"):
                xml << ("environment-name", self.settings["ENVIRONMENT"])

            if exception:
                with xml.error:
                    xml << ("class", exception.__class__.__name__)
                    xml << ("message", str(exception))
                    with xml.backtrace:
                        xml << (
                            "line",
                            {
                                "file": tb_dict.get("filename", "unknown"),
                                "number": tb_dict.get("line_number", "unknown"),
                                "method": tb_dict.get("function_name", "unknown"),
                            },
                        )

        return str(xml)
Example #19
0
 def build_volume_xml(self, volume):
     """
     :type volume: Volume
         :rtype : String
     """
     volume_xml = XMLBuilder('volume')
     volume_xml.name(
         self._get_name(
             volume.environment and volume.environment.name or '',
             volume.name))
     volume_xml.capacity(str(volume.capacity))
     with volume_xml.target:
         volume_xml.format(type=volume.format)
     if volume.backing_store is not None:
         with volume_xml.backingStore:
             volume_xml.path(self.driver.volume_path(volume.backing_store))
             volume_xml.format(type=volume.backing_store.format)
     return str(volume_xml)
Example #20
0
    def build_network_xml(self, network):
        """
        :type network: Network
            :rtype : String
        """
        network_xml = XMLBuilder('network')
        network_xml.name(self._get_name(
            network.environment and network.environment.name or '',
            network.name))
        if not (network.forward is None):
            network_xml.forward(mode=network.forward)
        if not (network.ip_network is None):
            ip_network = IPNetwork(network.ip_network)
            with network_xml.ip(address=str(ip_network[1]), prefix=str(ip_network.prefixlen)):
                if network.has_pxe_server:
                    network_xml.tftp(root=network.tftp_root_dir)
                if network.has_dhcp_server:
                    with network_xml.dhcp:
                        network_xml.range(start=str(network.ip_pool_start),
                                          end=str(network.ip_pool_end))
                        for interface in network.interfaces:
                            for address in interface.addresses:
                                if IPAddress(address.ip_address) in ip_network:
                                    network_xml.host(
                                        mac=str(interface.mac_address),
                                        ip=str(address.ip_address),
                                        name=interface.node.name
                                    )
                        if network.has_pxe_server:
                            network_xml.bootp(file="pxelinux.0")

        return str(network_xml)
Example #21
0
    def build_node_xml(self, node, emulator):
        """
        :rtype : String
        :type node: Node
        """
        node_xml = XMLBuilder("domain", type=node.hypervisor)
        node_xml.name(
            self._get_name(node.environment and node.environment.name or '',
                           node.name))
        node_xml.vcpu(str(node.vcpu))
        node_xml.memory(str(node.memory * 1024), unit='KiB')

        with node_xml.os:
            node_xml.type(node.os_type, arch=node.architecture)
            for boot_dev in json.loads(node.boot):
                node_xml.boot(dev=boot_dev)

        with node_xml.devices:
            node_xml.emulator(emulator)
            if node.has_vnc:
                node_xml.graphics(type='vnc', listen='0.0.0.0', autoport='yes')

            for disk_device in node.disk_devices:
                self._build_disk_device(node_xml, disk_device)
            for interface in node.interfaces:
                self._build_interface_device(node_xml, interface)
        return str(node_xml)
Example #22
0
    def build_node_xml(self, node, spec):
        node_xml = XMLBuilder("domain", type=spec.hypervisor)
        node_xml.name(node.id)
        node_xml.vcpu(str(node.cpu))
        node_xml.memory(str(node.memory * 1024), unit='KiB')

        with node_xml.os:
            node_xml.type(spec.os_type, arch=node.arch)
            for boot_dev in node.boot:
                if boot_dev == 'disk':
                    node_xml.boot(dev="hd")
                else:
                    node_xml.boot(dev=boot_dev)

        ide_disk_names = deque(
            ['hd' + c for c in list('abcdefghijklmnopqrstuvwxyz')])
        serial_disk_names = deque(
            ['sd' + c for c in list('abcdefghijklmnopqrstuvwxyz')])

        def disk_name(bus='ide'):
            if str(bus) == 'ide':
                return ide_disk_names.popleft()
            return serial_disk_names.popleft()
        with node_xml.devices:
            node_xml.emulator(spec.emulator)

            if len(node.disks) > 0:
                node_xml.controller(type="ide")

            for disk in node.disks:
                with node_xml.disk(type="file", device="disk"):
                    node_xml.driver(
                        name="qemu", type=disk.format,
                        cache="unsafe")
                    node_xml.source(file=disk.path)
                    node_xml.target(dev=disk_name(disk.bus), bus=disk.bus)

            if node.cdrom:
                with node_xml.disk(type="file", device="cdrom"):
                    node_xml.driver(name="qemu", type="raw")
                    node_xml.source(file=node.cdrom.isopath)
                    node_xml.target(
                        dev=disk_name(node.cdrom.bus),
                        bus=node.cdrom.bus)

            for interface in node.interfaces:
                with node_xml.interface(type="network"):
                    node_xml.source(network=interface.network.id)
                    if not (interface.type is None):
                        node_xml.model(type=interface.type)

            for interface in node.bridged_interfaces:
                with node_xml.interface(type="bridge"):
                    node_xml.source(bridge=interface.bridge)
                    if not (interface.type is None):
                        node_xml.model(type=interface.type)

            if node.vnc:
                node_xml.graphics(type='vnc', listen='0.0.0.0', autoport='yes')

        return str(node_xml)
Example #23
0
    def make_story_xml(self, name=None, description=None, story_type=None,
                       owned_by=None, requested_by=None, estimate=None, current_state=None, labels=None):
        story = XMLBuilder('story')
        if name is not None:
            story.name(name)
        if description is not None:
            story.description(description)
        if requested_by is not None:
            story.requested_by(requested_by)
        if owned_by is not None:
            story.owned_by(owned_by)
        if story_type is not None:
            story.story_type(story_type)
        if estimate is not None:
            story.estimate(str(estimate), type='integer')
        if current_state is not None:
            story.current_state(current_state)
        if labels is not None:
            label_string = ','
            if labels:
                label_string = ','.join(labels)
            story.labels(label_string)

        return str(story)
Example #24
0
 def update_dhcpd(self):
   mac = re.sub('-',':',self.fuel['mac'])
   fuel = self.fuel
   ip = vlans[self.vlan]['network']
   filename = "/tmp/deploy." + str(os.getpid())
   x = XMLBuilder('network')
   x.name("lab" + str(self.vlan))
   x.bridge(name = "br"+self.vlan, stp="off", delay="0")
   with x.forward(mode = "route", dev="eth0"):
     x.interface(dev="eth0")
   with x.ip(address = str(ip.ip+1), netmask="255.255.255.192"):
     with x.dhcp:
       x.host(mac=mac, ip=str(ip.ip+2))
       x.bootp(file="pxelinux.0")
     x.tftp(root="/var/lib/tftpboot")
   print str(x)+"\n"
   f=open(filename,"w")
   f.write(str(x)+"\n")
   f.close()
   os.system("sudo ifconfig br%s down" % self.vlan)
   os.system("virsh net-destroy lab%s" % self.vlan)
   os.system("virsh net-create %s" % filename)
   os.system("sudo brctl addif br%s eth1.%s" % (self.vlan, self.vlan))
Example #25
0
    def build_network_xml(self, network):
        network_xml = XMLBuilder('network')
        network_xml.name(network.id)
        if not network.forward is None:
            network_xml.forward(mode=network.forward)

        if hasattr(network, 'ip_addresses') and not network.ip_addresses is None:
            with network_xml.ip(
                address=str(network.ip_addresses[1]),
                prefix=str(network.ip_addresses.prefixlen)
            ):
                if network.pxe:
                    network_xml.tftp(root=network.tftp_root_dir)
                if network.dhcp_server:
                    with network_xml.dhcp:
                        if hasattr(network, 'dhcp_dynamic_address_start'):
                            start = network.dhcp_dynamic_address_start
                        else:
                            start = network.ip_addresses[2]

                        if hasattr(network, 'dhcp_dynamic_address_end'):
                            end = network.dhcp_dynamic_address_end
                        else:
                            end = network.ip_addresses[
                                network.ip_addresses.numhosts - 2]
                        allowed_addresses = list(network.ip_addresses)[2: network.ip_addresses.numhosts - 2]
                        network_xml.range(start=str(start), end=str(end))
                        for interface in network.interfaces:
                            address = find(
                                lambda ip: ip in allowed_addresses,
                                interface.ip_addresses)
                            if address and interface.mac_address:
                                network_xml.host(
                                    mac=str(interface.mac_address),
                                    ip=str(address), name=interface.node.name)
                        if network.pxe:
                            network_xml.bootp(file="pxelinux.0")

        return str(network_xml)
Example #26
0
    def build_node_xml(self, node, emulator):
        """
        :rtype : String
        :type node: Node
        """
        node_xml = XMLBuilder("domain", type=node.hypervisor)
        node_xml.name(
            self._get_name(node.environment and node.environment.name or '',
                           node.name))
        with node_xml.cpu(mode='host-model'):
            node_xml.model(fallback='forbid')
        node_xml.vcpu(str(node.vcpu))
        node_xml.memory(str(node.memory * 1024), unit='KiB')

        with node_xml.os:
            node_xml.type(node.os_type, arch=node.architecture)
            for boot_dev in json.loads(node.boot):
                node_xml.boot(dev=boot_dev)

        with node_xml.devices:
            node_xml.emulator(emulator)
            if node.has_vnc:
                if node.vnc_password:
                    node_xml.graphics(
                        type='vnc',
                        listen='0.0.0.0',
                        autoport='yes',
                        passwd=node.vnc_password)
                else:
                    node_xml.graphics(
                        type='vnc',
                        listen='0.0.0.0',
                        autoport='yes')

            for disk_device in node.disk_devices:
                self._build_disk_device(node_xml, disk_device)
            for interface in node.interfaces:
                self._build_interface_device(node_xml, interface)
            with node_xml.video:
                node_xml.model(type='vga', vram='9216', heads='1')
            with node_xml.serial(type='pty'):
                node_xml.target(port='0')
            with node_xml.console(type='pty'):
                node_xml.target(type='serial', port='0')
        return str(node_xml)
Example #27
0
class TestXMLBuilder(object):
    def setUp(self):
        self.xml = XMLBuilder('root')
        self.xml['xml_header'] = False
        self.xml['formatted'] = False
    
    def test_very_simple(self):
        eq_(str(self.xml), "<root />")

    def test_xml_header(self):
        self.xml['xml_header'] = True
        eq_(str(self.xml), '<?xml version="1.0" encoding="utf-8" ?>\n<root />')

    def test_unicode(self):
        self.xml.t
        eq_(unicode(self.xml), u"<root><t /></root>")

    def test_simple1(self):
        self.xml.t
        eq_(str(self.xml), "<root><t /></root>")

    def test_simple2(self):
        self.xml.t("some_data")
        eq_(str(self.xml), "<root><t>some_data</t></root>")

    def test_simple3(self):
        self.xml.t(a='1')
        eq_(str(self.xml), '<root><t a="1" /></root>')

    def test_simple4(self):
        self.xml.t("some data", a='1')
        eq_(str(self.xml), '<root><t a="1">some data</t></root>')

    def test_simple5(self):
        self.xml << "some data"
        eq_(str(self.xml), '<root>some data</root>')

    def test_simple6(self):
        self.xml << "some data" << '111' << '222'
        eq_(str(self.xml), '<root>some data111222</root>')

    @raises(ValueError)
    def test_wrong_data1(self):
        self.xml << 3

    @raises(ValueError)
    def test_wrong_data2(self):
        self.xml.t(attr=3)

    @raises(ValueError)
    def test_wrong_data2(self):
        self.xml.t("some_data", attr=3)

    @raises(ValueError)
    def test_wrong_data2(self):
        self.xml.t(True, attr=3)

    @raises(ValueError)
    def test_wrong_data3(self):
        self.xml.t(3)

    test_formatter1_res = \
"""<root>
    <t1 m="1">
        <t2 />
    </t1>
    <t3>mmm</t3>
</root>"""

    def test_formatter1(self):
        self.xml['formatted'] = True
        self.xml.t1(m='1').t2
        self.xml.t3('mmm')
        
        eq_(str(self.xml), self.test_formatter1_res)

    test_formatter2_res = '<root>\n\t<t1 m="1">\n\t\t<t2 />\n\t</t1>\n\t<t3>mmm</t3>\n</root>'

    def test_formatter2(self):
        self.xml['formatted'] = True
        self.xml['tabstep'] = '\t'
        self.xml.t1(m='1').t2
        self.xml.t3('mmm')
        
        eq_(str(self.xml), self.test_formatter2_res)

    def test_attrib(self):
        self.xml.t1(m='1').t2
        self.xml.t3('mmm')
        eq_(str(self.xml), '<root><t1 m="1"><t2 /></t1><t3>mmm</t3></root>')

    def test_with1(self):
        with self.xml.tree_root:
            pass

        eq_(str(self.xml), "<root><tree_root /></root>")        

    def test_with2(self):
        with self.xml.tree_root('rr'):
            pass

        eq_(str(self.xml), "<root><tree_root>rr</tree_root></root>")        

    def test_with3(self):
        with self.xml.tree_root(a='dt'):
            pass

        eq_(str(self.xml), '<root><tree_root a="dt" /></root>')        

    def test_with4(self):
        with self.xml.tree_root('mm', a='dt'):
            pass

        eq_(str(self.xml), '<root><tree_root a="dt">mm</tree_root></root>')        

    def test_with5(self):
        with self.xml.tree_root(a='dt'):
            self.xml << '11'

        eq_(str(self.xml), '<root><tree_root a="dt">11</tree_root></root>')        

    def test_with6(self):
        with self.xml.tree_root(a='dt'):
            self.xml << '11'
            self.xml.tt

        eq_(str(self.xml), '<root><tree_root a="dt">11<tt /></tree_root></root>')        

    def test_unicode(self):
        with self.xml.tree_root(a=u'dt'):
            self.xml << u'11'
            self.xml.tt('12')

        eq_(str(self.xml), u'<root><tree_root a="dt">11<tt>12</tt></tree_root></root>')        

    def test_unicode1(self):
        with self.xml.tree_root(a=u'dt'):
            self.xml << u'11'
            self.xml.tt('12')

        eq_(unicode(self.xml),
            u'<root><tree_root a="dt">11<tt>12</tt></tree_root></root>')        

    def test_unicode2(self):
        with self.xml.tree_root(a=u'dt'):
            self.xml << u'бла-бла-бла'
            self.xml.tt('12')

        eq_(str(self.xml).decode('utf8'),
            u'<root><tree_root a="dt">бла-бла-бла<tt>12</tt></tree_root></root>')        

    def test_with_all(self):
        self.xml.top
        with self.xml.tree_root('some data', attr='12'):
            self.xml.child1
            self.xml.child2('child data', attr='11')
            with self.xml.tree_subroot(attr='13'):
                self.xml.very_child('very data')
                with self.xml.tree_subsubroot:
                    pass

        eq_(str(self.xml), '<root>' + 
                             '<top />' + 
                                '<tree_root attr="12">some data' + 
                                    '<child1 />' + 
                                    '<child2 attr="11">child data</child2>' +
                                    '<tree_subroot attr="13">' +
                                        '<very_child>very data</very_child>'
                                        '<tree_subsubroot />' +
                                    '</tree_subroot>' +
                                '</tree_root>' + 
                            '</root>')
Example #28
0
def convert_suite_and_result_to_xunit(suite, result, name="PysivXunitTestSuite"):
    """Custom a test suite and result to XML.

    The name is used to set the xml suitename for jenkins.

    <testsuite errors="1" failures="1" name="1234" skip="1" tests="5">

    :param suite: unittest.TestSuite
    :param result: unittest.TestResult
    :param name:

    :return: XML instance
    """

    # When a test fails in setUpClass, the result is a
    # unittest.suite._ErrorHolder rather than a TestCase. We need to handle
    # those differently.
    def parse_setupclass_error(klass_id):
        """Return what's inside the parentheses."""
        return re.search("(?<=\().*(?=\))", klass_id).group(0)

    # Test cls names/id
    names = 'errors skipped failures'.split()
    klass_results = {}
    for n in names:
        klass_results[n] = []
        for klass, out in getattr(result, n):
            if isinstance(klass, unittest.suite._ErrorHolder):
                klass_results[n].append(parse_setupclass_error(klass.id()))
            else:
                klass_results[n].append(klass.id())

    nskipped = len(klass_results['skipped'])
    nerrors = len(klass_results['errors'])
    nfailures = len(klass_results['failures'])

    def _to_key(test_case):
        # If the test_case is an _ErrorHolder, the key should be parsed from
        # the description. It won't have a _testMethodName
        if isinstance(test_case, unittest.suite._ErrorHolder):
            return parse_setupclass_error(test_case.description)
        m = test_case.__module__
        n = test_case.__class__.__name__
        mn = test_case._testMethodName
        # d = test_case._testMethodDoc
        # return m, n, mn, d
        return ".".join([m, n, mn])

    all_test_cases = {}
    for s in suite:
        if isinstance(s, unittest.suite.TestSuite):
            for tc in s:
                all_test_cases[_to_key(tc)] = None
        else:
            raise TypeError("Unsupported test suite case ({x})".format(x=type(s)))

    ntests = len(all_test_cases)

    # loop over failures, errors, skipped, assign message
    for n in names:
        # get all testcases with state
        ts = getattr(result, n)
        for t, msg in ts:
            k = _to_key(t)
            all_test_cases[k] = msg

    # import ipdb; ipdb.set_trace()

    # Create XML
    x = XMLBuilder('testsuite', name=name, tests=str(ntests),
                   errors=str(nerrors), failures=str(nfailures),
                   skip=str(nskipped))

    for idx, message in all_test_cases.iteritems():
        test_method = idx.split('.')[-1]
        with x.testcase(classname=idx, name=test_method, time="1.000"):
            if idx in klass_results['errors']:
                x.error(type="exceptions.Exception", message=message)
            elif idx in klass_results['failures']:
                x.failure(type="exceptions.Exception", message=message)
            elif idx in klass_results['skipped']:
                # print "skipped", idx
                x.skipped(type="unittest.case.SkipTest", message=message)
            else:
                # print "Success", idx
                pass

    return x
Example #29
0
 def make_comment_xml(self, text, author):
     note = XMLBuilder('note')
     note.text(text)
     if author is not None:
         note.author(author)
     return str(note)
Example #30
0
 def setUp(self):
     self.xml = XMLBuilder('root')
     self.xml['xml_header'] = False
     self.xml['formatted'] = False