Example #1
0
def uixml(scwin, uixslt):
    extidx = uixslt.rindex('.')
    xslt2 = uixslt[:extidx] + "Post" + uixslt[extidx:]
    sctemplate = XMLHelper.writexml(scwin.asXML(True), UnicodeStringIO(), '',
                                    '\t', '\n')

    try:
        source = DefaultFactory.fromString(sctemplate, "urn:pass1")
        xsltUri = OsPathToUri(uixslt)
        transform = DefaultFactory.fromUri(xsltUri)

        processor = Processor.Processor()
        processor.appendStylesheet(transform)
        uixmlstr = processor.run(source)

        if os.path.exists(xslt2):
            source = DefaultFactory.fromString(uixmlstr, "urn:pass2")
            xsltUri = OsPathToUri(xslt2)
            transform = DefaultFactory.fromUri(xsltUri)

            processor = Processor.Processor()
            processor.appendStylesheet(transform)
            uixmlstr = processor.run(source)
    except Exception, e:
        QMessageBox.critical(None, 'Error!',
                             'Error with XSLT transform!\n\n' + str(e), 'OK')
        return
Example #2
0
    def render_document(self, document, stylesheet, outfile):
        """
        This method is responsible for using 'stylesheet' to transform
        'document' to the file 'outfile'.

        Override this method to use a different XSLT rendering engine.
        """
        from Ft.Xml.InputSource import DefaultFactory
        from Ft.Xml.Xslt import Processor

        # Get a "clean" processor object
        if self._xslt_processor is None:
            self._xslt_processor = Processor.Processor()
        else:
            self._xslt_processor.reset()

        # Add the stylesheet to the processor object.
        isrc = DefaultFactory.fromUri(stylesheet.uri)
        try:
            self._xslt_processor.appendStylesheet(isrc)
        finally:
            isrc.close()

        params = {
            'name': self.distribution.get_name(),
            'version': self.distribution.version,
            'fullname': self.distribution.get_fullname(),
            'author': self.distribution.author,
            'author-email': self.distribution.author_email,
        }
        params.update(document.params)

        # Render the document
        isrc = DefaultFactory.fromUri(document.uri)
        try:
            if self.dry_run:
                stream = cStringIO.StringIO()
            else:
                self.mkpath(os.path.dirname(outfile))
                stream = open(outfile, 'w')
            try:
                try:
                    self._xslt_processor.run(isrc,
                                             topLevelParams=params,
                                             outputStream=stream)
                    stream.write('\n')
                finally:
                    stream.close()
            except:
                if not self.dry_run:
                    os.remove(outfile)
                raise
        finally:
            isrc.close()
        return
Example #3
0
def transform(xml, xsl):
    """
    A simple wrapper for 4XSLT.
    """
    from Ft.Xml.Xslt.Processor import Processor
    from Ft.Xml.InputSource import DefaultFactory
    proc = Processor()
    xslObj = DefaultFactory.fromString(xsl, "http://rantelope.com/")
    proc.appendStylesheet(xslObj)
    xmlObj = DefaultFactory.fromString(xml)
    return proc.run(xmlObj)
Example #4
0
    def render_document(self, document, stylesheet, outfile):
        """
        This method is responsible for using 'stylesheet' to transform
        'document' to the file 'outfile'.

        Override this method to use a different XSLT rendering engine.
        """
        from Ft.Xml.InputSource import DefaultFactory
        from Ft.Xml.Xslt import Processor

        # Get a "clean" processor object
        if self._xslt_processor is None:
            self._xslt_processor = Processor.Processor()
        else:
            self._xslt_processor.reset()

        # Add the stylesheet to the processor object.
        isrc = DefaultFactory.fromUri(stylesheet.uri)
        try:
            self._xslt_processor.appendStylesheet(isrc)
        finally:
            isrc.close()

        params = {'name' : self.distribution.get_name(),
                  'version' : self.distribution.version,
                  'fullname' : self.distribution.get_fullname(),
                  'author' : self.distribution.author,
                  'author-email' : self.distribution.author_email,
                  }
        params.update(document.params)

        # Render the document
        isrc = DefaultFactory.fromUri(document.uri)
        try:
            if self.dry_run:
                stream = cStringIO.StringIO()
            else:
                self.mkpath(os.path.dirname(outfile))
                stream = open(outfile, 'w')
            try:
                try:
                    self._xslt_processor.run(isrc, topLevelParams=params,
                                             outputStream=stream)
                    stream.write('\n')
                finally:
                    stream.close()
            except:
                if not self.dry_run:
                    os.remove(outfile)
                raise
        finally:
            isrc.close()
        return
