Пример #1
0
def Test(tester):
    base = Uri.OsPathToUri(__file__, attemptAbsolute=True)

    tester.startGroup('Simple XLinks')
    from Ft.Xml.XLink.Processor import Processor

    tester.startTest('Process w/xlink:show="embed"')
    uri1 = Uri.Absolutize('addr_book1.xml', base)
    isrc = InputSource.DefaultFactory.fromUri(uri1)
    p = Processor()
    doc = p.run(isrc)
    stream = cStringIO.StringIO()
    Print(doc, stream)
    actual = stream.getvalue()
    tester.compare(EXPECTED_1, actual, func=TreeCompare.TreeCompare)
    tester.testDone()

    tester.startTest('Process w/xlink:show="replace"')
    uri3 = Uri.Absolutize('addr_book3.xml', base)
    isrc = InputSource.DefaultFactory.fromUri(uri3)
    p = Processor()
    doc = p.run(isrc)
    stream = cStringIO.StringIO()
    Print(doc, stream)
    actual = stream.getvalue()
    tester.compare(EXPECTED_2, actual, func=TreeCompare.TreeCompare)
    tester.testDone()

    return tester.groupDone()
Пример #2
0
    def test_transform(self):
        SIZE = 10

        import sys
        from amara.xslt import transform

        #Create the matrix to be transposed
        from Ft.Xml.Domlette import implementation
        doc = implementation.createDocument(None, 'table', None)
        counter = 1
        for row in range(SIZE):
            row_elem = doc.createElementNS(None, 'row')
            doc.documentElement.appendChild(row_elem)
            for col in range(SIZE):
                col_elem = doc.createElementNS(None, 'column')
                row_elem.appendChild(col_elem)
                content = doc.createTextNode(str(counter))
                col_elem.appendChild(content)
                counter = counter + 1

        stream = cStringIO.StringIO()
        from Ft.Xml.Domlette import Print
        Print(doc, stream)

        self.source = stringsource(stream.getvalue())
        result = transform(self.source, self.transform, output=io)
        self.assert_(treecompare.html_compare(self.expected, io.getvalue()))
        return
Пример #3
0
 def runFirst(self):
     start = time.time()
     self.target = self.xsltproc.runNode(self.source)
     Print(self.target)
     end = time.time()
     self.can_run_inc = True
     self.oldtime = (end - start) * 10000
     self.ready_for_inc = True
Пример #4
0
 def commitTransaction(self, txnService):
     #write out the dom
     output = file(self._location, 'w+')
     from Ft.Xml.Domlette import Print, PrettyPrint
     if self.prettyPrint:
         PrettyPrint(doc, output)
     else:
         Print(doc, output)
     output.close()
     self._defaultModel = None
Пример #5
0
def Test(tester):
    tester.startGroup('Idan Elfassy finds well-formedness bug in printer')
    doc = NonvalidatingReader.parseString(SRC1, __name__)
    tester.startTest('Ft.Xml.Domlette.Print')
    stream = cStringIO.StringIO()
    Print(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED1_PRINTED, result)
    tester.testDone()
    tester.groupDone()
    return
Пример #6
0
Файл: test.py Проект: zggl/lxir
 def _get_result(self):
     doc = NonvalidatingReader.parseString(self.output,
                                           self.URI_P % self.name)
     ctxt = Context(doc, processorNss=NSS)
     nodes = Evaluate("//mml:math", context=ctxt)
     assert len(nodes) == 1
     node = nodes[0]
     node.removeAttributeNS(None, u'begin-id')
     node.removeAttributeNS(None, u'end-id')
     o = StringIO.StringIO()
     Print(node, stream=o)
     return o.getvalue()
Пример #7
0
 def syncConfig(self):
     """
     synchronizes both original and dynamic configuration to vermont instance
     """
     logger().debug("VermontInstance.syncConfig()")
     if self.__cfgModified:
         self._transmitConfig()
         self.__cfgModified = False
     if self.dynCfgModified:
         if self.__parseXml:
             textio = StringIO()
             Print(self.dynCfgXml, stream=textio)
             self.__dynCfgText = textio.getvalue()
         self._transmitDynConfig()
         self.__dynCfgModified = False
