##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# 
# 1. Redistributions in source code must retain the above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################

# DB stuff copied from testBTrees.py

import unittest
import ZODB # for Persistent
import glob
import os
import sys

from Products.ParsedXML import ParsedXML
from Products.ParsedXML.StrIO import StringIO

import unittest

class PersistenceTestCase(unittest.TestCase):

    implementation = ParsedXML.theDOMImplementation

    def openDB(self):
        from ZODB.FileStorage import FileStorage
        from ZODB.DB import DB
        storage = FileStorage(self.dbName)
        db = DB(storage)
        self.db = db.open().root()

    def closeDB(self):
        get_transaction().commit()
        self.document = None
        self.db._p_jar._db.close()
        self.db = None

    def getAppDocument(self):
        "put the document that startup put in the db in self.document"
        self.document = self.db['doc']

    def cycleDB(self):
        """close and open the db and replace self.document.
        Any nonpersistent changes to self.document should be lost."""
        self.closeDB()
        self.openDB()
        self.getAppDocument()

    def delDB(self):
        map(os.unlink, glob.glob("fs_tmp__*"))

    def setUp(self):
        """open db, create a document in the db, set self.document to it"""

        self.dbName = 'fs_tmp__%s' % os.getpid()
        self.openDB()
        self.db['doc'] = ParsedXML.ParsedXML('foo')
        get_transaction().commit()
        self.document = self.db['doc']

    def tearDown(self):
        self.closeDB()
        self.delDB()

    def checkIDPersistence(self):
        "assert that changing the ID persists over transactions"
        self.document._setId('newId')
        self.cycleDB()
        assert self.document.getId() == 'newId'

    def checkParsedXMLDOMPersistence(self):
        "assert that a Parsed XML DOM edit persists over transactions"
        elt = self.document.createElement('elt')
        self.document.firstChild.appendChild(elt)
        self.cycleDB()
        childLen = self.document.firstChild.childNodes.length
        assert childLen == 1, "DOM edit didn't persist"

    def checkDOMPersistence(self):
        "assert that a DOM edit persists over transactions"

        doc = ParsedXML.createDOMDocument()

        import OFS.SimpleItem
        si = self.db['si'] = OFS.SimpleItem.SimpleItem()
        si.doc = doc
        elt = si.doc.createElement('elt')
        si.doc.firstChild.appendChild(elt)

        self.cycleDB()
        # not using the normal db document, must grab ourselves
        si = self.db['si']
                
        childLen = si.doc.firstChild.childNodes.length
        assert childLen == 1, "DOM edit didn't persist"
        
    def checkParsePersistence(self):
        "assert that a parse persists over transactions"
        testDir = os.path.join(
            sys.modules['Products.ParsedXML'].__path__[0],
            'tests')
        filename = os.path.join(testDir, 'xml', '4ohn4ktj.xml')
        file = open(filename)
        self.document.parseXML(filename)
        file.close()
        childLen = self.document.firstChild.childNodes.length
        self.cycleDB()
        childLen1 = self.document.firstChild.childNodes.length
        assert childLen == childLen1, "parse didn't persist"

    def checkSubnodeParsePersistence(self):
        "assert that a subnode parse persists over transactions"        
        docString = '<?xml version="1.0" ?><foo></foo>'
        subNodeString = '<foo>bar</foo>'
        self.document.documentElement.parseXML(StringIO(subNodeString))
        self.cycleDB()
        childLen = self.document.documentElement.childNodes.length
        assert childLen == 1, "parse on subnode didn't persist"

    # right now it's too annoying to get parsing to work at a transient
    # document proxy, but it could be less aggravating if we had a better
    # way to get at the persistent document.
    #def checkTransientDocumentParsePersistence(self):
    #    """assert that a parse of a transient proxy of the document
    #    persists over transactions"""
    #    docStringBefore = '<?xml version="1.0" ?><foo></foo>'
    #    docStringAfter = '<?xml version="1.0" ?><foo>bar</foo>'
    #    self.document.documentElement.ownerDocument.parseXML(
    #        StringIO(docStringAfter))
    #    self.cycleDB()
    #    childLen = self.document.documentElement.childNodes.length
    #    assert childLen == 1, "parse on subnode didn't persist"

#      def checkTheseDamnTests(self):
#          "assert that I understand how these tests should work"
#          docString = '<?xml version="1.0" ?><foo>fff</foo>'        
#          self.document.parseXML(StringIO(docString))
#          get_transaction().commit()
#          # db and doc length now 1
#          self.document.documentElement.removeChild(
#              self.document.documentElement.firstChild)
#          # doc length 0, db length 1
        
#          # do what closeDB and openDB do, but *don't commit*
#          # so the above edit shouldn't stay.

#          #closeDB but don't commit
#          #get_transaction().commit()
#          self.document = None
#          self.db._p_jar._db.close()
#          self.db = None

#          #openDB
#          from ZODB.FileStorage import FileStorage
#          from ZODB.DB import DB
#          storage = FileStorage(self.dbName)
#          db = DB(storage)
#          self.db = db.open().root()

#          self.getAppDocument()
#          get_transaction().commit()
#          assert self.document.documentElement.childNodes.length == 1, (
#              "these tests are faulty")


def test_suite():
    """Return a test suite for the Zope testing framework."""

    return unittest.makeSuite(PersistenceTestCase, 'check')

def main():
    unittest.TextTestRunner().run(test_suite())

if __name__ == '__main__':
    main()
    