Example #5
0
def Test(tester):
    # We don't use test_harness.XsltTest and friends because they hide away
    # the API details we're testing in this module.
    # See http://bugs.4suite.org/641693

    tester.startGroup("Test multiple stylesheet invokation")
    xp = Processor()
    xp.appendStylesheet(
        DefaultFactory.fromString(stylesheet_string, uri="data:ss"))
    result1 = xp.run(DefaultFactory.fromString(source_string, uri="data:src1"))
    result2 = xp.run(DefaultFactory.fromString(source_string, uri="data:src2"))
    tester.compare(result1, EXPECTED_1)
    tester.compare(result2, EXPECTED_1)
    tester.groupDone()
    return
Example #6
0
def test_decl_handler(tester):
    tester.startTest("DTDHandler")
    parser = CreateParser()
    handler = DeclHandler()
    parser.setProperty(property_declaration_handler, handler)

    parser.parse(DefaultFactory.fromString(DTD_CONTENT, "file:source"))

    elements = [
        (u'doc', u'(#PCDATA|e)*'),
        (u'e', u'EMPTY'),
    ]
    attributes = [
        (u'e', u'id', u'ID', u'#REQUIRED', None),
        (u'e', u'a1', u'CDATA', u'#IMPLIED', None),
        (u'e', u'enum', u'(v1|v2)', None, u'v1'),
    ]
    entities = [
        (u'e1', u'e1'),
        (u'%e2', u'e2'),
        (u'e3', None, u'file:entity.ent'),
    ]
    tester.compare(elements, handler.elements, "element decls")
    tester.compare(attributes, handler.attributes, "attribute decls")
    tester.compare(entities, handler.entities, "entity decls")
    tester.testDone()
Example #7
0
def Test(tester):
    tester.startGroup('pick stylesheet from xml-stylesheet PIs')
    for tup in tests:
        (title_st, source_st, expected_st) = tup[:3]
        errcode = None
        media = None
        if len(tup) > 3:
            errcode = tup[3]
        if len(tup) > 4:
            media = tup[4]
        expected = expected_st or ''
        source = test_harness.FileInfo(string=source_st, baseUri=uri)
        if media:
            proc = Processor.Processor()
            proc.mediaPref = media
            tester.startTest(title_st)
            isrc = DefaultFactory.fromString(source_st, uri)
            result = proc.run(isrc, ignorePis=0)
            tester.compare(expected_st, result, func=TreeCompare.TreeCompare)
            tester.testDone()
            del proc, isrc, result
        else:
            test_harness.XsltTest(tester, source, [], expected,
                                  exceptionCode=errcode,
                                  title=title_st, ignorePis=0)
    tester.groupDone()
    return
Example #8
0
def test_decl_handler(tester):
    tester.startTest("DTDHandler")
    parser = CreateParser()
    handler = DeclHandler()
    parser.setProperty(property_declaration_handler, handler)

    parser.parse(DefaultFactory.fromString(DTD_CONTENT, "file:source"))
    
    elements = [
        (u'doc', u'(#PCDATA|e)*'),
        (u'e', u'EMPTY'),
        ]
    attributes = [
        (u'e', u'id', u'ID', u'#REQUIRED', None),
        (u'e', u'a1', u'CDATA', u'#IMPLIED', None),
        (u'e', u'enum', u'(v1|v2)', None, u'v1'),
        ]
    entities = [
        (u'e1', u'e1'),
        (u'%e2', u'e2'),
        (u'e3', None, u'file:entity.ent'),
        ]
    tester.compare(elements, handler.elements, "element decls")
    tester.compare(attributes, handler.attributes, "attribute decls")
    tester.compare(entities, handler.entities, "entity decls")
    tester.testDone()
