##
## test_jambtables.py
## Login : <uli@pu.smp.net>
## Started on  Thu Jun 24 08:08:12 2010 Uli Fouquet
## $Id$
## 
## Copyright (C) 2010 Uli Fouquet
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## 
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
## 
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
"""
Tests for JAMB tables.

"""
import os
import shutil
import tempfile
import unittest

import grok

from datetime import datetime

from zope.interface.verify import verifyClass, verifyObject
from zope.site import LocalSiteManager
from zope.site.hooks import setSite, clearSite

from waeup.sirp.app import University
from waeup.sirp.datacenter import DataCenter
from waeup.sirp.jambtables import JAMBDataTable
from waeup.sirp.jambtables.interfaces import IJAMBDataTable


class JAMBTableTestCaseBase(unittest.TestCase):

    def setUp(self):
        self.tempdir = tempfile.mkdtemp()
        self.datafile = os.path.join(
            self.tempdir, 'jambsample.csv'
            )
        open(self.datafile, 'wb').write(
            'reg_no,fst_sit_fname,lastname,firstname,middlenames,sex,date_of_birth,jamb_state,jamb_lga,course1,screening_date,screening_venue,entry_session,screening_type,ignore_this_col\n' + 
            '91100546DD,ISUOSUO MOSES ODOMERO,ISUOSUO,MOSES,ODOMERO,M,25/5/1982,DEL,ISO-S,BSCPOL,2009/09/25 09:00:00 GMT+1,REPRINT SLIP AS FROM WED 23/09/2009,9,pde,blah\n' +
            '91111834CC,DURUIHEOMA AUGUSTINA ADANNA,DURUIHEOMA,AUGUSTINA,ADANNA,F,15/4/1986,IMO,MBAIT,BSCPOL,2009/09/25 09:00:00 GMT+1,REPRINT SLIP AS FROM WED 23/09/2009,9,pde,blah\n' +
            '91109351AC,ARISERE EBIKEBUNA COMFORT,ARISERE,EBIKEBUNA,COMFORT,F,6/1/1984,EDO,OV-SW,BSCPOL,2009/09/25 09:00:00 GMT+1,REPRINT SLIP AS FROM WED 23/09/2009,9,pde,blah\n'
            )
        setSite()
        return

    def tearDown(self):
        shutil.rmtree(self.tempdir)
        return

class JAMBTableTestCase(JAMBTableTestCaseBase):
    def test_createJAMBTable(self):
        table = JAMBDataTable()
        self.assertEqual(table._data_len, 0)
        self.assertEqual(table._temporary, False)
        self.assertEqual(table._datafile_path, None)
        return

    def test_iterator(self):
        table = JAMBDataTable()
        self.assertEqual(len(list(table)), 0)
        table.importFromCSV(self.datafile)
        self.assertEqual(len(list(table)), 3)

    def test_import(self):
        table = JAMBDataTable()
        self.assertEqual(table.import_datetime, None)
        table.importFromCSV(self.datafile)
        self.assertNotEqual(table.import_datetime, None)

    def test_clear(self):
        table = JAMBDataTable()
        table.importFromCSV(self.datafile)
        path = table._datafile_path
        table.clear()
        exists = os.path.exists(path)
        self.assertEqual(exists, False)
        self.assertEqual(0, len(list(table)))

    def test_clear_broken_path(self):
        table = JAMBDataTable()
        table.importFromCSV(self.datafile)
        path = table._datafile_path
        table._datafile_path = 'not-existent-path'
        table.clear()
        
    def test_import_datetime(self):
        table = JAMBDataTable()
        self.assertTrue(table.import_datetime is None)
        table.importFromCSV(self.datafile)
        now = datetime.now()
        diff = now - table.import_datetime
        self.assertTrue(diff.seconds < 5)
        table.clear()
        self.assertTrue(table.import_datetime is None)

    def test_importer_username(self):
        table = JAMBDataTable()
        self.assertTrue(table.importer_username is None)
        table.importFromCSV(self.datafile, 'manfred')
        self.assertEqual(table.importer_username, u'manfred')
        self.assertTrue(isinstance(table.importer_username, unicode))
        table.importFromCSV(self.datafile, 'fred')
        self.assertEqual(table.importer_username, u'fred')
        table.importFromCSV(self.datafile)
        self.assertTrue(table.importer_username is None)
        table.clear()
        self.assertTrue(table.importer_username is None)

    def test_keys(self):
        table = JAMBDataTable()
        self.assertFalse('91100546DD' in table.keys())
        table.importFromCSV(self.datafile)
        self.assertTrue('91100546DD' in table.keys())
        self.assertFalse('91100546DE' in table.keys())

    def test_items(self):
        table = JAMBDataTable()
        self.assertEqual([], list(table.items()))
        table.importFromCSV(self.datafile)
        self.assertNotEqual([], list(table.items()))

    def test_interface_compliance(self):
        self.assertTrue(verifyClass(IJAMBDataTable, JAMBDataTable))
        table = JAMBDataTable()
        self.assertTrue(verifyObject(IJAMBDataTable, table))
        table.importFromCSV(self.datafile)
        self.assertTrue(verifyObject(IJAMBDataTable, table))

class JAMBTableFunctionalTestCase(JAMBTableTestCaseBase):
    """A test case where we check JAMB tables inside a site.
    """

    def setUp(self):
        super(JAMBTableFunctionalTestCase, self).setUp()
        
        # We need at least these to register factories for a University.
        grok.testing.grok('waeup.sirp.student')
        grok.testing.grok('waeup.sirp.hostel')
        grok.testing.grok('waeup.sirp.university')

        self.site = University()
        sm = LocalSiteManager(self.site)
        self.site.setSiteManager(sm)
        self.datacenter_dir = tempfile.mkdtemp()
        self.datacenter = self.site['datacenter']
        self.datacenter.setStoragePath(self.datacenter_dir)
        # If the old datacenter already had a jambtables dir, remove it...
        if os.path.isdir(
            os.path.join(self.datacenter_dir, 'jambdata')
            ):
            shutil.rmtree(os.path.join(self.datacenter_dir, 'jambdata'))
        return

    def tearDown(self):
        shutil.rmtree(self.tempdir)
        shutil.rmtree(self.datacenter_dir)
        # Unregister site...
        setSite()
        return

    def test_createJAMBTableInSite(self):
        table = JAMBDataTable()
        self.assertEqual(table._data_len, 0)
        self.assertEqual(table._temporary, False)
        self.assertEqual(table._datafile_path, None)
        table.importFromCSV(self.datafile)
        return

    def test_createJAMBTableOutsideSite(self):
        clearSite(self.site)
        table = JAMBDataTable()
        self.assertEqual(table._data_len, 0)
        self.assertEqual(table._temporary, False)
        self.assertEqual(table._datafile_path, None)
        table.importFromCSV(self.datafile)
        return

        
def test_suite():
    suite = unittest.TestSuite()
    for testcase in [
        JAMBTableTestCase,
        JAMBTableFunctionalTestCase,
        ]:
        suite.addTest(unittest.TestLoader().loadTestsFromTestCase(
                testcase
                )
        )
    return suite
