## $Id: tests.py 7357 2011-12-16 06:40:31Z henrik $
##
## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
## 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 hostels and their UI components.
"""
import shutil
import tempfile
import grok
from zope.event import notify

from zope.interface.verify import verifyClass, verifyObject
from zope.component.hooks import setSite, clearSite
from zope.testbrowser.testing import Browser
from zope.security.interfaces import Unauthorized
from zope.catalog.interfaces import ICatalog
from zope.component import queryUtility
from waeup.sirp.app import University
from waeup.sirp.hostels.interfaces import (
    IHostelsContainer, IHostel, IBed)
from waeup.sirp.hostels.container import HostelsContainer
from waeup.sirp.hostels.hostel import Hostel, Bed
from waeup.sirp.testing import (FunctionalLayer, FunctionalTestCase)
from waeup.sirp.students.student import Student
from waeup.sirp.students.accommodation import BedTicket
from waeup.sirp.university.department import Department

class HostelsContainerTestCase(FunctionalTestCase):

    layer = FunctionalLayer

    def test_interfaces(self):
        # Make sure the correct interfaces are implemented.
        self.assertTrue(
            verifyClass(
                IHostelsContainer, HostelsContainer)
            )
        self.assertTrue(
            verifyObject(
                IHostelsContainer, HostelsContainer())
            )
        self.assertTrue(
            verifyClass(
                IHostel, Hostel)
            )
        self.assertTrue(
            verifyObject(
                IHostel, Hostel())
            )
        self.assertTrue(
            verifyClass(
                IBed, Bed)
            )
        self.assertTrue(
            verifyObject(
                IBed, Bed())
            )
        return

    def test_base(self):
        # We cannot call the fundamental methods of a base in that case
        container = HostelsContainer()
        hostel = Hostel()
        self.assertRaises(
            NotImplementedError, container.archive)
        self.assertRaises(
            NotImplementedError, container.clear)
        # We cannot add arbitrary objects
        department = Department()
        self.assertRaises(
            TypeError, container.addHostel, department)
        self.assertRaises(
            TypeError, hostel.addBed, department)

class HostelsFullSetup(FunctionalTestCase):

    def setUp(self):
        super(HostelsFullSetup, self).setUp()

        # Setup a sample site for each test
        app = University()
        self.dc_root = tempfile.mkdtemp()
        app['datacenter'].setStoragePath(self.dc_root)

        # Prepopulate the ZODB...
        self.getRootFolder()['app'] = app
        # we add the site immediately after creation to the
        # ZODB. Catalogs and other local utilities are not setup
        # before that step.
        self.app = self.getRootFolder()['app']
        # Set site here. Some of the following setup code might need
        # to access grok.getSite() and should get our new app then
        setSite(app)

        # Add student with subobjects
        student = Student()
        student.firstname = u'Anna'
        student.lastname = u'Tester'
        student.reg_number = u'123'
        student.matric_number = u'234'
        student.sex = u'f'
        self.app['students'].addStudent(student)
        self.student_id = student.student_id
        self.student = self.app['students'][self.student_id]
        self.student['studycourse'].current_session = 2004
        self.student['studycourse'].entry_session = 2004
        # The students_catalog must be informed that the
        # session attribute has changed
        notify(grok.ObjectModifiedEvent(self.student))

        # Set accommodation_session
        self.app['configuration'].accommodation_session = 2004

        # Create a hostel
        hostel = Hostel()
        hostel.hostel_id = u'hall-x'
        self.app['hostels'][hostel.hostel_id] = hostel

        # Create a bed
        bed = Bed()
        bed.bed_id = u'xyz'
        bed.bed_number = 1
        bed.bed_type = u'abc'
        self.app['hostels'][hostel.hostel_id][bed.bed_id] = bed

        self.container_path = 'http://localhost/app/hostels'
        self.student_path = 'http://localhost/app/students/%s' % self.student_id
        self.manage_container_path = self.container_path + '/@@manage'
        self.add_hostel_path = self.container_path + '/addhostel'

        # Put the prepopulated site into test ZODB and prepare test
        # browser
        self.browser = Browser()
        self.browser.handleErrors = False

    def tearDown(self):
        super(HostelsFullSetup, self).tearDown()
        clearSite()
        shutil.rmtree(self.dc_root)

class BedCatalogTests(HostelsFullSetup):

    layer = FunctionalLayer

    def test_get_catalog(self):
        # We can get a beds catalog if we wish
        cat = queryUtility(ICatalog, name='beds_catalog')
        assert cat is not None

    def test_search_by_type(self):
        # We can find a certain bed
        cat = queryUtility(ICatalog, name='beds_catalog')
        results = cat.searchResults(bed_type=(u'abc', u'abc'))
        results = [x for x in results] # Turn results generator into list
        assert len(results) == 1
        assert results[0] is self.app['hostels']['hall-x']['xyz']

    def test_search_by_owner(self):
        # We can find a certain bed
        myobj = self.app['hostels']['hall-x']['xyz']
        myobj.owner = u'abc'
        notify(grok.ObjectModifiedEvent(myobj))
        cat = queryUtility(ICatalog, name='beds_catalog')
        results = cat.searchResults(owner=(u'abc', u'abc'))
        results = [x for x in results] # Turn results generator into list
        assert len(results) == 1
        assert results[0] is self.app['hostels']['hall-x']['xyz']

class HostelsUITests(HostelsFullSetup):

    layer = FunctionalLayer

    def test_anonymous_access(self):
        # Anonymous users can't access hostels containers
        self.assertRaises(
            Unauthorized, self.browser.open, self.manage_container_path)
        return

    def test_add_search_edit_delete_manage_hostels(self):
        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
        self.browser.open(self.container_path)
        self.browser.getLink("Manage accommodation").click()
        self.assertEqual(self.browser.headers['Status'], '200 Ok')
        self.assertEqual(self.browser.url, self.manage_container_path)
        self.browser.getControl("Add hostel").click()
        self.assertEqual(self.browser.headers['Status'], '200 Ok')
        self.assertEqual(self.browser.url, self.add_hostel_path)
        self.browser.getControl("Create hostel").click()
        self.assertEqual(self.browser.headers['Status'], '200 Ok')
        self.assertTrue('Hostel created' in self.browser.contents)
        self.browser.open(self.container_path + '/addhostel')
        self.browser.getControl("Create hostel").click()
        self.assertTrue('The hostel already exists' in self.browser.contents)
        hall = self.app['hostels']['hall-1']
        hall.blocks_for_female = ['A','B']
        self.browser.open(self.container_path + '/hall-1')
        expected = '''...<ul id="form.blocks_for_female" ><li>Block A</li>
<li>Block B</li></ul>...'''
        self.assertMatches(expected,self.browser.contents)
        self.browser.open(self.container_path + '/hall-1/manage')
        self.browser.getControl(name="form.rooms_per_floor").value = '1'
        self.browser.getControl("Save").click()
        self.assertTrue('Form has been saved' in self.browser.contents)
        # Since the testbrowser does not support Javascrip the
        # save action cleared the settings above and we have to set them
        # again
        self.assertTrue(len(hall.blocks_for_female) == 0)
        hall.blocks_for_female = ['A','B']
        hall.beds_for_fresh = ['A']
        hall.beds_for_returning = ['B']
        hall.beds_for_final = ['C']
        hall.beds_for_all = ['D','E']
        self.browser.getControl("Update all beds").click()
        expected = '...0 empty beds removed, 10 beds added, 0 occupied beds modified ()...'
        self.assertMatches(expected,self.browser.contents)
        cat = queryUtility(ICatalog, name='beds_catalog')
        results = cat.searchResults(
            bed_type=('regular_female_all', 'regular_female_all'))
        results = [x for x in results]
        assert len(results) == 4
        # Reserve bed
        self.browser.getControl("Switch reservation", index=0).click()
        self.assertTrue('No item selected' in self.browser.contents)
        ctrl = self.browser.getControl(name='val_id')
        ctrl.getControl(value='hall-1_A_101_A').selected = True
        ctrl.getControl(value='hall-1_A_101_B').selected = True
        ctrl.getControl(value='hall-1_A_101_C').selected = True
        ctrl.getControl(value='hall-1_A_101_D').selected = True
        self.browser.getControl("Switch reservation", index=0).click()
        self.assertTrue('Successfully switched beds: hall-1_A_101_A (reserved)'
            in self.browser.contents)
        assert self.app['hostels']['hall-1'][
            'hall-1_A_101_D'].bed_type == 'regular_female_reserved'
        expected = 'name="form.beds_reserved.0." size="20" type="text" value="A_101_A"  />'
        self.assertTrue(expected in self.browser.contents)
        # Provoke exception
        self.app['hostels']['hall-1']['hall-1_A_101_D'].bed_type = u'nonsense'
        ctrl = self.browser.getControl(name='val_id')
        ctrl.getControl(value='hall-1_A_101_D').selected = True
        self.browser.getControl("Switch reservation", index=0).click()
        self.assertMatches(
            '...need more than 1 value to unpack...', self.browser.contents)
        self.app['hostels']['hall-1'][
            'hall-1_A_101_D'].bed_type = u'regular_female_reserved'
        # Change hostel configuration
        hall.beds_for_all = ['D']
        self.browser.getControl("Update all beds").click()
        expected = '...10 empty beds removed, 8 beds added, 0 occupied beds modified...'
        self.assertMatches(expected,self.browser.contents)
        results = cat.searchResults(
            bed_type=('regular_female_all', 'regular_female_all'))
        results = [x for x in results]
        assert len(results) == 1
        # Unreserve bed
        ctrl = self.browser.getControl(name='val_id')
        ctrl.getControl(value='hall-1_A_101_A').selected = True
        ctrl.getControl(value='hall-1_A_101_B').selected = True
        ctrl.getControl(value='hall-1_A_101_C').selected = True
        ctrl.getControl(value='hall-1_A_101_D').selected = True
        self.browser.getControl("Switch reservation", index=0).click()
        assert self.app['hostels']['hall-1'][
            'hall-1_A_101_D'].bed_type == 'regular_female_all'
        self.assertFalse(expected in self.browser.contents)
        # Release bed which has previously been booked
        bedticket = BedTicket()
        bedticket.ticket_id = u'2004'
        bedticket.bed_coordinates = u'anything'
        self.student['accommodation'].addBedTicket(bedticket)
        self.app['hostels']['hall-1']['hall-1_A_101_D'].owner = self.student_id
        self.browser.open(self.container_path + '/hall-1/manage')
        ctrl = self.browser.getControl(name='val_id')
        self.browser.getControl("Release selected beds", index=0).click()
        self.assertMatches("...No item selected...", self.browser.contents)
        ctrl = self.browser.getControl(name='val_id')
        ctrl.getControl(value='hall-1_A_101_D').selected = True
        self.browser.getControl("Release selected beds", index=0).click()
        self.assertMatches(
          '...Successfully released beds: hall-1_A_101_D (%s)...' % self.student_id,
          self.browser.contents)
        self.assertMatches(bedticket.bed_coordinates,
          u' -- booking cancelled on <YYYY-MM-DD hh:mm:ss> --')
        # If we release a free be, nothing will happen
        ctrl = self.browser.getControl(name='val_id')
        ctrl.getControl(value='hall-1_A_101_D').selected = True
        self.browser.getControl("Release selected beds", index=0).click()
        self.assertMatches(
          '...No allocated bed selected...', self.browser.contents)
        # Managers can manually allocate studenst after cancellation
        self.browser.open(self.container_path + '/hall-1/hall-1_A_101_A')
        self.browser.getControl(name="form.owner").value = [self.student_id]
        self.browser.getControl("Save").click()
        self.assertMatches("...Form has been saved...", self.browser.contents)
        # If we open the same form again, we will be redirected to hostel
        # manage page. Beds must be released first before they can be
        # allocated to other students.
        self.browser.open(self.container_path + '/hall-1/hall-1_A_101_A')
        self.assertEqual(self.browser.url,
            self.container_path + '/hall-1/@@manage#tab-2')
        # Updating the beds again will not affect the allocation and also
        # the bed numbering remains the same
        old_number = self.app['hostels']['hall-1']['hall-1_A_101_A'].bed_number
        old_owner = self.app['hostels']['hall-1']['hall-1_A_101_A'].owner
        self.browser.getControl("Update all beds").click()
        # 7 beds have been removed and re-added, 1 bed remains untouched
        expected = '...7 empty beds removed, 7 beds added, 0 occupied beds modified...'
        self.assertMatches(expected,self.browser.contents)
        new_number = self.app['hostels']['hall-1']['hall-1_A_101_A'].bed_number
        new_owner = self.app['hostels']['hall-1']['hall-1_A_101_A'].owner
        self.assertEqual(new_number, old_number)
        self.assertEqual(new_owner, old_owner)
        # If we change the bed type of an allocated bed, the modification will
        # be indicated
        hall.blocks_for_female = ['B']
        hall.blocks_for_male = ['A']
        self.browser.getControl("Update all beds").click()
        expected = '...7 empty beds removed, 7 beds added, ' + \
            '1 occupied beds modified (hall-1_A_101_A )...'
        self.assertMatches(expected,self.browser.contents)
        new_number = self.app['hostels']['hall-1']['hall-1_A_101_A'].bed_number
        # Also the number of the bed has changed.
        self.assertFalse(new_number == old_number)
        # Remove entire hostel
        self.browser.open(self.manage_container_path)
        ctrl = self.browser.getControl(name='val_id')
        value = ctrl.options[0]
        ctrl.getControl(value=value).selected = True
        self.browser.getControl("Remove selected", index=0).click()
        self.assertTrue('Successfully removed' in self.browser.contents)
        # Catalog is empty
        results = cat.searchResults(
            bed_type=('regular_female_all', 'regular_female_all'))
        results = [x for x in results]
        assert len(results) == 0