Example #9
0
    def download(self, xmlobj, whichStyleSheet="styleSheet.xsl"):
  
        """Download XML to EEPROM, use broken method. This will likely fail if
        line is longer than reciever's buffer size."""
        #xml = testmeasurements.get_string(xmlobj)
        xml = get_string(xmlobj)
        from Ft.Lib import Uri
        from Ft.Xml.Xslt import Transform
        from Ft.Xml.InputSource import DefaultFactory
        import os.path
        #STYLESHEET = os.path.join(os.environ["STRATATEST_HOME"], 'etc', 'styleSheet.xsl')
        STYLESHEET = os.path.join(os.environ["STRATATEST_HOME"], 'etc', whichStyleSheet)
        #print "XML: %s" % xml
        xsltFile = DefaultFactory.fromUri(Uri.OsPathToUri(STYLESHEET))
        result = Transform(xml, xsltFile)
        #print "******** result: %s ********" % result
        if (result == ""):
            # This is a fall back in case the xsl stylesheet found no matches.
            print >>sys.stderr, "Warning: XSL didn't match any xml elements."
            result = xml
            
        #5/16/07 - dave 
        #self._docommand("download clear")

        for line in result.split("\n"):
            self.info("line: %s" % line)
        time.sleep(1)
            #self._download_line(line)
        return  
    def __init__(self,iptFile,ctFile,truncTime):
        # Read epidemic and truncate to truncTime
        self.infectives = []
        self.labels = []
        epiFile = open(iptFile,'r')
        for line in epiFile:
            toks = line.split()
            label = atoi(toks[0])
            I = atof(toks[1])
            N = atof(toks[2])
            R = atof(toks[3])
            if N <= truncTime: # Take individuals who have been notified by truncTime
                if R > truncTime: # If R > truncTime, set R = truncTime
                    R = truncTime
                self.infectives.append(Infective(label,I,N,R))
                self.labels.append(label)
        epiFile.close()

                
        # Read in XML
        conFile = Uri.OsPathToUri(ctFile)
        xmlSrc = DefaultFactory.fromUri(conFile,stripElements=[(EMPTY_NAMESPACE,'*',1)])
        self.doc = NonvalidatingReader.parse(xmlSrc)

        # Remove from the contact DOM any contact info
        #   for individuals that are not present in labels
        self.labels = set(self.labels)
        for contact in self.doc.documentElement.xpath(u'tc:contact',explicitNss={u'tc':u'tracedcontacts'}):
            contactLabel = atoi(contact.getAttributeNS(None,u'id'))
            if contactLabel not in self.labels:
                self.doc.documentElement.removeChild(contact)
Example #11
0
    def build_static(self):
        documents = []
        for document in self.static:
            # Building is as simple as creating a new Document instance to
            # reflect the converted paths.
            document = copy.copy(document)
            document.source = util.convert_path(document.source)
            documents.append(document)

        # Validate the content
        if self.validate:
            from xml.sax.handler import feature_validation
            from Ft.Xml.InputSource import DefaultFactory
            from Ft.Xml.Sax import CreateParser

            class ErrorHandler:
                def __init__(self, displayhook):
                    self.displayhook = displayhook
                def warning(self, exception):
                    self.displayhook(exception)
                def error(self, exception):
                    self.displayhook(exception)
                def fatalError(self, exception):
                    raise exception

            parser = CreateParser()
            parser.setFeature(feature_validation, True)
            parser.setErrorHandler(ErrorHandler(self.warn))

            for document in documents:
                self.announce('validating %s' % document.source, 2)
                parser.parse(DefaultFactory.fromUri(document.source))
        return documents