Пример #8
0
    def export_to_xml(self, file=None):
        if self.export_xml is None:
            self.export_xml = os.path.join(".", "print.xml")
        if file is None:
            file = asksaveasfilename(
                title="Export to XML as...",
                filetypes=[("XML files", "*.xml"), ("All files", "*")],
                initialfile=os.path.split(self.export_xml)[1],
                initialdir=os.path.split(self.export_xml)[0])

        if file == "" or file is ():
            return

        doc = implementation.createRootNode('file:///article.xml')

        self.app.ann_frame.build_xml(doc)

        outFile = open(file, 'w')
        Print(doc, stream=outFile)
        outFile.close()
Пример #9
0
def Test(tester):
    #Create the matrix to be transposed
    doc = implementation.createDocument(None, 'table', None)
    counter = 1
    for row in range(SIZE):
        row_elem = doc.createElementNS(None, 'row')
        doc.documentElement.appendChild(row_elem)
        for col in range(SIZE):
            col_elem = doc.createElementNS(None, 'column')
            row_elem.appendChild(col_elem)
            content = doc.createTextNode(str(counter))
            col_elem.appendChild(content)
            counter = counter + 1

    stream = cStringIO.StringIO()
    Print(doc, stream)

    source = test_harness.FileInfo(string=stream.getvalue())
    sheet = test_harness.FileInfo(string=sheet_1)
    test_harness.XsltTest(tester, source, [sheet], expected_1)
    return
Пример #10
0
def Test(tester):

    tester.startTest("Evaluate on a HTML Document")

    if HtmlLib is None:
        tester.warning("Requires PyXML to be installed")
        tester.testDone()
        return

    xml_dom = HtmlLib.FromHtml(html)

    p = Ft.Xml.XPath.parser.new()
    exp = p.parse("/HTML/HEAD")

    c=Context.Context(xml_dom,0,0)
    result=exp.evaluate(c)

    
    st = cStringIO.StringIO()
    Print(result[0],st)
    tester.compare(expected_1,st.getvalue())

    tester.testDone()
def node_to_string(node):
       buf = cStringIO.StringIO();
       Print(node, stream=buf, encoding='utf-8');
       return buf.getvalue();
Пример #12
0
        doc = reader.parse(source_isrc)
        CloseStream(source_isrc, quiet=True)

        if rng_isrc is not None:
            validator = RelaxNgValidator(rng_isrc)
            CloseStream(rng_isrc, quiet=True)
            result = validator.validateNode(doc)
            if not result.nullable():
                raise RngInvalid(result)

        if not noserialize:
            from Ft.Xml.Domlette import Print, PrettyPrint
            if pretty:
                PrettyPrint(doc, out_file, encoding, as_html)
            else:
                Print(doc, out_file, encoding, as_html)

    except Exception, e:
        import traceback
        traceback.print_exc(1000, sys.stderr)
        raise

    try:
        if out_file.isatty():
            out_file.flush()
            sys.stderr.write('\n')
        else:
            out_file.close()
    except (IOError, ValueError):
        pass
Пример #13
0
def serialize_doc(node):
    buf = StringIO()
    Print(node, buf)
    return buf.getvalue()
