
from Ft.Server.Server import FtServerServerException,Error
from Ft.Server.Common import DocumentReference, ValidationInfo, CreationParams

import test_helper

def _init(tester):
    tester.startTest("Clean and Init")
    repo = test_helper.GetRepo(tester)
    if repo.hasResource('/test'):
        repo.deleteResource('/test')

    test = repo.createContainer('/test',1)

    test.createDocument('schema1',SCHEMA1)

    dr = DocumentReference.InternalDocumentReference('/test/schema1')
    vi = ValidationInfo.SchematronValidationInfo(dr)
    cp = CreationParams.CreationParams(vInfo = vi)
    test.createXPathDocumentDefinition('xml-schema',{},[],cp)
    repo.txCommit()
    tester.testDone()


def test_creation(tester):

    tester.startTest("Create Valid XML Document")
    repo = test_helper.GetRepo(tester)
    test = repo.fetchResource('/test')
    doc = test.createDocument('doc1',DOC1,docDef='xml-schema')
    repo.txCommit()
    tester.testDone()


    tester.startTest("Create Invalid XML Document")
    repo = test_helper.GetRepo(tester)
    test = repo.fetchResource('/test')
    tester.testException(test.createDocument,('doc2',DOC2,'xml-schema'),FtServerServerException,{'code':Error.VALIDATION_ERROR})
    repo.txRollback()
    tester.testDone()


def test_modification(tester):

    tester.startTest("Modify Valid XML Document")
    repo = test_helper.GetRepo(tester)
    test = repo.fetchResource('/test')
    doc = test.fetchResource('doc1')
    doc.setContent(DOC1)
    repo.txCommit()
    tester.testDone()


    tester.startTest("Modify Invalid XML Document")
    repo = test_helper.GetRepo(tester)
    test = repo.fetchResource('/test')
    doc = test.fetchResource('doc1')
    tester.testException(doc.setContent,(DOC2,),FtServerServerException,{'code':Error.VALIDATION_ERROR})
    repo.txRollback()
    tester.testDone()




   
DOC1="""<docelem v='foo'/>"""
DOC2="""<docelem w='foo'/>"""

SCHEMA1="""<schema xmlns='http://www.ascc.net/xml/schematron'>
    
  <pattern name='Root'>
    <rule context="/docelem">
      <assert test='@v'>
        VALIDATION ERROR: The root element must have a v attribute
      </assert>      
    </rule>
  </pattern>
  
</schema>"""
    


def Test(tester):
    _init(tester)
    test_creation(tester)
    test_modification(tester)