Example #12
0
def Test(tester):
    tester.startGroup('pick stylesheet from xml-stylesheet PIs')
    for tup in tests:
        (title_st, source_st, expected_st) = tup[:3]
        errcode = None
        media = None
        if len(tup) > 3:
            errcode = tup[3]
        if len(tup) > 4:
            media = tup[4]
        expected = expected_st or ''
        source = test_harness.FileInfo(string=source_st, baseUri=uri)
        if media:
            proc = Processor.Processor()
            proc.mediaPref = media
            tester.startTest(title_st)
            isrc = DefaultFactory.fromString(source_st, uri)
            result = proc.run(isrc, ignorePis=0)
            tester.compare(expected_st, result, func=TreeCompare.TreeCompare)
            tester.testDone()
            del proc, isrc, result
        else:
            test_harness.XsltTest(tester,
                                  source, [],
                                  expected,
                                  exceptionCode=errcode,
                                  title=title_st,
                                  ignorePis=0)
    tester.groupDone()
    return
Example #13
0
def Test(tester):
    # We don't use test_harness.XsltTest and friends because they hide away
    # the API details we're testing in this module.
    # See http://bugs.4suite.org/641693

    tester.startGroup("Test multiple stylesheet invokation")
    xp = Processor()
    xp.appendStylesheet(DefaultFactory.fromString(stylesheet_string,
                                                  uri="data:ss"))
    result1 = xp.run(DefaultFactory.fromString(source_string,
                                     uri="data:src1"))
    result2 = xp.run(DefaultFactory.fromString(source_string,
                                     uri="data:src2"))
    tester.compare(result1, EXPECTED_1)
    tester.compare(result2, EXPECTED_1)
    tester.groupDone()
    return
Example #14
0
def test_locator_ft(tester):
    tester.startTest("4Suite InputSource")
    parser = CreateParser()
    parser.setContentHandler(LocatorTester(tester))
    parser.parse(DefaultFactory.fromUri(CONTENT_URI))
    verify_finished_locator(tester, parser)
    tester.testDone()
    return
Example #15
0
def test_locator_ft(tester):
    tester.startTest("4Suite InputSource")
    parser = CreateParser()
    parser.setContentHandler(LocatorTester(tester))
    parser.parse(DefaultFactory.fromUri(CONTENT_URI))
    verify_finished_locator(tester, parser)
    tester.testDone()
    return
Example #16
0
def test_errors_location(tester):
    tester.startTest("Location")
    parser = CreateParser()
    content = "<foo bar foorbar>"
    uri = "urn:test:source"
    try:
        parser.parse(DefaultFactory.fromString(content, uri))
    except SAXParseException, e:
        tester.compare(uri, e.getSystemId())
Example #17
0
def test_errors_incomplete(tester):
    tester.startTest("Incomplete Parsing")
    parser = CreateParser()
    content = "<foo>"
    uri = "urn:test:source"
    try:
        parser.parse(DefaultFactory.fromString(content, uri))
    except SAXParseException, e:
        pass
Example #18
0
def test_xmlreader_ft(tester):
    tester.startTest("4Suite InputSource")
    parser = CreateParser()
    builder = DomBuilder()
    parser.setContentHandler(builder)
    parser.parse(DefaultFactory.fromUri(CONTENT_URI))
    tester.compare(XMLREADER_CONTENT, builder, func=compare_builder)
    tester.testDone()
    return
def main():
    """
    """
    feed_format = ( len(sys.argv) > 1 ) and sys.argv[1] or 'atom'
    feed_url    = ( len(sys.argv) > 2 ) and sys.argv[2] or FEED_URL
    
    source    = DefaultFactory.fromUri(feed_url)
    
    trans_fin = open('ch14_xslt_normalizer.xsl', 'r')
    trans_url = 'http://www.decafbad.com/2005/04/ch14_xslt_normalizer.xsl'
    transform = DefaultFactory.fromStream(trans_fin, trans_url)
    
    processor = Processor.Processor()
    processor.appendStylesheet(transform)
    
    result = processor.run(source, 
                           topLevelParams={'format':feed_format})
    print result