def test_writer(tester, domMod):
    tester.startGroup('Domlette serialization')

    tester.startTest('minimal document with DOCTYPE')
    doc = domMod.implementation.createDocument(EMPTY_NAMESPACE, u'foo', None)
    doc.publicId = u'myPub'
    doc.systemId = u'mySys'
    buf = cStringIO.StringIO()
    Print(doc, buf)
    result = buf.getvalue()
    tester.compare(doctype_expected_1, result)
    tester.testDone()

    tester.startGroup('namespace-free XHTML')
    tester.startTest('create document')
    doc = domMod.implementation.createDocument(EMPTY_NAMESPACE, None, None)
    html = doc.createElementNS(EMPTY_NAMESPACE, u'html')
    head = doc.createElementNS(EMPTY_NAMESPACE, u'head')
    title = doc.createElementNS(EMPTY_NAMESPACE, u'title')
    titletext = doc.createTextNode(u'test')
    body = doc.createElementNS(EMPTY_NAMESPACE, u'body')
    h1 = doc.createElementNS(EMPTY_NAMESPACE, u'h1')
    h1text = doc.createTextNode(u'xhtml test')
    hr = doc.createElementNS(EMPTY_NAMESPACE, u'hr')
    hr.setAttributeNS(EMPTY_NAMESPACE, u'noshade', u'noshade')
    pre = doc.createElementNS(EMPTY_NAMESPACE, u'pre')
    pretext = doc.createTextNode(JABBERWOCKY)
    pre.appendChild(pretext)
    h1.appendChild(h1text)
    body.appendChild(h1)
    body.appendChild(hr)
    body.appendChild(pre)
    title.appendChild(titletext)
    head.appendChild(title)
    html.appendChild(head)
    html.appendChild(body)
    doc.appendChild(html)
    tester.testDone()

    tester.startTest('as XML with Print')
    buf = cStringIO.StringIO()
    Print(doc, buf)
    result = buf.getvalue()
    tester.compare(xhtml_expected_1, result)
    tester.testDone()

    tester.startTest('as HTML with Print')
    buf = cStringIO.StringIO()
    Print(doc, buf, asHtml=1)
    result = buf.getvalue()
    tester.compare(xhtml_expected_2, result)
    tester.testDone()

    tester.startTest('as XML with PrettyPrint')
    buf = cStringIO.StringIO()
    PrettyPrint(doc, buf)
    result = buf.getvalue()
    tester.compare(xhtml_expected_3, result)
    tester.testDone()

    tester.startTest('as HTML with PrettyPrint')
    buf = cStringIO.StringIO()
    PrettyPrint(doc, buf, asHtml=1)
    result = buf.getvalue()
    tester.compare(xhtml_expected_4, result)
    tester.testDone()

    tester.groupDone()

    tester.groupDone()
    return
Пример #15
0
def insert_math_images(file):
    file = os.path.abspath(file)
    doc = NonvalidatingReader.parseUri(file)
    ctxt = Context(doc, processorNss=NSS)

    # Check that verbatim math is used
    for node in Evaluate("//xhtml:span[@class='verbatimmath']/@lxir:value",
                         context=ctxt):
        verbatimmath = node.value
    assert verbatimmath == u'true', "Need verbatim math mode for math conversion"

    # Check that the document class is known
    latexClass = None
    symbols = []
    for node in Evaluate(
            "//xhtml:span[@class='ClassOrPackageUsed']/@lxir:name",
            context=ctxt):
        if latexClasses.has_key(node.value):
            latexClass = latexClasses[node.value]
        elif node.value in symbolPackages:
            symbols.append(node.value[:-4])
    assert latexClass, "Unknown document class used"

    # Get All macro text
    macros = []
    for node in Evaluate("//xhtml:span[@class='macro']//text()", context=ctxt):
        macros.append(node.nodeValue)

    gen = ImageGenerator(file, latexClass, macros, symbols)

    # Convert All math images
    for node in Evaluate("//xhtml:span[@class='formule']", context=ctxt):
        c = Context(node, processorNss=NSS)
        formula = ""
        for t in Evaluate("xhtml:span[@class='text']/text()", context=c):
            formula += t.nodeValue
        formula = formula.strip()
        if not len(formula):
            print "empty formula found in document"
            image, mathml, label = None, None, None
        else:
            if formula[0] != "$":
                p = node.parentNode
                env = p.getAttributeNS(None, 'class')
                assert env, "No env found for equation"
                if env[-5:] == "-star":
                    env = env[:-5] + "*"
                formula = "\\begin{" + env + "}\n" + formula + "\n\\end{" + env + "}"
            image, mathml, label = gen.makeImage(formula)
        # remove the empty text node(s)
        for t in Evaluate("xhtml:span[@class='text']", context=c):
            t.parentNode.removeChild(t)

        if image:
            img = node.ownerDocument.createElementNS(XHTML_NAMESPACE, "img")
            img.setAttributeNS(XHTML_NAMESPACE, "src", image)
            img.setAttributeNS(XHTML_NAMESPACE, "alt", formula)
            node.appendChild(img)

        if mathml:
            if mathml.tagName != 'math':
                # here, we have the case : a$_b$
                # mathml is: <span class='msub'><span class='mi'/><span>b</span></span>
                # original xml is : ... <span>a</span><span class="formula"> ...</span>
                # and node is the formula
                # p is <span>a</span>
                p = get_prev_span_node(node)
                newNode = node.parentNode.insertBefore(mathml.cloneNode(True),
                                                       node)
                newNode.firstChild.appendChild(p)
                node.parentNode.removeChild(node)
                print "Formula '%s' replaced by simple form (%s)." % (
                    formula, newNode.tagName + '.' +
                    newNode.getAttributeNS(None, u'class'))
            else:
                node.appendChild(node.ownerDocument.importNode(mathml, True))

        if label:
            node.appendChild(node.ownerDocument.importNode(label, True))
    base, ext = os.path.splitext(file)
    output = base + "_images" + ext
    o = open(output, "w")
    Print(doc, stream=o)
    o.close()
