import os

#
#Note: While testing it might be useful to use
#
#export TRACEOUT=4ODS:4Suite.PgDatabase
#export TRACEOUT_FLAGS=LABEL
#
#Requires the database to be set up with the schema from varsity1.odl or varsity2.odl
#
#Typical test process:
#
#python ../Tools/4odb_destroy.py test
#python ../Tools/4odb_create.py test
#python basic_test5.py
#


odl_string = '''
module Test {

class Student (extent students)
{
	attribute string name;

};
};
'''
#'

DBNAME=os.environ.get("ODS_TEST_DB","ods:test")

import sys, test_util
from Ft.Ods import Database
from Ft.Ods.StorageManager.Adapters import Constants

def Test(tester):
    try:
        _Test(tester)
    finally:
        if os.path.exists('Test'):
            from distutils import dir_util
            dir_util.remove_tree('Test')
        pass

def _Test(tester):

    tester.startGroup("Extent %s Driver" % tester.ods_driver_name)

    test_util.DbInit(DBNAME,odl_string)

    tester.startTest('Testing Generated syntax')
    try:
        from Test import Student
        reload(Student)
    except:
        tester.error('Error in syntax', 1)


    tester.testDone()


    db = Database.Database()
    db.open(DBNAME)

    tester.startTest("Test Empty")
    tx = db.new()
    tx.begin()

    ext = db.lookup('students')

    tester.testResults(0,len(ext),done=0,msg="Too many extents when suppoed to be empty")

    tester.testDone()
    tester.startTest("Test Adding")

    s = Student.new(db)
    s.name = 'Mike Olson'

    tester.testResults(1,len(ext),done=0,msg="Too many extents when suppoed to be one")
    tester.testResults(s,ext[0],done=0,msg="Wrong value in extents")
    tx.commit()

    tester.testDone()
    id = s._4ods_getId()


    tester.startTest("Test Loading Extent")
    tx = db.new()
    tx.begin()

    s = db._4ods_getPersistentObjectById(Constants.Types.POBJECT,id)

    ext = db.lookup('students')
    tester.testResults(1,len(ext),done=0,msg="Too many extents when suppoed to be one")
    tester.testResults(s,ext[0],done=0,msg="Wrong value in extents")

    tester.testDone()
    
    tester.startTest("Test Deleting")
    s2 = ext[0]
    s2.delete()

    tester.testResults(0,len(ext),done=0,msg="Too many extents when suppoed to be empty")

    tx.commit()

    tester.testDone()
    
    tester.startTest("Test Loading after delete")
    tx = db.new()
    tx.begin()

    ext = db.lookup('students')
    tester.testResults(0,len(ext),done=0,msg="Too many extents when suppoed to be empty")

    tester.testDone()
    tester.groupDone()
    tx.abort()
    db.close()
    
if __name__ == '__main__':

    from Ft.Lib import TestSuite
    tester = TestSuite.TestSuite(1, 1)
    from Ft.Ods.StorageManager import Adapters
    tester.ods_driver_name = Adapters.g_driverName

    retVal = Test(tester)
    sys.exit(retVal)