Example #20
0
def test_errors_location(tester):
    tester.startTest("Location")
    parser = CreateParser()
    content = "<foo bar foorbar>"
    uri = "urn:test:source"
    try:
        parser.parse(DefaultFactory.fromString(content, uri))
    except SAXParseException, e:
        tester.compare(uri, e.getSystemId())
Example #21
0
def test_xmlreader_ft(tester):
    tester.startTest("4Suite InputSource")
    parser = CreateParser()
    builder = DomBuilder()
    parser.setContentHandler(builder)
    parser.parse(DefaultFactory.fromUri(CONTENT_URI))
    tester.compare(XMLREADER_CONTENT, builder, func=compare_builder)
    tester.testDone()
    return
Example #22
0
def test_errors_incomplete(tester):
    tester.startTest("Incomplete Parsing")
    parser = CreateParser()
    content = "<foo>"
    uri = "urn:test:source"
    try:
        parser.parse(DefaultFactory.fromString(content, uri))
    except SAXParseException, e:
        pass
Example #23
0
def Test(tester):
    # We don't use test_harness.XsltTest and friends because they hide
    # away the API details we're testing in this module.
    # See http://bugs.4suite.org/641693
    tester.startGroup("Test multiple stylesheet invokation")
    transform = DefaultFactory.fromString(TRANSFORM_2, "http://foo.com/")
    processor.appendStylesheet(transform)

    results = ["<xml><aaa>nope</aaa></xml>",
               "<xml><aaa>now</aaa></xml>",
               "<xml><aaa>now</aaa></xml>"]

    for x in range(0,2):
        SOURCE = results[x]
        source = DefaultFactory.fromString(SOURCE, "file:bogus.xml")
        result = processor.run(source)
        tester.compare(result, EXPECTED)

    tester.groupDone()
    return
Example #24
0
def Test(tester):
    # We don't use test_harness.XsltTest and friends because they hide
    # away the API details we're testing in this module.
    # See http://bugs.4suite.org/641693
    tester.startGroup("Test multiple stylesheet invokation")
    transform = DefaultFactory.fromString(TRANSFORM_2, "http://foo.com/")
    processor.appendStylesheet(transform)

    results = [
        "<xml><aaa>nope</aaa></xml>", "<xml><aaa>now</aaa></xml>",
        "<xml><aaa>now</aaa></xml>"
    ]

    for x in range(0, 2):
        SOURCE = results[x]
        source = DefaultFactory.fromString(SOURCE, "file:bogus.xml")
        result = processor.run(source)
        tester.compare(result, EXPECTED)

    tester.groupDone()
    return
Example #25
0
    def build_dom_and_apply_style_sheet(self, xsl, file):
        #doc = xml.dom.minidom.Document()
        doc = implementation.createRootNode('file:///article.xml')

        self.app.ann_frame.build_xml(doc)
            
        xsltproc = Processor()
        xsltproc.appendStylesheet(DefaultFactory.fromUri(Uri.OsPathToUri(xsl)))
        output = xsltproc.runNode(doc, 'file:///article.xml')

        outFile = open(file,'w')
        outFile.write(output)
        outFile.close()                  
Example #26
0
    def build_dom_and_apply_style_sheet(self, xsl, file):
        #doc = xml.dom.minidom.Document()
        doc = implementation.createRootNode('file:///article.xml')

        self.app.ann_frame.build_xml(doc)

        xsltproc = Processor()
        xsltproc.appendStylesheet(DefaultFactory.fromUri(Uri.OsPathToUri(xsl)))
        output = xsltproc.runNode(doc, 'file:///article.xml')

        outFile = open(file, 'w')
        outFile.write(output)
        outFile.close()
Example #27
0
def test_lexical_handler(tester):
    tester.startTest("LexicalHandler")
    parser = CreateParser()
    handler = LexicalHandler()
    parser.setProperty(property_lexical_handler, handler)

    parser.parse(DefaultFactory.fromString(DTD_CONTENT, "file:source"))
    
    events = [('startDTD', (u'doc', None, None)),
              ('endDTD', ()),
              ('startCDATA', ()),
              ('endCDATA', ()),
              ]
    comments = [u'LexicalHandler']
    tester.compare(events, handler.events, "events")
    tester.compare(comments, handler.comments, "comments")
    tester.testDone()