Пример #16
0
def Test(tester):
    tester.startGroup('Uche finds nested default namespace munging')
    doc = implementation.createDocument(None, None, None)
    elem1 = doc.createElementNS("http://example.com/1", "x:foo")
    doc.appendChild(elem1)
    elem2 = doc.createElementNS(None, "bar")
    elem1.appendChild(elem2)
    tester.startTest('Outer with prefix.  Print')
    stream = cStringIO.StringIO()
    Print(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED1_PRINTED, result)
    tester.testDone()
    tester.startTest('Outer with prefix.  PrettyPrint')
    stream = cStringIO.StringIO()
    PrettyPrint(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED1_PRETTY, result)
    tester.testDone()

    doc = implementation.createDocument(None, None, None)
    elem1 = doc.createElementNS("http://example.com/1", "foo")
    doc.appendChild(elem1)
    elem2 = doc.createElementNS(None, "bar")
    elem1.appendChild(elem2)
    tester.startTest('Outer without prefix.  Print')
    stream = cStringIO.StringIO()
    Print(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED2_PRINTED, result)
    tester.testDone()
    tester.startTest('Outer without prefix.  PrettyPrint')
    stream = cStringIO.StringIO()
    PrettyPrint(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED2_PRETTY, result)
    tester.testDone()

    doc = implementation.createDocument(None, None, None)
    elem1 = doc.createElementNS(None, "foo")
    doc.appendChild(elem1)
    elem2 = doc.createElementNS("http://example.com/1", "bar")
    elem1.appendChild(elem2)
    tester.startTest('outer no prefix or ns, inner ns no prefix.  Print')
    stream = cStringIO.StringIO()
    Print(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED3_PRINTED, result)
    tester.testDone()
    tester.startTest('outer no prefix or ns, inner ns no prefix.  PrettyPrint')
    stream = cStringIO.StringIO()
    PrettyPrint(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED3_PRETTY, result)
    tester.testDone()

    doc = implementation.createDocument(None, None, None)
    elem1 = doc.createElementNS(None, "foo")
    doc.appendChild(elem1)
    elem2 = doc.createElementNS("http://example.com/1", "bar")
    elem1.appendChild(elem2)
    elem3 = doc.createElementNS(None, "baz")
    elem2.appendChild(elem3)
    tester.startTest(
        'outer no prefix or ns, then ns no prefix then no prefix no ns.  Print'
    )
    stream = cStringIO.StringIO()
    Print(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED4_PRINTED, result)
    tester.testDone()
    tester.startTest(
        'outer no prefix or ns, then ns no prefix then no prefix no ns.  PrettyPrint'
    )
    stream = cStringIO.StringIO()
    PrettyPrint(doc, stream=stream)
    result = stream.getvalue()
    tester.compare(EXPECTED4_PRETTY, result)
    tester.testDone()
    tester.groupDone()
    return
Пример #17
0
 def commit(self):  #{
     print >> sys.stderr, 'Writing out DOM to ' + self.file
     f = open(self.file, 'w')
     Print(self.doc, stream=f)
     f.close()
     print >> sys.stderr, 'Written.'
