"""
$RCSfile: TestXPathMethod.py,v $
Unit tests for ZopeXMLMethods product

Author: Craeg Strong <cstrong@arielpartners.com>

Release: 1.0
"""

__cvstag__  = '$Name:  $'[6:-2]
__date__    = '$Date: 2005/09/06 02:08:59 $'[6:-2]
__version__ = '$Revision: 1.2 $'[10:-2]

import os, sys
if __name__ == '__main__':
    execfile(os.path.join(sys.path[0], 'framework.py'))

# Load fixture
from Testing import ZopeTestCase

from transaction import manager

# ZopeXMLMethods
from Products.ZopeXMLMethods import XPathMethod

ZopeTestCase.installProduct('ZopeXMLMethods')
ZopeTestCase.installProduct('PageTemplates')

from Testing.ZopeTestCase import folder_name, standard_permissions
host, port = ZopeTestCase.utils.startZServer(3)
base = 'http://%s:%d/%s' %(host, port, folder_name)

class XPathMethodTestCase(ZopeTestCase.ZopeTestCase):
    """
    Unit tests for ZopeXMLMethods Zope Product.  These tests use the
    ZopeTestCase enhanced testing product.
    """

    ################################################################
    # Fixture
    ################################################################

    def beforeSetUp(self):
        manager.begin()

    def afterSetUp(self):
        '''Add object to default fixture'''

        #
        # Some of our negative testcases can cause warning
        # strings to be printed out.  Suppress those,
        # because it makes it seem like there is something wrong
        # with the test when there is not.
        # CKS 9/10/2002
        #
        #import warnings
        #warnings.filterwarnings('ignore','',UserWarning)
        
        pass

    def beforeClose(self):
        # Commit the cleared app
        manager.commit()

    def afterClear(self):
        '''Clean up after myself'''
        pass
    
    ################################################################
    # Test Cases
    ################################################################

    def test_01(self):
        "Ensure that XPathMethod cannot be created with a blank ID"
        self.assertRaises(Exception, XPathMethod.addInstance,
                          self.folder,id='',
                          xpathExpression='document/a')

    def test_02(self):
        "Ensure that XPathMethod can be created with minimal correct params"

        xform = XPathMethod.addInstance(self.folder,id='aXPathMethod',
                                        xpathExpression='document/a')

        self.failUnless(xform, "XPathMethod successfully created should not be None")
        self.assertEquals(xform.id, 'aXPathMethod')

    def test_03(self):
        "Ensure that basic xpath works correctly"

        xmlFile      = open('testfiles/simple.xml', 'rb')
        self.folder.manage_addDTMLMethod('aSource', '', xmlFile)

        XPathMethod.addInstance(self.folder,id='aXPathMethod',
                                xpathExpression='document/b/text()')
        result = self.folder.aSource.aXPathMethod.evaluateString(self.app.REQUEST)
        self.assertEquals(result.strip(), "Hello, world")

    def test_04(self):
        "Ensure that XPathMethod reports invalid XPath"
        xmlFile      = open('testfiles/simple.xml', 'rb')
        self.folder.manage_addDTMLMethod('aSource', '', xmlFile)

        XPathMethod.addInstance(self.folder,id='aXPathMethod',
                                xpathExpression='\\bad$%xpath\\')
        self.assertRaises(Exception,
                          self.folder.aSource.aXPathMethod.evaluateString,
                          self.app.REQUEST)

    def test_05(self):
        "Ensure that evaluation can produce valid ZPT"
        xmlFile      = open('testfiles/templatetest.xml', 'rb')
        self.folder.manage_addFile('aSource', xmlFile)
        self.folder.who = "sneezy"

        XPathMethod.addInstance(self.folder,id='aXPathMethod',
                                xpathExpression = '/document/b/span',
                                content_type='text/html',
                                behave_like='Page Template')
        method = self.folder.aSource.aXPathMethod

        result = method(method, self.app.REQUEST)
        self.assertEquals(result.strip(), "<span>Hello, sneezy</span>")

    ################################################################
    # Test Runner Setup
    ################################################################

if __name__ == '__main__':
    from Products.ZopeXMLMethods.processors.ProcessorRegistry import ProcessorRegistry
    from Products.ZopeXMLMethods.processors.interfaces import IXPathProcessor
    
    # Specify which processor to use
    #ProcessorRegistry.CandidateProcessors = ( 'FourSuiteProcessor' )
        
    # report which processor we are using
    print "Using processor:", ProcessorRegistry.defaultName(IXPathProcessor)

    framework(descriptions=1, verbosity=2) # 0=quiet 1=default 2=verbose
else:
    # While framework.py provides its own test_suite() 
    # method the testrunner utility does not.
    import unittest
    def test_suite():
        suite = unittest.TestSuite()
        suite.addTest(unittest.makeSuite(XPathMethodTestCase))
        return suite