Example #28
0
def test_lexical_handler(tester):
    tester.startTest("LexicalHandler")
    parser = CreateParser()
    handler = LexicalHandler()
    parser.setProperty(property_lexical_handler, handler)

    parser.parse(DefaultFactory.fromString(DTD_CONTENT, "file:source"))

    events = [
        ('startDTD', (u'doc', None, None)),
        ('endDTD', ()),
        ('startCDATA', ()),
        ('endCDATA', ()),
    ]
    comments = [u'LexicalHandler']
    tester.compare(events, handler.events, "events")
    tester.compare(comments, handler.comments, "comments")
    tester.testDone()
Example #29
0
def test_dtd_handler(tester):
    tester.startTest("DTDHandler")
    parser = CreateParser()
    dtdhandler = DTDHandler()
    parser.setDTDHandler(dtdhandler)

    parser.parse(DefaultFactory.fromString(DTD_CONTENT, "file:source"))

    notations = [
        (u'GIF',
         u'-//CompuServe//NOTATION Graphics Interchange Format 89a//EN', None),
    ]
    entities = [
        (u'img', None, u'file:expat.gif', u'GIF'),
    ]
    tester.compare(notations, dtdhandler.notations, "notations")
    tester.compare(entities, dtdhandler.entities, "unparsed entities")
    tester.testDone()
Example #30
0
def test_dtd_handler(tester):
    tester.startTest("DTDHandler")
    parser = CreateParser()
    dtdhandler = DTDHandler()
    parser.setDTDHandler(dtdhandler)

    parser.parse(DefaultFactory.fromString(DTD_CONTENT, "file:source"))
    
    notations = [
        (u'GIF',
         u'-//CompuServe//NOTATION Graphics Interchange Format 89a//EN',
         None),
        ]
    entities = [
        (u'img', None, u'file:expat.gif', u'GIF'),
        ]
    tester.compare(notations, dtdhandler.notations, "notations")
    tester.compare(entities, dtdhandler.entities, "unparsed entities")
    tester.testDone()
Example #31
0
def test_attrs_empty(tester):
    tester.startTest("Empty")
    parser = CreateParser()
    gatherer = AttributesGatherer()
    parser.setContentHandler(gatherer)

    content = "<doc/>"

    parser.parse(DefaultFactory.fromString(content, "urn:test:source"))
    attrs = gatherer._attrs
    name = (TEST_NAMESPACE, "attr")
    try:
        attrs.getValue(name)
    except KeyError:
        pass
    else:
        tester.error("getValue")
    try:
        attrs[name]
    except KeyError:
        pass
    else:
        tester.error("__getitem__")
    try:
        attrs.getQNameByName(name)
    except KeyError:
        pass
    else:
        tester.error("getQNameByName")
    tester.compare(0, len(attrs), "__len__")
    tester.compare(False, name in attrs, "__contains__")
    tester.compare(False, attrs.has_key(name), "has_key")
    tester.compare(None, attrs.get(name), "get")
    tester.compare(25, attrs.get(name, 25), "get")
    tester.compare([], attrs.keys(), "keys")
    tester.compare([], attrs.items(), "items")
    tester.compare([], attrs.values(), "values")
    tester.testDone()
    return
Example #32
0
def test_attrs_empty(tester):
    tester.startTest("Empty")
    parser = CreateParser()
    gatherer = AttributesGatherer()
    parser.setContentHandler(gatherer)

    content = "<doc/>"
    
    parser.parse(DefaultFactory.fromString(content, "urn:test:source"))
    attrs = gatherer._attrs
    name = (TEST_NAMESPACE, "attr")
    try:
        attrs.getValue(name)
    except KeyError:
        pass
    else:
        tester.error("getValue")
    try:
        attrs[name]
    except KeyError:
        pass
    else:
        tester.error("__getitem__")
    try:
        attrs.getQNameByName(name)
    except KeyError:
        pass
    else:
        tester.error("getQNameByName")
    tester.compare(0, len(attrs), "__len__")
    tester.compare(False, name in attrs, "__contains__")
    tester.compare(False, attrs.has_key(name), "has_key")
    tester.compare(None, attrs.get(name), "get")
    tester.compare(25, attrs.get(name, 25), "get")
    tester.compare([], attrs.keys(), "keys")
    tester.compare([], attrs.items(), "items")
    tester.compare([], attrs.values(), "values")
    tester.testDone()
    return