Пример #18
0
def Test(tester):
    tester.startGroup("Fragment parse")

    tester.startTest("Plain parse")
    isrc = CreateInputSource(SOURCE1)
    doc = ParseFragment(isrc)
    stream = cStringIO.StringIO()
    Print(doc, stream)
    tester.compare(EXPECTED1, stream.getvalue())
    #Minimal node testing
    tester.compare(len(doc.childNodes), 1)
    tester.compare(doc.childNodes[0].nodeType, Node.ELEMENT_NODE)
    tester.compare(doc.childNodes[0].nodeName, u'p')
    tester.compare(doc.childNodes[0].namespaceURI, None)
    tester.compare(doc.childNodes[0].prefix, None,)
    tester.testDone()

    tester.startTest("Parse with overridden default namespace")
    nss = {u'xml': u'http://www.w3.org/XML/1998/namespace',
           None: u'http://www.w3.org/1999/xhtml'}
    isrc = CreateInputSource(SOURCE1)
    doc = ParseFragment(isrc, nss)
    stream = cStringIO.StringIO()
    Print(doc, stream)
    tester.compare(EXPECTED2, stream.getvalue())
    #doc = ParseFragment(TEST_STRING)
    #Minimal node testing
    tester.compare(len(doc.childNodes), 1)
    tester.compare(doc.childNodes[0].nodeType, Node.ELEMENT_NODE)
    tester.compare(doc.childNodes[0].nodeName, u'p')
    tester.compare(doc.childNodes[0].namespaceURI, u'http://www.w3.org/1999/xhtml')
    tester.compare(doc.childNodes[0].prefix, None,)
    tester.testDone()

    tester.startTest("Parse with overridden default namespace and re-overridden child")
    nss = {u'xml': u'http://www.w3.org/XML/1998/namespace',
           None: u'http://www.w3.org/1999/xhtml'}
    isrc = CreateInputSource(SOURCE2)
    doc = ParseFragment(isrc, nss)
    stream = cStringIO.StringIO()
    Print(doc, stream)
    tester.compare(EXPECTED3, stream.getvalue())
    #Minimal node testing
    tester.compare(len(doc.childNodes), 1)
    tester.compare(doc.childNodes[0].nodeType, Node.ELEMENT_NODE)
    tester.compare(doc.childNodes[0].nodeName, u'p')
    tester.compare(doc.childNodes[0].namespaceURI, u'http://www.w3.org/1999/xhtml')
    tester.compare(doc.childNodes[0].prefix, None,)
    tester.testDone()

    tester.startTest("Parse with overridden non-default namespace")
    nss = {u'xml': u'http://www.w3.org/XML/1998/namespace',
           u'h': u'http://www.w3.org/1999/xhtml'}
    isrc = CreateInputSource(SOURCE3)
    doc = ParseFragment(isrc, nss)
    stream = cStringIO.StringIO()
    Print(doc, stream)
    tester.compare(EXPECTED4, stream.getvalue())
    #doc = ParseFragment(TEST_STRING)
    #Minimal node testing
    tester.compare(len(doc.childNodes), 1)
    tester.compare(doc.childNodes[0].nodeType, Node.ELEMENT_NODE)
    tester.compare(doc.childNodes[0].nodeName, u'h:p')
    tester.compare(doc.childNodes[0].namespaceURI, u'http://www.w3.org/1999/xhtml')
    tester.compare(doc.childNodes[0].prefix, u'h')
    tester.testDone()

    tester.groupDone()
    return
Пример #19
0
                del context.objects[target]
            except KeyError, e:
                pass

            # now re-retrieve from confStore
            rec = confStore.fetch_record(session, target)            
            dom = rec.get_dom(session)
            config = dom.childNodes[0]
            config.setAttributeNS(None, 'configStore', cfgStr)
            context.subConfigs[target] = config
            
        try:
            xml = config.toxml()
        except AttributeError, e:
            stream = StringIO()
            Print(config, stream)
            stream.seek(0)
            xml = stream.read()

        self.send_xml(xml, req)

    def handle_listObjects(self, req):
        # List existing objects in context

        storeHash = {}
        collHash = {}
        processHash = {}

        # get start obj from request
        store = FieldStorage(req)
        try: