#!/usr/bin/python

import unittest
import copy
import os
import re
import FragmentFilter
import xml.sax.saxutils
#from Ft.Lib.pDomlette import PyExpatReader
from xml.sax import make_parser, parseString, parse
from Ft.Xml import InputSource
from Ft.Xml.Domlette import NonvalidatingReader
from StringIO import StringIO
#from logilab.xmldiff.input import tree_from_stream
#from logilab.xmldiff.ezs import EzsCorrector
#from logilab.xmldiff.fmes import FmesCorrector
#from logilab.xmldiff.format import factions_print, xupdate_print
from xmlcomp import XmlComp

"""
The contents of this file are subject to the Mozilla Public License  Version 1.1 (the "License"); you may not use this file except in  compliance with the License. 
You may obtain a copy of the License at http://www.mozilla.org/MPL/ 
Software distributed under the License is distributed on an "AS IS"  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the  License for the specific language governing rights and limitations under  the License. 

The Original Code is available at http://downloads.xmlschemata.org/python/xvif/

The Initial Developer of the Original Code is Eric van der Vlist. Portions  created by Eric van der Vlist are Copyright (C) 2002. All Rights Reserved. 

Contributor(s): 
"""


class TestRegfragSuite(unittest.TestCase):

	"""This class runs a test suite of transformations on a
	regular fragmentations implementation"""
	

	def rulesParser(self, loc, valid=1):
		parser = make_parser()
		rules = FragmentFilter.RulesLoader()
		parser.setContentHandler(rules)
		parser.setFeature("http://xml.org/sax/features/namespaces", 1)
		factory = InputSource.DefaultFactory
		isrc=factory.fromUri(loc)
		exception = 0
		msg=""
		try:
			parser.parse(isrc.stream)
		except FragmentFilter.InvalidRuleException, msg:
			exception=1
		if valid:
			self.failUnless(exception==0,
				'the rules should be valid (%s)' % (msg))
		else:
			self.failUnless(exception==1,
				'the rules should be invalid')
		return rules

	def fragmentDocument(self, rules, fromLoc, valid=1, toLoc=""):
		parser = make_parser()
		fragFilter = FragmentFilter.FragmentFilter(rules)
		parser.setContentHandler(fragFilter)
		parser.setFeature("http://xml.org/sax/features/namespaces", 1)
		out = StringIO()
		fragFilter.setContentHandler(xml.sax.saxutils.XMLGenerator(out))
		factory = InputSource.DefaultFactory
		isrc=factory.fromUri(fromLoc)
		msg = ""
		try:
			parser.parse(isrc.stream)
			exception = 0
		except FragmentFilter.InvalidFragmentException, msg:
			exception = 1
		if valid:
			self.failUnless(exception == 0,
				'Unexpected exception :'+ msg)
			#expected = tree_from_stream(toLoc, 1)
			#got =  tree_from_stream(StringIO(out.getvalue()), 1)
			#dp = EzsCorrector()
			#dp = FmesCorrector(.59, .5)
			#actions = dp.process_trees(got, expected)
			#print actions
			#factions_print(actions)
			#if actions:
			#	factions_print(actions)
			#	xupdate_print(actions)
			#self.failUnless(not actions, "Unexpected result file %s: %s" % (toLoc, out.getvalue()))

			comp = XmlComp()
			#comp.removeCheck(XmlComp.NAMESPACE_DECLARATION)
			#comp.removeCheck(XmlComp.WHITESPACES)
			reader = NonvalidatingReader
			d1 = reader.parseUri(toLoc)
			d2 = reader.parseString(out.getvalue(), "dummy")
			res = comp.compare(d1, d2)
			self.failUnless(not res, "Unexpected result file %s: %s (%s)" % (toLoc, res, out.getvalue()))
		else:
			self.failUnless(exception == 1,
				"Shouldn't have been valid:\n" )

	def run1test(self):
		global suite
		print self._TestCase__testMethodName
		dir = "%s/%s/" % (suite, self._TestCase__testMethodName[4:])
		print dir
		files = os.listdir(dir)
		print files
		if 'c-trans.xml' in files:
			rules = self.rulesParser(dir + 'c-trans.xml')
			i = 1
			while 1:
				if "%d-i-from.xml" % i in files:
					self.fragmentDocument(rules, "%s%d-i-from.xml" % (dir, i), valid=0)
					print "invalid"
				elif "%d-v-from.xml" % i in files:
					self.fragmentDocument(rules, "%s%d-v-from.xml" % (dir, i), valid=1, toLoc="%s%d-to.xml" % (dir, i))
					print "valid"
				else:
					break
				i += 1
		elif 'i-trans.xml' in files:
			rules = self.rulesParser(dir + 'i-trans.xml', 0)
		return

if __name__ == "__main__":
	suite = "tests/regfrag"
	for rep in os.listdir(suite):
		if re.match("\d{3}", rep):
			print rep
			f =  lambda self: self.run1test()
			setattr(TestRegfragSuite, "test"+rep, f)
	unittest.main()