Example #33
0
def test_attrs_specified(tester):
    tester.startTest("Specified")
    parser = CreateParser()
    gatherer = AttributesGatherer()
    parser.setContentHandler(gatherer)

    content = "<doc xmlns:ns='%s' ns:attr='val'/>" % str(TEST_NAMESPACE)

    parser.parse(DefaultFactory.fromString(content, "urn:test:source"))
    attrs = gatherer._attrs
    name = (TEST_NAMESPACE, "attr")
    tester.compare(u"val", attrs.getValue(name), "getValue")
    tester.compare(u"val", attrs[name], "__getitem__")
    tester.compare(u"ns:attr", attrs.getQNameByName(name), "getQNameByName")
    tester.compare(1, len(attrs), "__len__")
    tester.compare(True, name in attrs, "__contains__")
    tester.compare(True, attrs.has_key(name), "has_key")
    tester.compare(u"val", attrs.get(name), "get")
    tester.compare(u"val", attrs.get(name, 25), "get")
    tester.compare([name], attrs.keys(), "keys")
    tester.compare([(name, u"val")], attrs.items(), "items")
    tester.compare([u"val"], attrs.values(), "values")
    tester.testDone()
    return
Example #34
0
def test_attrs_specified(tester):
    tester.startTest("Specified")
    parser = CreateParser()
    gatherer = AttributesGatherer()
    parser.setContentHandler(gatherer)

    content = "<doc xmlns:ns='%s' ns:attr='val'/>" % str(TEST_NAMESPACE)
    
    parser.parse(DefaultFactory.fromString(content, "urn:test:source"))
    attrs = gatherer._attrs
    name = (TEST_NAMESPACE, "attr")
    tester.compare(u"val", attrs.getValue(name), "getValue")
    tester.compare(u"val", attrs[name], "__getitem__")
    tester.compare(u"ns:attr", attrs.getQNameByName(name), "getQNameByName")
    tester.compare(1, len(attrs), "__len__")
    tester.compare(True, name in attrs, "__contains__")
    tester.compare(True, attrs.has_key(name), "has_key")
    tester.compare(u"val", attrs.get(name), "get")
    tester.compare(u"val", attrs.get(name, 25), "get")
    tester.compare([name], attrs.keys(), "keys")
    tester.compare([(name, u"val")], attrs.items(), "items")
    tester.compare([u"val"], attrs.values(), "values")
    tester.testDone()
    return
Example #35
0
def compare_builder(expected, builder):
    isrc = DefaultFactory.fromString(expected, "urn:test:expected")
    expected = NonvalParse(isrc)
    return not TreeCompare.NodeCompare(expected, builder.getDocument())
import Ft
from Ft.Xml.InputSource import DefaultFactory
import trace,sys


from xml.xpath import Context, Util

ancienset = Ft.Xml.Xslt.XsltContext.XsltContext.set
def mongetattr(ins,attname):
  print "Aie!"
  return None

def monset(ins,d):
  print "On défini un truc sur le contexte"
  ancienset(ins,d)
  

def monsetattr(ins,attname,val):
  print "HeHo !"

print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys()
Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['set'] = monset
Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['addDocument'] = monsetattr
Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['__setattr__'] = monsetattr
print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys()
xsltproc = Processor()

xsltproc.appendStylesheet(DefaultFactory.fromUri("file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons_to_xhtml_list.xsl"))
html = xsltproc.run(DefaultFactory.fromUri("file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons.xml"))
print html
Example #37
0
def mongetattr(ins, attname):
    print "Aie!"
    return None


def monset(ins, d):
    print "On défini un truc sur le contexte"
    ancienset(ins, d)


