TestInputTypes.py :  » Language-Interface » Pyana » Pyana-0.9.2 » Test » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Language Interface » Pyana 
Pyana » Pyana 0.9.2 » Test » TestInputTypes.py
import Pyana
import os
import unittest

class Reader:
    def __init__(self, buffer):
        self.buffer = buffer
        
    def read(self, readSize = None):
        if readSize is None:
            readSize = len(self.buffer)
        readBuffer = self.buffer[:readSize]
        self.buffer = self.buffer[readSize:]
        return readBuffer

class ReadException(Exception):
    pass

class RaisingReader:
    def read(self, readSize = None):
        raise ReadException

class BadTypeReader:
    def read(self, readSize = None):
        return 5
    
class InputSource:
    def __init__(self, string):
        self.string = string
        
    def makeStream(self):
        return Reader(self.string)

class MakeStreamException(Exception):
    pass

class RaisingInputSource:
    def makeStream(self):
        raise MakeStreamException

class BadTypeInputSource:
    def makeStream(self):
        return 5

class EntityResolver:
    def __init__(self):
        pass
        
    def resolveEntity(self, public, system):
        from StringIO import StringIO

        if system.endswith('.xml'):    
            assert system == 'http://foo.bar/baz.xml'
            return InputSource(r'''<message>Good!</message>''')
        else:
            assert system == 'http://foo.bar/baz.xsl'
            return InputSource(r'''<stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"/>''')

class CompleteInputSource(InputSource):
    def __init__(self, string, encoding, system, public):
        self.string = string
        self.system = system
        self.public = public
        self.encoding = encoding
        
    def makeStream(self):
        return Reader(self.string)

    def getEncoding(self): return self.encoding
    def getSystemId(self): return self.system
    def getPublicId(self): return self.system

class EncodingException(Exception):
    pass

class EncodingRaisingInputSource(CompleteInputSource):
    def __init__(self):
        CompleteInputSource.__init__(self, 'string', 'encoding', 'system', 'public')
    def getEncoding(self): raise EncodingException()
    
class BadEncodingInputSource(EncodingRaisingInputSource):
    def getEncoding(self): return 5  
    
inputTestXSL = r'''
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text"/>
    <xsl:template match="a"><xsl:value-of select="child::text()"/></xsl:template>
</xsl:stylesheet>
'''

inputTestXML = r'''
<a>Success!</a>
'''

complexInputSourceXSL = r'''
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text"/>
    <xsl:include href="baz.xsl"/>
    <xsl:template match="/">
        <xsl:apply-templates select="document('baz.xml', .)//message"/>
    </xsl:template>
</xsl:stylesheet>
'''

processingInstructionTestXML = r'''
<?xml-stylesheet type="text/xsl" href="testInput.xsl"?>
<a>Success!</a>
'''

class InputTypesTestCase(unittest.TestCase):
    def setUp(self):
        self.t = Pyana.Transformer()

        self.xmlPath = 'testInput.xml'
        self.xslPath = 'testInput.xsl'
            
    def checkStringInput(self):
        assert self.t.transform2String(
                inputTestXML,
                inputTestXSL
            ) == "Success!"

        parsedSource = self.t.parseSource(inputTestXML)
        stylesheet = self.t.compileStylesheet(inputTestXSL)
        self.t.transform2String(
                parsedSource,
                stylesheet
            )  == "Success!"
        
    def checkURIInput(self):
        assert os.path.exists(self.xmlPath) and \
               os.path.exists(self.xslPath), \
               'Files missing, URI test skipped'

        assert self.t.transform2String(
                    Pyana.URI(self.xmlPath),
                    Pyana.URI(self.xslPath)
                )  == "Success!"

        parsedSource = self.t.parseSource(Pyana.URI(self.xmlPath))
        stylesheet = self.t.compileStylesheet(Pyana.URI(self.xslPath))
        assert self.t.transform2String(
                parsedSource,
                stylesheet
            ) == "Success!"
        
        self.assertRaises(
                    Pyana.SAXError,
                    self.t.transform2String,
                    Pyana.URI(self.xmlPath + 'blah!'),
                    Pyana.URI(self.xslPath)
                )

        self.assertRaises(
                    Pyana.SAXError,
                    self.t.parseSource,
                    Pyana.URI(self.xmlPath + 'blah!')
                )
        
        self.assertRaises(
                    Pyana.SAXError,
                    self.t.transform2String,
                    Pyana.URI(self.xmlPath),
                    Pyana.URI(self.xslPath + 'blah!')
                )

        self.assertRaises(
                    Pyana.SAXError,
                    self.t.compileStylesheet,
                    Pyana.URI(self.xslPath + 'blah!')
                )
        
    def checkReadInput(self):
        assert Pyana.transform2String(
                Reader(inputTestXML),
                Reader(inputTestXSL)
            ) == "Success!"

        parsedSource = self.t.parseSource(Reader(inputTestXML))
        stylesheet = self.t.compileStylesheet(Reader(inputTestXSL))
        assert self.t.transform2String(
                parsedSource,
                stylesheet
            ) == "Success!"
        
        # Test "RaisingReader"
        self.assertRaises(
                ReadException,
                self.t.transform2String,
                RaisingReader(),
                Reader(inputTestXSL)
            )

        self.assertRaises(
                ReadException,
                self.t.parseSource,
                RaisingReader()
            )
        
        self.assertRaises(
                ReadException,
                self.t.transform2String,
                Reader(inputTestXML),
                RaisingReader()
            )

        self.assertRaises(
                ReadException,
                self.t.compileStylesheet,
                RaisingReader()
            )
        
        # Test "BadTypeReader"
        self.assertRaises(
                TypeError,
                self.t.transform2String,
                BadTypeReader(),
                Reader(inputTestXSL)
            )

        self.assertRaises(
                TypeError,
                self.t.parseSource,
                BadTypeReader()
            )
        
        self.assertRaises(
                TypeError,
                self.t.transform2String,
                Reader(inputTestXML),
                BadTypeReader()
            )

        self.assertRaises(
                TypeError,
                self.t.compileStylesheet,
                BadTypeReader()
            )

    def checkInputSourceInput(self):
        inputTestXML = ur'''<?xml version="1.0" encoding="UTF-16"?>
            <a>Success!</a>
        '''.encode('utf-16')
        
        assert Pyana.transform2String(
                InputSource(inputTestXML),
                InputSource(inputTestXSL)
            ) == "Success!"

        # Test "RaisingInputSource"
        self.assertRaises(
                MakeStreamException,
                self.t.transform2String,
                RaisingInputSource(),
                InputSource(inputTestXSL)
            )
        
        self.assertRaises(
                MakeStreamException,
                self.t.transform2String,
                InputSource(inputTestXML),
                RaisingInputSource()
            )

        # Test "BadTypeInputSource"
        self.assertRaises(
                AttributeError,
                self.t.transform2String,
                BadTypeInputSource(),
                InputSource(inputTestXSL)
            )
        
        self.assertRaises(
                AttributeError,
                self.t.transform2String,
                InputSource(inputTestXML),
                BadTypeInputSource()
            )

    def checkCompleteInputSource(self):
        import codecs
        try:
            # try this encoding because it is very unlikely that it
            # could be successfully guessed
            encoding = 'IBM1140'
            codecs.lookup(encoding)
        except LookupError:
            encoding = 'UTF-8'
            
        xmlInput = CompleteInputSource(
            unicode(inputTestXML).encode(encoding),
            encoding,
            'http://foo.bar/xml',
            '')

        xslInput = CompleteInputSource(
            unicode(complexInputSourceXSL).encode(encoding),
            encoding,
            'http://foo.bar/xsl',
            '')

        t = Pyana.Transformer()
        t.setEntityResolver(EntityResolver())
        assert t.transform2String(xmlInput, xslInput) == 'Good!'
    
        # Test incorrect InputSources 
        self.assertRaises(
                EncodingException,
                self.t.transform2String,
                EncodingRaisingInputSource(),
                InputSource(inputTestXSL)
            )

        self.assertRaises(
                TypeError,
                self.t.transform2String,
                BadEncodingInputSource(),
                InputSource(inputTestXSL)
            )
        
    def checkProcessingInstruction(self):
        assert os.path.exists(self.xmlPath) and \
               os.path.exists(self.xslPath), \
               'Files missing, processing instruction test skipped'
       
        assert self.t.transform2String(
                    processingInstructionTestXML
                ) == 'Success!'

        parsedSource = self.t.parseSource(processingInstructionTestXML)
        assert self.t.transform2String(
                    parsedSource
                ) == 'Success!'
        
        assert self.t.transform2String(
                    processingInstructionTestXML,
                    None
                ) == 'Success!'

        self.assertRaises(
                    Pyana.ProcessorError,
                    self.t.transform2String,
                    inputTestXML, # No processing instruction  
                )

    def checkBadInputType(self):
        self.assertRaises(
                    TypeError,
                    self.t.transform2String,
                    5,
                    None
                )

        self.assertRaises(
                    TypeError,
                    self.t.transform2String,
                    processingInstructionTestXML,
                    5
                )
        
        self.assertRaises(
                    TypeError,
                    self.t.parseSource,
                    5
                )

        self.assertRaises(
                    TypeError,
                    self.t.compileStylesheet,
                    5
                )

    def checkParseSourceSchema(self):
        class ErrorHandler:
            def __init__(self, expected):
                self.expected = expected
                self.expected.reverse()
                       
            def common(self, name, e):
                expected_type, expected_pattern = self.expected.pop()
                assert expected_type == name
                assert str(e).find(expected_pattern) != -1
                
            def warning(self, e):
                self.common('warning', e)        
            def error(self, e):
                self.common('error', e)
            def fatalError(self, e):
                self.common('fatalError', e)
            def resetErrors(self):
                pass

            def __del__(self):
                assert len(self.expected) == 0
                    
                    
        xml = '''<int xmlns="http://pyana.sourceforge.net/">5</int>'''
        badxml = '''<int xmlns="http://pyana.sourceforge.net/">Foo</int>'''
        
        t = Pyana.Transformer()        
        t.useValidation = 1

        t.setErrorHandler(ErrorHandler([]))
        t.parseSource(xml, externalSchema = "http://pyana.sourceforge.net/ testSchema.xsd")
        
        t.setErrorHandler(ErrorHandler([('error', 'Datatype error')]))
        t.parseSource(badxml, externalSchema = "http://pyana.sourceforge.net/ testSchema.xsd")

        t.setErrorHandler(ErrorHandler([('error', 'different target namespace')]))
        t.parseSource(xml, externalSchema = "foo testSchema.xsd")

        t.setErrorHandler(ErrorHandler([('error', 'different target namespace'),
                                        ('error', 'Datatype error')]))
        t.parseSource(badxml, externalSchema = "foo testSchema.xsd")
        
        t.setErrorHandler(ErrorHandler([('warning', 'could not be opened')]))
        t.parseSource(xml, externalSchema = "http://pyana.sourceforge.net/ foo.xsd")

        t.setErrorHandler(ErrorHandler([]))
        t.parseSource(xml, externalSchema = "")

        t.setErrorHandler(None)        
        self.assertRaises(Pyana.SAXParseError, t.parseSource, xml, externalSchema = "Hello")      
        self.assertRaises(TypeError, t.parseSource, xml, externalSchema = {})
        
        
    def checkInputCombinations(self):
        import copy
        
        assert os.path.exists(self.xmlPath) and \
               os.path.exists(self.xslPath), \
               'Files missing, input combinations test skipped'

        sources = [
                        inputTestXML,
                        Pyana.URI(self.xmlPath),
                        Reader(inputTestXML),
                        InputSource(inputTestXML),
                        self.t.parseSource(inputTestXML)
                ]

        styles = [
                        inputTestXSL,
                        Pyana.URI(self.xslPath),
                        Reader(inputTestXSL),
                        InputSource(inputTestXSL),
                        self.t.compileStylesheet(inputTestXSL)
                ]
        
        for source in sources:
            for style in styles:
                # Can't recycle reader objects
                if isinstance(source, Reader):
                    source = Reader(inputTestXML)
                if isinstance(style, Reader):
                    style = Reader(inputTestXSL)
                    
                assert self.t.transform2String(source, style) == 'Success!'
        
def getTestSuites(type):
    return unittest.TestSuite([
            unittest.makeSuite(InputTypesTestCase, type)
                ])
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.