def monsetattr(ins, attname, val):
    print "HeHo !"


print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys()
Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['set'] = monset
Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['addDocument'] = monsetattr
Ft.Xml.Xslt.XsltContext.XsltContext.__dict__['__setattr__'] = monsetattr
print Ft.Xml.Xslt.XsltContext.XsltContext.__dict__.keys()
xsltproc = Processor()

xsltproc.appendStylesheet(
    DefaultFactory.fromUri(
        "file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons_to_xhtml_list.xsl"
    ))
html = xsltproc.run(
    DefaultFactory.fromUri(
        "file:///home/t0rt00se/Travail/SILR3/pTrans/testset/persons.xml"))
print html
Example #38
0
    output, result = XMLTestRunner().run(suite, options.timestamp)

    ro = output
    if options.format is not None:
        try:
            from Ft.Lib import Uri
            from Ft.Xml.InputSource import DefaultFactory
            from Ft.Xml.Xslt.Processor import Processor
        except:
            print "Couldn't import modules to generate HTML."
            
        processor = Processor()

        if options.format == "html":
            xform = DefaultFactory.fromString(html_xform, "uri")
        elif options.format == "text":
            xform = DefaultFactory.fromString(text_xform, "uri")

        processor.appendStylesheet(xform)
        
        try:
            ro = processor.run(DefaultFactory.fromString(output, "uri"))
        except Exception, e:
            print "Failed to generate HTML. (%s)" % e
            ro = None
                
    if options.outputFile is not None and ro is not None:
        f = file(options.outputFile, 'w')
        f.write(ro)
        f.close()
    output, result = XMLTestRunner().run(suite, options.timestamp)

    ro = output
    if options.format is not None:
        try:
            from Ft.Lib import Uri
            from Ft.Xml.InputSource import DefaultFactory
            from Ft.Xml.Xslt.Processor import Processor
        except:
            print "Couldn't import modules to generate HTML."

        processor = Processor()

        if options.format == "html":
            xform = DefaultFactory.fromString(html_xform, "uri")
        elif options.format == "text":
            xform = DefaultFactory.fromString(text_xform, "uri")

        processor.appendStylesheet(xform)

        try:
            ro = processor.run(DefaultFactory.fromString(output, "uri"))
        except Exception, e:
            print "Failed to generate HTML. (%s)" % e
            ro = None

    if options.outputFile is not None and ro is not None:
        f = file(options.outputFile, 'w')
        f.write(ro)
        f.close()
Example #40
0
    processor.setDocumentReader(Ft.Xml.Domlette.NonvalidatingReader)
    processor.appendStylesheet(stylesheet)
    output = cStringIO.StringIO()
    processor.run(source, outputStream = output)
    return output.getvalue()

minx = miny = maxx = maxy = None
classes = {}

basename = sys.argv[1].rsplit('.',1)[0]
png = os.popen("pngtopnm %s.png 2>/dev/null" % basename)
png.readline()
size = map(int, png.readline().strip().split(' '))
png.read()

for line in xsltproc(InputFactory.fromStream(gzip.open(sys.argv[1]), sys.argv[1]),
                     InputFactory.fromString(stylesheet, '<string>')).strip().split("\n"):
    name,box = line.rsplit(' ',1)
    tlx, tly, brx, bry = (float(val)
                          for point in box.split(';')
                          for val in point.split(','))
    name = name[1:-1]
    if minx is None or tlx<minx : minx = tlx
    if maxx is None or tlx>maxx : maxx = tlx
    if minx is None or brx<minx : minx = brx
    if maxx is None or brx>maxx : maxx = brx
    if miny is None or tly<miny : miny = tly
    if maxy is None or tly>maxy : maxy = tly
    if miny is None or bry<miny : miny = bry
    if maxy is None or bry>maxy : maxy = bry 
    if name:
Example #41
0
def compare_builder(expected, builder):
    isrc = DefaultFactory.fromString(expected, "urn:test:expected")
    expected = NonvalParse(isrc)
    return not TreeCompare.NodeCompare(expected, builder.getDocument())