source: main/waeup.kofa/branches/uli-py3/src/waeup/kofa/students/tests/test_browser.py @ 17341

Last change on this file since 17341 was 16030, checked in by Henrik Bettermann, 5 years ago

Adjust log messages and tests.

  • Property svn:keywords set to Id
File size: 250.2 KB
Line 
1# -*- coding: utf-8 -*-
2## $Id: test_browser.py 16030 2020-03-06 21:20:29Z henrik $
3##
4## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
5## This program is free software; you can redistribute it and/or modify
6## it under the terms of the GNU General Public License as published by
7## the Free Software Foundation; either version 2 of the License, or
8## (at your option) any later version.
9##
10## This program is distributed in the hope that it will be useful,
11## but WITHOUT ANY WARRANTY; without even the implied warranty of
12## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13## GNU General Public License for more details.
14##
15## You should have received a copy of the GNU General Public License
16## along with this program; if not, write to the Free Software
17## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18##
19"""
20Test the student-related UI components.
21"""
22import shutil
23import tempfile
24import pytz
25import base64
26from datetime import datetime, timedelta, date
27from StringIO import StringIO
28import os
29import grok
30from zc.async.testing import wait_for_result
31from zope.event import notify
32from zope.component import createObject, queryUtility, getUtility
33from zope.component.hooks import setSite, clearSite
34from zope.catalog.interfaces import ICatalog
35from zope.security.interfaces import Unauthorized
36from zope.securitypolicy.interfaces import IPrincipalRoleManager
37from zope.testbrowser.testing import Browser
38from zope.interface import implementedBy
39from zope.schema.fieldproperty import FieldProperty
40from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState
41from waeup.kofa.testing import FunctionalLayer, FunctionalTestCase
42from waeup.kofa.app import University
43from waeup.kofa.interfaces import IFileStoreNameChooser, IExtFileStore
44from waeup.kofa.payments.interfaces import IPayer
45from waeup.kofa.students.payments import StudentOnlinePayment
46from waeup.kofa.students.student import Student
47from waeup.kofa.students.studylevel import StudentStudyLevel
48from waeup.kofa.university.faculty import Faculty
49from waeup.kofa.university.department import Department
50from waeup.kofa.interfaces import IUserAccount, IJobManager, VALIDATED, CREATED
51from waeup.kofa.authentication import LocalRoleSetEvent
52from waeup.kofa.hostels.hostel import Hostel, Bed, NOT_OCCUPIED
53from waeup.kofa.tests.test_async import FunctionalAsyncTestCase
54from waeup.kofa.browser.tests.test_pdf import samples_dir
55from waeup.kofa.tests.test_authentication import SECRET
56
57PH_LEN = 15911  # Length of placeholder file
58
59SAMPLE_IMAGE = os.path.join(os.path.dirname(__file__), 'test_image.jpg')
60SAMPLE_IMAGE_BMP = os.path.join(os.path.dirname(__file__), 'test_image.bmp')
61URL_LECTURER_LANDING = 'http://localhost/app/my_courses'
62
63curr_year = datetime.now().year
64
65def lookup_submit_value(name, value, browser):
66    """Find a button with a certain value."""
67    for num in range(0, 100):
68        try:
69            button = browser.getControl(name=name, index=num)
70            if button.value.endswith(value):
71                return button
72        except IndexError:
73            break
74    return None
75
76
77class StudentsFullSetup(FunctionalTestCase):
78    # A test case that only contains a setup and teardown
79    #
80    # Complete setup for students handlings is rather complex and
81    # requires lots of things created before we can start. This is a
82    # setup that does all this, creates a university, creates PINs,
83    # etc.  so that we do not have to bother with that in different
84    # test cases.
85
86    layer = FunctionalLayer
87
88    def setUp(self):
89        super(StudentsFullSetup, self).setUp()
90
91        # Setup a sample site for each test
92        app = University()
93        self.dc_root = tempfile.mkdtemp()
94        app['datacenter'].setStoragePath(self.dc_root)
95
96        # Prepopulate the ZODB...
97        self.getRootFolder()['app'] = app
98        # we add the site immediately after creation to the
99        # ZODB. Catalogs and other local utilities are not setup
100        # before that step.
101        self.app = self.getRootFolder()['app']
102        # Set site here. Some of the following setup code might need
103        # to access grok.getSite() and should get our new app then
104        setSite(app)
105
106        # Add student with subobjects
107        student = createObject('waeup.Student')
108        student.firstname = u'Anna'
109        student.lastname = u'Tester'
110        student.reg_number = u'123'
111        student.matric_number = u'234'
112        student.sex = u'm'
113        student.email = 'aa@aa.ng'
114        student.phone = u'1234'
115        student.date_of_birth = date(1981, 2, 4)
116        self.app['students'].addStudent(student)
117        self.student_id = student.student_id
118        self.student = self.app['students'][self.student_id]
119
120        # Set password
121        IUserAccount(
122            self.app['students'][self.student_id]).setPassword('spwd')
123
124        self.login_path = 'http://localhost/app/login'
125        self.container_path = 'http://localhost/app/students'
126        self.manage_container_path = self.container_path + '/@@manage'
127        self.add_student_path = self.container_path + '/addstudent'
128        self.student_path = self.container_path + '/' + self.student_id
129        self.manage_student_path = self.student_path + '/manage_base'
130        self.trigtrans_path = self.student_path + '/trigtrans'
131        self.clearance_path = self.student_path + '/view_clearance'
132        self.personal_path = self.student_path + '/view_personal'
133        self.edit_clearance_path = self.student_path + '/cedit'
134        self.manage_clearance_path = self.student_path + '/manage_clearance'
135        self.edit_personal_path = self.student_path + '/edit_personal'
136        self.manage_personal_path = self.student_path + '/manage_personal'
137        self.studycourse_path = self.student_path + '/studycourse'
138        self.payments_path = self.student_path + '/payments'
139        self.acco_path = self.student_path + '/accommodation'
140        self.history_path = self.student_path + '/history'
141
142        # Create 5 access codes with prefix'PWD'
143        pin_container = self.app['accesscodes']
144        pin_container.createBatch(
145            datetime.utcnow(), 'some_userid', 'PWD', 9.99, 5)
146        pins = pin_container['PWD-1'].values()
147        self.pwdpins = [x.representation for x in pins]
148        self.existing_pwdpin = self.pwdpins[0]
149        parts = self.existing_pwdpin.split('-')[1:]
150        self.existing_pwdseries, self.existing_pwdnumber = parts
151        # Create 5 access codes with prefix 'CLR'
152        pin_container.createBatch(
153            datetime.now(), 'some_userid', 'CLR', 9.99, 5)
154        pins = pin_container['CLR-1'].values()
155        pins[0].owner = u'Hans Wurst'
156        self.existing_clrac = pins[0]
157        self.existing_clrpin = pins[0].representation
158        parts = self.existing_clrpin.split('-')[1:]
159        self.existing_clrseries, self.existing_clrnumber = parts
160        # Create 2 access codes with prefix 'HOS'
161        pin_container.createBatch(
162            datetime.now(), 'some_userid', 'HOS', 9.99, 2)
163        pins = pin_container['HOS-1'].values()
164        self.existing_hosac = pins[0]
165        self.existing_hospin = pins[0].representation
166        parts = self.existing_hospin.split('-')[1:]
167        self.existing_hosseries, self.existing_hosnumber = parts
168
169        # Populate university
170        self.certificate = createObject('waeup.Certificate')
171        self.certificate.code = u'CERT1'
172        self.certificate.application_category = 'basic'
173        self.certificate.study_mode = 'ug_ft'
174        self.certificate.start_level = 100
175        self.certificate.end_level = 500
176        self.certificate.school_fee_1 = 40000.0
177        self.certificate.school_fee_2 = 20000.0
178        self.app['faculties']['fac1'] = Faculty(code=u'fac1')
179        self.app['faculties']['fac1']['dep1'] = Department(code=u'dep1')
180        self.app['faculties']['fac1']['dep1'].certificates.addCertificate(
181            self.certificate)
182        self.course = createObject('waeup.Course')
183        self.course.code = 'COURSE1'
184        self.course.semester = 1
185        self.course.credits = 10
186        self.course.passmark = 40
187        self.app['faculties']['fac1']['dep1'].courses.addCourse(
188            self.course)
189        self.app['faculties']['fac1']['dep1'].certificates[
190            'CERT1'].addCertCourse(self.course, level=100)
191
192        # Configure university and hostels
193        self.app['hostels'].accommodation_states = ['admitted']
194        self.app['hostels'].accommodation_session = 2004
195        delta = timedelta(days=10)
196        self.app['hostels'].startdate = datetime.now(pytz.utc) - delta
197        self.app['hostels'].enddate = datetime.now(pytz.utc) + delta
198        self.app['configuration'].carry_over = True
199        configuration = createObject('waeup.SessionConfiguration')
200        configuration.academic_session = 2004
201        configuration.clearance_fee = 3456.0
202        configuration.transcript_fee = 4567.0
203        configuration.booking_fee = 123.4
204        configuration.maint_fee = 987.0
205        configuration.transfer_fee = 456.0
206        configuration.late_registration_fee = 345.0
207        self.app['configuration'].addSessionConfiguration(configuration)
208
209        # Create a hostel with two beds
210        hostel = Hostel()
211        hostel.hostel_id = u'hall-1'
212        hostel.hostel_name = u'Hall 1'
213        hostel.maint_fee = 876.0
214        self.app['hostels'].addHostel(hostel)
215        bed = Bed()
216        bed.bed_id = u'hall-1_A_101_A'
217        bed.bed_number = 1
218        bed.owner = NOT_OCCUPIED
219        bed.bed_type = u'regular_male_fr'
220        self.app['hostels'][hostel.hostel_id].addBed(bed)
221        bed = Bed()
222        bed.bed_id = u'hall-1_A_101_B'
223        bed.bed_number = 2
224        bed.owner = NOT_OCCUPIED
225        bed.bed_type = u'regular_female_fr'
226        self.app['hostels'][hostel.hostel_id].addBed(bed)
227
228        # Set study course attributes of test student
229        self.student['studycourse'].certificate = self.certificate
230        self.student['studycourse'].current_session = 2004
231        self.student['studycourse'].entry_session = 2004
232        self.student['studycourse'].current_verdict = 'A'
233        self.student['studycourse'].current_level = 100
234        # Update the catalog
235        notify(grok.ObjectModifiedEvent(self.student))
236
237        # Put the prepopulated site into test ZODB and prepare test
238        # browser
239        self.browser = Browser()
240        self.browser.handleErrors = False
241
242    def tearDown(self):
243        super(StudentsFullSetup, self).tearDown()
244        clearSite()
245        shutil.rmtree(self.dc_root)
246
247
248class StudentsContainerUITests(StudentsFullSetup):
249    # Tests for StudentsContainer class views and pages
250
251    layer = FunctionalLayer
252
253    def test_anonymous_access(self):
254        # Anonymous users can't access students containers
255        self.assertRaises(
256            Unauthorized, self.browser.open, self.container_path)
257        self.assertRaises(
258            Unauthorized, self.browser.open, self.manage_container_path)
259        return
260
261    def test_manage_access(self):
262        # Managers can access the view page of students
263        # containers and can perform actions
264        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
265        self.browser.open(self.container_path)
266        self.assertEqual(self.browser.headers['Status'], '200 Ok')
267        self.assertEqual(self.browser.url, self.container_path)
268        self.browser.getLink("Manage students section").click()
269        self.assertEqual(self.browser.headers['Status'], '200 Ok')
270        self.assertEqual(self.browser.url, self.manage_container_path)
271        return
272
273    def test_add_search_delete_students(self):
274        # Managers can add search and remove students
275        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
276        self.browser.open(self.manage_container_path)
277        self.browser.getLink("Add student").click()
278        self.assertEqual(self.browser.headers['Status'], '200 Ok')
279        self.assertEqual(self.browser.url, self.add_student_path)
280        self.browser.getControl(name="form.firstname").value = 'Bob'
281        self.browser.getControl(name="form.lastname").value = 'Tester'
282        self.browser.getControl(name="form.reg_number").value = '123'
283        self.browser.getControl("Create student").click()
284        self.assertTrue(
285            'Registration number exists already' in self.browser.contents)
286        self.browser.getControl(name="form.reg_number").value = '1234'
287        self.browser.getControl("Create student").click()
288        self.assertTrue('Student record created' in self.browser.contents)
289
290        # Registration and matric numbers must be unique
291        self.browser.getLink("Manage").click()
292        self.browser.getControl(name="form.reg_number").value = '123'
293        self.browser.getControl("Save").click()
294        self.assertMatches('...Registration number exists...',
295                           self.browser.contents)
296        self.browser.getControl(name="form.reg_number").value = '789'
297        self.browser.getControl(name="form.matric_number").value = '234'
298        self.browser.getControl("Save").click()
299        self.assertMatches('...Matriculation number exists...',
300                           self.browser.contents)
301
302        # We can find a student with a certain student_id
303        self.browser.open(self.container_path)
304        self.browser.getControl("Find student(s)").click()
305        self.assertTrue('Empty search string' in self.browser.contents)
306        self.browser.getControl(name="searchtype").value = ['student_id']
307        self.browser.getControl(name="searchterm").value = self.student_id
308        self.browser.getControl("Find student(s)").click()
309        self.assertTrue('Anna Tester' in self.browser.contents)
310
311        # We can find a student in a certain session
312        self.browser.open(self.container_path)
313        self.browser.getControl(name="searchtype").value = ['current_session']
314        self.browser.getControl(name="searchterm").value = '2004'
315        self.browser.getControl("Find student(s)").click()
316        self.assertTrue('Anna Tester' in self.browser.contents)
317        # Session fileds require integer values
318        self.browser.open(self.container_path)
319        self.browser.getControl(name="searchtype").value = ['current_session']
320        self.browser.getControl(name="searchterm").value = '2004/2005'
321        self.browser.getControl("Find student(s)").click()
322        self.assertTrue('Only year dates allowed' in self.browser.contents)
323        self.browser.open(self.manage_container_path)
324        self.browser.getControl(name="searchtype").value = ['current_session']
325        self.browser.getControl(name="searchterm").value = '2004/2005'
326        self.browser.getControl("Find student(s)").click()
327        self.assertTrue('Only year dates allowed' in self.browser.contents)
328
329        # We can find a student in a certain study_mode
330        self.browser.open(self.container_path)
331        self.browser.getControl(name="searchtype").value = ['current_mode']
332        self.browser.getControl(name="searchterm").value = 'ug_ft'
333        self.browser.getControl("Find student(s)").click()
334        self.assertTrue('Anna Tester' in self.browser.contents)
335
336        # We can find a student in a certain department
337        self.browser.open(self.container_path)
338        self.browser.getControl(name="searchtype").value = ['depcode']
339        self.browser.getControl(name="searchterm").value = 'dep1'
340        self.browser.getControl("Find student(s)").click()
341        self.assertTrue('Anna Tester' in self.browser.contents)
342
343        # We can find a student by searching for all kind of name parts
344        self.browser.open(self.manage_container_path)
345        self.browser.getControl("Find student(s)").click()
346        self.assertTrue('Empty search string' in self.browser.contents)
347        self.browser.getControl(name="searchtype").value = ['fullname']
348        self.browser.getControl(name="searchterm").value = 'Anna Tester'
349        self.browser.getControl("Find student(s)").click()
350        self.assertTrue('Anna Tester' in self.browser.contents)
351        self.browser.open(self.manage_container_path)
352        self.browser.getControl(name="searchtype").value = ['fullname']
353        self.browser.getControl(name="searchterm").value = 'Anna'
354        self.browser.getControl("Find student(s)").click()
355        self.assertTrue('Anna Tester' in self.browser.contents)
356        self.browser.open(self.manage_container_path)
357        self.browser.getControl(name="searchtype").value = ['fullname']
358        self.browser.getControl(name="searchterm").value = 'Tester'
359        self.browser.getControl("Find student(s)").click()
360        self.assertTrue('Anna Tester' in self.browser.contents)
361        self.browser.open(self.manage_container_path)
362        self.browser.getControl(name="searchtype").value = ['fullname']
363        self.browser.getControl(name="searchterm").value = 'An'
364        self.browser.getControl("Find student(s)").click()
365        self.assertFalse('Anna Tester' in self.browser.contents)
366        self.browser.open(self.manage_container_path)
367        self.browser.getControl(name="searchtype").value = ['fullname']
368        self.browser.getControl(name="searchterm").value = 'An*'
369        self.browser.getControl("Find student(s)").click()
370        self.assertTrue('Anna Tester' in self.browser.contents)
371        self.browser.open(self.manage_container_path)
372        self.browser.getControl(name="searchtype").value = ['fullname']
373        self.browser.getControl(name="searchterm").value = 'tester'
374        self.browser.getControl("Find student(s)").click()
375        self.assertTrue('Anna Tester' in self.browser.contents)
376        self.browser.open(self.manage_container_path)
377        self.browser.getControl(name="searchtype").value = ['fullname']
378        self.browser.getControl(name="searchterm").value = 'Tester Ana'
379        self.browser.getControl("Find student(s)").click()
380        self.assertFalse('Anna Tester' in self.browser.contents)
381        self.browser.open(self.manage_container_path)
382        self.browser.getControl(name="searchtype").value = ['fullname']
383        self.browser.getControl(name="searchterm").value = 'Tester Anna'
384        self.browser.getControl("Find student(s)").click()
385        self.assertTrue('Anna Tester' in self.browser.contents)
386        # The old searchterm will be used again
387        self.browser.getControl("Find student(s)").click()
388        self.assertTrue('Anna Tester' in self.browser.contents)
389
390        # We can find suspended students
391        self.student.suspended = True
392        notify(grok.ObjectModifiedEvent(self.student))
393        self.browser.open(self.manage_container_path)
394        self.browser.getControl(name="searchtype").value = ['suspended']
395        self.browser.getControl("Find student(s)").click()
396        self.assertTrue('Anna Tester' in self.browser.contents)
397        self.browser.open(self.container_path)
398        self.browser.getControl(name="searchtype").value = ['suspended']
399        self.browser.getControl("Find student(s)").click()
400        self.assertTrue('Anna Tester' in self.browser.contents)
401
402        # The catalog is informed when studycourse objects have been
403        # edited
404        self.browser.open(self.studycourse_path + '/manage')
405        self.browser.getControl(name="form.current_session").value = ['2010']
406        self.browser.getControl(name="form.entry_session").value = ['2010']
407        self.browser.getControl(name="form.entry_mode").value = ['ug_ft']
408        self.browser.getControl("Save").click()
409
410        # We can find the student in the new session
411        self.browser.open(self.manage_container_path)
412        self.browser.getControl(name="searchtype").value = ['current_session']
413        self.browser.getControl(name="searchterm").value = '2010'
414        self.browser.getControl("Find student(s)").click()
415        self.assertTrue('Anna Tester' in self.browser.contents)
416
417        ctrl = self.browser.getControl(name='entries')
418        ctrl.getControl(value=self.student_id).selected = True
419        self.browser.getControl("Remove selected", index=0).click()
420        self.assertTrue('Successfully removed' in self.browser.contents)
421        self.browser.getControl(name="searchtype").value = ['student_id']
422        self.browser.getControl(name="searchterm").value = self.student_id
423        self.browser.getControl("Find student(s)").click()
424        self.assertTrue('No student found' in self.browser.contents)
425
426        self.browser.open(self.container_path)
427        self.browser.getControl(name="searchtype").value = ['student_id']
428        self.browser.getControl(name="searchterm").value = self.student_id
429        self.browser.getControl("Find student(s)").click()
430        self.assertTrue('No student found' in self.browser.contents)
431        return
432
433    def test_add_graduated_students(self):
434        # Managers can add search and remove students
435        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
436        self.browser.open(self.manage_container_path)
437        self.browser.getLink("Add student").click()
438        self.assertEqual(self.browser.headers['Status'], '200 Ok')
439        self.assertEqual(self.browser.url, self.add_student_path)
440        self.browser.getControl(name="form.firstname").value = 'Bob'
441        self.browser.getControl(name="form.lastname").value = 'Tester'
442        self.browser.getControl(name="form.reg_number").value = '1234'
443        self.browser.getControl("Create graduated student").click()
444        self.assertTrue('Graduated student record created' in self.browser.contents)
445        self.assertEqual(self.app['students']['K1000001'].state, 'graduated')
446        self.browser.open("http://localhost/app/students/K1000001/history")
447        self.assertTrue("State 'graduated' set by Manager" in self.browser.contents)
448        return
449
450
451class OfficerUITests(StudentsFullSetup):
452    # Tests for Student class views and pages
453
454    def test_student_properties(self):
455        self.student['studycourse'].current_level = 100
456        self.assertEqual(self.student.current_level, 100)
457        self.student['studycourse'].current_session = 2011
458        self.assertEqual(self.student.current_session, 2011)
459        self.student['studycourse'].current_verdict = 'A'
460        self.assertEqual(self.student.current_verdict, 'A')
461        return
462
463    def test_studylevelmanagepage(self):
464        studylevel = StudentStudyLevel()
465        studylevel.level = 100
466        cert = self.app['faculties']['fac1']['dep1'].certificates['CERT1']
467        self.student['studycourse'].addStudentStudyLevel(cert, studylevel)
468        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
469        self.browser.open(self.studycourse_path + '/100/manage')
470        self.assertEqual(
471            self.browser.url, self.studycourse_path + '/100/manage')
472        self.assertEqual(self.browser.headers['Status'], '200 Ok')
473
474    def test_basic_auth(self):
475        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
476        self.browser.open('http://localhost/app')
477        self.browser.getLink("Logout").click()
478        self.assertTrue('You have been logged out' in self.browser.contents)
479        # But we are still logged in since we've used basic
480        # authentication here.  Wikipedia says: Existing browsers
481        # retain authentication information until the tab or browser
482        # is closed or the user clears the history.  HTTP does not
483        # provide a method for a server to direct clients to discard
484        # these cached credentials. This means that there is no
485        # effective way for a server to "log out" the user without
486        # closing the browser. This is a significant defect that
487        # requires browser manufacturers to support a "logout" user
488        # interface element ...
489        self.assertTrue('Manager' in self.browser.contents)
490
491    def test_basic_auth_base64(self):
492        auth_token = base64.b64encode('mgr:mgrpw')
493        self.browser.addHeader('Authorization', 'Basic %s' % auth_token)
494        self.browser.open(self.manage_container_path)
495        self.assertEqual(self.browser.headers['Status'], '200 Ok')
496
497    def test_manage_access(self):
498        # Managers can access the pages of students
499        # and can perform actions
500        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
501        self.browser.open(self.student_path)
502        self.assertEqual(self.browser.headers['Status'], '200 Ok')
503        self.assertEqual(self.browser.url, self.student_path)
504        self.browser.getLink("Trigger").click()
505        self.assertEqual(self.browser.headers['Status'], '200 Ok')
506        # Managers can trigger transitions
507        self.browser.getControl(name="transition").value = ['admit']
508        self.browser.getControl("Save").click()
509        # Managers can edit base
510        self.browser.open(self.student_path)
511        self.browser.getLink("Manage").click()
512        self.assertEqual(self.browser.url, self.manage_student_path)
513        self.assertEqual(self.browser.headers['Status'], '200 Ok')
514        self.browser.getControl(name="form.firstname").value = 'John'
515        self.browser.getControl(name="form.lastname").value = 'Tester'
516        self.browser.getControl(name="form.reg_number").value = '345'
517        self.browser.getControl(name="password").value = 'secret'
518        self.browser.getControl(name="control_password").value = 'secret'
519        self.browser.getControl("Save").click()
520        self.assertMatches('...Form has been saved...',
521                           self.browser.contents)
522        self.browser.open(self.student_path)
523        self.browser.getLink("Clearance Data").click()
524        self.assertEqual(self.browser.headers['Status'], '200 Ok')
525        self.assertEqual(self.browser.url, self.clearance_path)
526        self.browser.getLink("Manage").click()
527        self.assertEqual(self.browser.headers['Status'], '200 Ok')
528        self.assertEqual(self.browser.url, self.manage_clearance_path)
529        self.browser.getControl(name="form.date_of_birth").value = '09/10/1961'
530        self.browser.getControl("Save").click()
531        self.assertMatches('...Form has been saved...',
532                           self.browser.contents)
533
534        self.browser.open(self.student_path)
535        self.browser.getLink("Personal Data").click()
536        self.assertEqual(self.browser.headers['Status'], '200 Ok')
537        self.assertEqual(self.browser.url, self.personal_path)
538        self.browser.getLink("Manage").click()
539        self.assertEqual(self.browser.headers['Status'], '200 Ok')
540        self.assertEqual(self.browser.url, self.manage_personal_path)
541        self.browser.open(self.personal_path)
542        self.assertTrue('Updated' in self.browser.contents)
543        self.browser.getLink("Edit").click()
544        self.assertEqual(self.browser.headers['Status'], '200 Ok')
545        self.assertEqual(self.browser.url, self.edit_personal_path)
546        self.browser.getControl("Save").click()
547        # perm_address is required in IStudentPersonalEdit
548        self.assertMatches('...Required input is missing...',
549                           self.browser.contents)
550        self.browser.getControl(name="form.perm_address").value = 'My address!'
551        self.browser.getControl("Save").click()
552        self.assertMatches('...Form has been saved...',
553                           self.browser.contents)
554
555        # Managers can browse all subobjects
556        self.browser.open(self.student_path)
557        self.browser.getLink("Payments").click()
558        self.assertEqual(self.browser.headers['Status'], '200 Ok')
559        self.assertEqual(self.browser.url, self.payments_path)
560        self.browser.open(self.student_path)
561        self.browser.getLink("Accommodation").click()
562        self.assertEqual(self.browser.headers['Status'], '200 Ok')
563        # We have been redirected to the manage page
564        self.assertEqual(self.browser.url, self.acco_path + '/manage')
565        self.browser.open(self.student_path)
566        self.browser.getLink("History").click()
567        self.assertEqual(self.browser.headers['Status'], '200 Ok')
568        self.assertEqual(self.browser.url, self.history_path)
569        self.assertMatches('...Admitted by Manager...',
570                           self.browser.contents)
571        # Only the Application Slip does not exist
572        self.assertFalse('Application Slip' in self.browser.contents)
573        return
574
575    def test_flash_notice(self):
576        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
577        self.browser.open(self.student_path)
578        self.assertFalse('alert alert-warning' in self.browser.contents)
579        self.student.flash_notice = u'Happy Birthday!'
580        self.browser.open(self.student_path)
581        self.assertTrue(
582            '<div><div class="alert alert-warning">Happy Birthday!</div>'
583            in self.browser.contents)
584        return
585
586    def test_manage_contact_student(self):
587        # Managers can contact student
588        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
589        # Remove required FieldProperty attribute first ...
590        delattr(Student, 'email')
591        # ... and replace by None
592        self.student.email = None
593        # Now we have to add  the FieldProperty attribute again. Otherwise
594        # many other tests below will fail.
595        iface = list(implementedBy(Student))[0]
596        field_property = FieldProperty(iface['email'])
597        setattr(Student, 'email', field_property)
598        self.browser.open(self.student_path)
599        self.browser.getLink("Send email").click()
600        self.browser.getControl(
601            name="form.subject").value = 'Important subject'
602        self.browser.getControl(name="form.body").value = 'Hello!'
603        self.browser.getControl("Send message now").click()
604        self.assertTrue(
605            'An smtp server error occurred' in self.browser.contents)
606        self.student.email = 'xx@yy.zz'
607        self.browser.getControl("Send message now").click()
608        self.assertTrue('Your message has been sent' in self.browser.contents)
609        return
610
611    def test_manage_remove_department(self):
612        # Lazy student is studying CERT1
613        lazystudent = Student()
614        lazystudent.firstname = u'Lazy'
615        lazystudent.lastname = u'Student'
616        self.app['students'].addStudent(lazystudent)
617        student_id = lazystudent.student_id
618        student_path = self.container_path + '/' + student_id
619        lazystudent['studycourse'].certificate = self.certificate
620        notify(grok.ObjectModifiedEvent(lazystudent))
621        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
622        self.browser.open(student_path + '/studycourse')
623        self.assertTrue('CERT1' in self.browser.contents)
624        # After some years the department is removed
625        del self.app['faculties']['fac1']['dep1']
626        # So CERT1 does no longer exist and lazy student's
627        # certificate reference is removed too
628        self.browser.open(student_path + '/studycourse')
629        self.assertEqual(self.browser.headers['Status'], '200 Ok')
630        self.assertEqual(self.browser.url, student_path + '/studycourse')
631        self.assertFalse('CERT1' in self.browser.contents)
632        self.assertMatches('...<div>--</div>...',
633                           self.browser.contents)
634
635    def test_manage_upload_file(self):
636        # Managers can upload a file via the StudentClearanceManageFormPage
637        # The image is stored even if form has errors
638        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
639        self.browser.open(self.manage_clearance_path)
640        # No birth certificate has been uploaded yet
641        # Browsing the link shows a placerholder image
642        self.browser.open('birth_certificate')
643        self.assertEqual(
644            self.browser.headers['content-type'], 'image/jpeg')
645        self.assertEqual(len(self.browser.contents), PH_LEN)
646        # Create a pseudo image file and select it to be uploaded in form
647        # as birth certificate
648        self.browser.open(self.manage_clearance_path)
649        image = open(SAMPLE_IMAGE, 'rb')
650        ctrl = self.browser.getControl(name='birthcertificateupload')
651        file_ctrl = ctrl.mech_control
652        file_ctrl.add_file(image, filename='my_birth_certificate.jpg')
653        # The Save action does not upload files
654        self.browser.getControl("Save").click()  # submit form
655        self.assertFalse(
656            '<a target="image" href="birth_certificate">'
657            in self.browser.contents)
658        # ... but the correct upload submit button does
659        image = open(SAMPLE_IMAGE)
660        ctrl = self.browser.getControl(name='birthcertificateupload')
661        file_ctrl = ctrl.mech_control
662        file_ctrl.add_file(image, filename='my_birth_certificate.jpg')
663        self.browser.getControl(
664            name='upload_birthcertificateupload').click()
665        # There is a correct <img> link included
666        self.assertTrue(
667            'href="http://localhost/app/students/K1000000/birth_certificate"'
668            in self.browser.contents)
669        # Browsing the link shows a real image
670        self.browser.open('birth_certificate')
671        self.assertEqual(
672            self.browser.headers['content-type'], 'image/jpeg')
673        self.assertEqual(len(self.browser.contents), 2787)
674        # We can't reupload a file. The existing file must be deleted first.
675        self.browser.open(self.manage_clearance_path)
676        self.assertFalse(
677            'upload_birthcertificateupload' in self.browser.contents)
678        # File must be deleted first
679        self.browser.getControl(name='delete_birthcertificateupload').click()
680        self.assertTrue(
681            'birth_certificate deleted' in self.browser.contents)
682        # Uploading a file which is bigger than 250k will raise an error
683        big_image = StringIO(open(SAMPLE_IMAGE, 'rb').read() * 100)
684        ctrl = self.browser.getControl(name='birthcertificateupload')
685        file_ctrl = ctrl.mech_control
686        file_ctrl.add_file(big_image, filename='my_birth_certificate.jpg')
687        self.browser.getControl(
688            name='upload_birthcertificateupload').click()
689        self.assertTrue(
690            'Uploaded file is too big' in self.browser.contents)
691        # we do not rely on filename extensions given by uploaders
692        image = open(SAMPLE_IMAGE, 'rb')  # a jpg-file
693        ctrl = self.browser.getControl(name='birthcertificateupload')
694        file_ctrl = ctrl.mech_control
695        # tell uploaded file is bmp
696        file_ctrl.add_file(image, filename='my_birth_certificate.bmp')
697        self.browser.getControl(
698            name='upload_birthcertificateupload').click()
699        self.assertTrue(
700            # jpg file was recognized
701            'File birth_certificate.jpg uploaded.' in self.browser.contents)
702        # Delete file again
703        self.browser.getControl(name='delete_birthcertificateupload').click()
704        self.assertTrue(
705            'birth_certificate deleted' in self.browser.contents)
706        # File names must meet several conditions
707        bmp_image = open(SAMPLE_IMAGE_BMP, 'rb')
708        ctrl = self.browser.getControl(name='birthcertificateupload')
709        file_ctrl = ctrl.mech_control
710        file_ctrl.add_file(bmp_image, filename='my_birth_certificate.bmp')
711        self.browser.getControl(
712            name='upload_birthcertificateupload').click()
713        self.assertTrue(
714            'Only the following extensions are allowed'
715            in self.browser.contents)
716
717        # Managers can upload a file via the StudentBaseManageFormPage
718        self.browser.open(self.manage_student_path)
719        image = open(SAMPLE_IMAGE_BMP, 'rb')
720        ctrl = self.browser.getControl(name='passportuploadmanage')
721        file_ctrl = ctrl.mech_control
722        file_ctrl.add_file(image, filename='my_photo.bmp')
723        self.browser.getControl(
724            name='upload_passportuploadmanage').click()
725        self.assertTrue(
726            'jpg file format expected' in self.browser.contents)
727        ctrl = self.browser.getControl(name='passportuploadmanage')
728        file_ctrl = ctrl.mech_control
729        image = open(SAMPLE_IMAGE, 'rb')
730        file_ctrl.add_file(image, filename='my_photo.jpg')
731        self.browser.getControl(
732            name='upload_passportuploadmanage').click()
733        self.assertTrue(
734            'src="http://localhost/app/students/K1000000/passport.jpg"'
735            in self.browser.contents)
736        # We remove the passport file again
737        self.browser.open(self.manage_student_path)
738        self.browser.getControl('Delete').click()
739        self.browser.open(self.student_path + '/clearance_slip.pdf')
740        self.assertEqual(self.browser.headers['Status'], '200 Ok')
741        self.assertEqual(self.browser.headers['Content-Type'],
742                         'application/pdf')
743        # We want to see the signature fields.
744        IWorkflowState(self.student).setState('cleared')
745        self.browser.open(self.student_path + '/clearance_slip.pdf')
746        self.assertEqual(self.browser.headers['Status'], '200 Ok')
747        self.assertEqual(self.browser.headers['Content-Type'],
748                         'application/pdf')
749        path = os.path.join(samples_dir(), 'clearance_slip.pdf')
750        open(path, 'wb').write(self.browser.contents)
751        print "Sample PDF clearance_slip.pdf written to %s" % path
752
753    def test_manage_course_lists(self):
754        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
755        self.browser.open(self.student_path)
756        self.browser.getLink("Study Course").click()
757        self.assertEqual(self.browser.headers['Status'], '200 Ok')
758        self.assertEqual(self.browser.url, self.studycourse_path)
759        self.assertTrue('Undergraduate Full-Time' in self.browser.contents)
760        self.browser.getLink("Manage").click()
761        self.assertTrue('Manage study course' in self.browser.contents)
762        # Before we can select a level, the certificate must
763        # be selected and saved
764        self.browser.getControl(name="form.certificate").value = ['CERT1']
765        self.browser.getControl(name="form.current_session").value = ['2004']
766        self.browser.getControl(name="form.current_verdict").value = ['A']
767        self.browser.getControl(name="form.entry_mode").value = ['ug_ft']
768        self.browser.getControl("Save").click()
769        # Now we can save also the current level which depends on start and end
770        # level of the certificate
771        self.browser.getControl(name="form.current_level").value = ['100']
772        self.browser.getControl("Save").click()
773        # Managers can add and remove any study level (course list)
774        self.browser.getControl(name="addlevel").value = ['100']
775        self.browser.getControl("Add study level").click()
776        self.assertMatches(
777            '...You must select a session...', self.browser.contents)
778        self.browser.getControl(name="addlevel").value = ['100']
779        self.browser.getControl(name="level_session").value = ['2004']
780        self.browser.getControl("Add study level").click()
781        self.assertMatches('...<span>100</span>...', self.browser.contents)
782        self.assertEqual(self.student['studycourse']['100'].level, 100)
783        self.assertEqual(
784            self.student['studycourse']['100'].level_session, 2004)
785        self.browser.getControl(name="addlevel").value = ['100']
786        self.browser.getControl(name="level_session").value = ['2004']
787        self.browser.getControl("Add study level").click()
788        self.assertMatches('...This level exists...', self.browser.contents)
789        self.browser.getControl("Remove selected").click()
790        self.assertMatches(
791            '...No study level selected...', self.browser.contents)
792        self.browser.getControl(name="val_id").value = ['100']
793        self.browser.getControl(name="level_session").value = ['2004']
794        self.browser.getControl("Remove selected").click()
795        self.assertMatches('...Successfully removed...', self.browser.contents)
796        # Removing levels is properly logged
797        logfile = os.path.join(
798            self.app['datacenter'].storage, 'logs', 'students.log')
799        logcontent = open(logfile).read()
800        self.assertTrue(
801            'zope.mgr - students.browser.StudyCourseManageFormPage '
802            '- K1000000 - removed: 100' in logcontent)
803        # Add level again
804        self.browser.getControl(name="addlevel").value = ['100']
805        self.browser.getControl(name="level_session").value = ['2004']
806        self.browser.getControl("Add study level").click()
807
808        # Managers can view and manage course lists
809        self.browser.getLink("100").click()
810        self.assertMatches(
811            '...: 100 (Year 1)...', self.browser.contents)
812        self.browser.getLink("Manage").click()
813        self.browser.getControl(name="form.level_session").value = ['2002']
814        self.browser.getControl("Save").click()
815        self.browser.getControl("Remove selected").click()
816        self.assertMatches('...No ticket selected...', self.browser.contents)
817        ctrl = self.browser.getControl(name='val_id')
818        ctrl.getControl(value='COURSE1').selected = True
819        self.browser.getControl("Remove selected", index=0).click()
820        self.assertTrue('Successfully removed' in self.browser.contents)
821        # Removing course tickets is properly logged
822        logfile = os.path.join(
823            self.app['datacenter'].storage, 'logs', 'students.log')
824        logcontent = open(logfile).read()
825        self.assertTrue(
826            'zope.mgr - students.browser.StudyLevelManageFormPage '
827            '- K1000000 - level 100 - removed: COURSE1' in logcontent)
828        self.browser.getLink("here").click()
829        self.browser.getControl(name="form.course").value = ['COURSE1']
830        self.course.credits = 100
831        self.browser.getControl("Add course ticket").click()
832        self.assertMatches(
833            '...Maximum credits exceeded...', self.browser.contents)
834        self.course.credits = 10
835        self.browser.getControl("Add course ticket").click()
836        self.assertTrue('Successfully added' in self.browser.contents)
837        # We can do the same by adding the course on the manage page directly
838        del self.student['studycourse']['100']['COURSE1']
839        self.browser.getControl(name="course").value = 'COURSE1'
840        self.browser.getControl("Add course ticket").click()
841        self.assertTrue('Successfully added' in self.browser.contents)
842        self.browser.getLink("here").click()
843        self.browser.getControl(name="form.course").value = ['COURSE1']
844        self.browser.getControl("Add course ticket").click()
845        self.assertTrue('The ticket exists' in self.browser.contents)
846        self.browser.getControl("Cancel").click()
847        self.browser.getLink("COURSE1").click()
848        self.browser.getLink("Manage").click()
849        self.browser.getControl("Save").click()
850        self.assertTrue('Form has been saved' in self.browser.contents)
851        # Grade and weight have been determined
852        self.browser.open(self.studycourse_path + '/100/COURSE1')
853        self.assertFalse('Grade' in self.browser.contents)
854        self.assertFalse('Weight' in self.browser.contents)
855        self.student['studycourse']['100']['COURSE1'].score = 55
856        self.browser.open(self.studycourse_path + '/100/COURSE1')
857        self.assertTrue('Grade' in self.browser.contents)
858        self.assertTrue('Weight' in self.browser.contents)
859        self.assertEqual(
860            self.student['studycourse']['100']['COURSE1'].grade, 'C')
861        self.assertEqual(
862            self.student['studycourse']['100']['COURSE1'].weight, 3)
863        # We add another ticket to check if GPA will be correctly
864        # calculated (and rounded)
865        courseticket = createObject('waeup.CourseTicket')
866        courseticket.code = 'ANYCODE'
867        courseticket.title = u'Any TITLE'
868        courseticket.credits = 13
869        courseticket.score = 66
870        courseticket.semester = 1
871        courseticket.dcode = u'ANYDCODE'
872        courseticket.fcode = u'ANYFCODE'
873        self.student['studycourse']['100']['COURSE2'] = courseticket
874        self.browser.open(self.student_path + '/studycourse/100')
875        # total credits
876        self.assertEqual(
877            self.student['studycourse']['100'].gpa_params_rectified[1], 23)
878        # weigheted credits = 3 * 10 + 4 * 13
879        self.assertEqual(
880            self.student['studycourse']['100'].gpa_params_rectified[2], 82.0)
881        # sgpa = 82 / 23
882        self.assertEqual(
883            self.student['studycourse']['100'].gpa_params_rectified[0],
884            3.5652173913043477)
885        # Carry-over courses will be collected when next level is created
886        self.browser.open(self.student_path + '/studycourse/manage')
887        # Add next level
888        self.student['studycourse']['100']['COURSE1'].score = 10
889        self.browser.getControl(name="addlevel").value = ['200']
890        self.browser.getControl(name="level_session").value = ['2005']
891        self.browser.getControl("Add study level").click()
892        self.browser.getLink("200").click()
893        self.assertMatches(
894            '...: 200 (Year 2)...', self.browser.contents)
895        # Since COURSE1 has score 10 it becomes a carry-over course
896        # in level 200
897        self.assertEqual(
898            sorted(self.student['studycourse']['200'].keys()), [u'COURSE1'])
899        self.assertTrue(
900            self.student['studycourse']['200']['COURSE1'].carry_over)
901        # Passed and failed courses have been counted
902        self.assertEqual(
903            self.student['studycourse']['100'].passed_params,
904            (1, 1, 13, 10, 'COURSE1 ', ''))
905        self.assertEqual(
906            self.student['studycourse']['200'].passed_params,
907            (0, 0, 0, 0, '', 'COURSE1 '))
908        # And also cumulative params can be calculated. Meanwhile we have the
909        # following courses: COURSE1 and COURSE2 in level 100 and
910        # COURSE1 as carry-over course in level 200.
911        self.assertEqual(
912            self.student['studycourse']['100'].cumulative_params,
913            (2.260869565217391, 23, 52.0, 23, 13))
914        # COURSE1 in level 200 is not taken into consideration
915        # when calculating the gpa.
916        self.assertEqual(
917            self.student['studycourse']['200'].cumulative_params,
918            (2.260869565217391, 23, 52.0, 33, 13))
919        return
920
921    def test_gpa_calculation_with_carryover(self):
922        studylevel = createObject(u'waeup.StudentStudyLevel')
923        studylevel.level = 100
924        studylevel.level_session = 2005
925        self.student['studycourse'].entry_mode = 'ug_ft'
926        self.student['studycourse'].addStudentStudyLevel(
927            self.certificate, studylevel)
928        # First course has been added automatically.
929        # Set score above passmark.
930        studylevel['COURSE1'].score = studylevel['COURSE1'].passmark + 1
931        # GPA is 1.
932        self.assertEqual(
933            self.student['studycourse']['100'].gpa_params_rectified[0], 1.0)
934        # Set score below passmark.
935        studylevel['COURSE1'].score = studylevel['COURSE1'].passmark - 1
936        # GPA is still 0.
937        self.assertEqual(
938            self.student['studycourse']['100'].gpa_params_rectified[0], 0.0)
939        studylevel2 = createObject(u'waeup.StudentStudyLevel')
940        studylevel2.level = 200
941        studylevel2.level_session = 2006
942        self.student['studycourse'].addStudentStudyLevel(
943            self.certificate, studylevel2)
944        # Carry-over course has been autonatically added.
945        studylevel2['COURSE1'].score = 66
946        # The score of the carry-over course is now used for calculation of the
947        # GPA at level 100 ...
948        self.assertEqual(
949            self.student['studycourse']['100'].gpa_params_rectified[0], 4.0)
950        # ... but not at level 200
951        self.assertEqual(
952            self.student['studycourse']['200'].gpa_params_rectified[0], 0.0)
953        return
954
955    def test_manage_payments(self):
956        # Managers can add online school fee payment tickets
957        # if certain requirements are met
958        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
959        self.browser.open(self.payments_path)
960        IWorkflowState(self.student).setState('cleared')
961        self.browser.getLink("Add current session payment ticket").click()
962        self.browser.getControl(name="form.p_category").value = ['schoolfee']
963        self.browser.getControl("Create ticket").click()
964        self.assertMatches('...ticket created...',
965                           self.browser.contents)
966        ctrl = self.browser.getControl(name='val_id')
967        value = ctrl.options[0]
968        self.browser.getLink(value).click()
969        self.assertMatches('...Amount Authorized...',
970                           self.browser.contents)
971        self.assertEqual(self.student['payments'][value].amount_auth, 40000.0)
972        payment_url = self.browser.url
973        logfile = os.path.join(
974            self.app['datacenter'].storage, 'logs', 'students.log')
975        logcontent = open(logfile).read()
976        self.assertTrue(
977            ' zope.mgr - students.browser.OnlinePaymentAddFormPage - '
978            'K1000000 - added: %s' % value
979            in logcontent)
980        # The pdf payment slip can't yet be opened
981        #self.browser.open(payment_url + '/payment_slip.pdf')
982        #self.assertMatches('...Ticket not yet paid...',
983        #                   self.browser.contents)
984
985        # The same payment (with same p_item, p_session and
986        # p_category) can be initialized a second time if the former
987        # ticket is not yet paid.
988        self.browser.open(self.payments_path)
989        self.browser.getLink("Add current session payment ticket").click()
990        self.browser.getControl(name="form.p_category").value = ['schoolfee']
991        self.browser.getControl("Create ticket").click()
992        self.assertMatches('...Payment ticket created...',
993                           self.browser.contents)
994
995        # The ticket can be found in the payments_catalog
996        cat = queryUtility(ICatalog, name='payments_catalog')
997        results = list(cat.searchResults(p_state=('unpaid', 'unpaid')))
998        self.assertEqual(len(results), 2)
999        self.assertTrue(results[0] is self.student['payments'][value])
1000        # Managers can approve the payment
1001        # If, by some reason, the state has already changed,
1002        # an access code is created after approval.
1003        IWorkflowState(self.student).setState('school fee paid')
1004        self.assertEqual(len(self.app['accesscodes']['SFE-0']), 0)
1005        self.browser.open(payment_url)
1006        self.browser.getLink("Approve payment").click()
1007        self.assertMatches(
1008            '...Payment approved...', self.browser.contents)
1009        # Approval is logged in students.log ...
1010        logcontent = open(logfile).read()
1011        self.assertTrue(
1012            'zope.mgr - students.browser.OnlinePaymentApproveView '
1013            '- K1000000 - schoolfee payment approved'
1014            in logcontent)
1015        # ... and in payments.log
1016        logfile = os.path.join(
1017            self.app['datacenter'].storage, 'logs', 'payments.log')
1018        logcontent = open(logfile).read()
1019        self.assertTrue(
1020            '"zope.mgr",K1000000,%s,schoolfee,40000.0,AP,,,,,,\n' % value
1021            in logcontent)
1022        # The authorized amount has been stored in the new access code
1023        self.assertEqual(
1024            self.app['accesscodes']['SFE-0'].values()[0].cost, 40000.0)
1025
1026        # The catalog has been updated
1027        results = list(cat.searchResults(p_state=('unpaid', 'unpaid')))
1028        self.assertTrue(len(results), 0)
1029        results = list(cat.searchResults(p_state=('paid', 'paid')))
1030        self.assertTrue(len(results), 1)
1031        self.assertTrue(results[0] is self.student['payments'][value])
1032
1033        # Payments can't be approved twice
1034        self.browser.open(payment_url + '/approve')
1035        self.assertMatches('...This ticket has already been paid...',
1036                          self.browser.contents)
1037
1038        # Now the first ticket is paid and no more ticket of same type
1039        # (with same p_item, p_session and p_category) can be added.
1040        # First we have to reset the workflow state.
1041        IWorkflowState(self.student).setState('cleared')
1042        self.browser.open(self.payments_path)
1043        self.browser.getLink("Add current session payment ticket").click()
1044        self.browser.getControl(name="form.p_category").value = ['schoolfee']
1045        self.browser.getControl("Create ticket").click()
1046        self.assertMatches(
1047            '...This type of payment has already been made...',
1048            self.browser.contents)
1049
1050        # Managers can open the pdf payment slip
1051        self.browser.open(payment_url)
1052        self.browser.getLink("Download payment slip").click()
1053        self.assertEqual(self.browser.headers['Status'], '200 Ok')
1054        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
1055
1056        # Managers can remove online school fee payment tickets
1057        self.browser.open(self.payments_path)
1058        self.browser.getControl("Remove selected").click()
1059        self.assertMatches('...No payment selected...', self.browser.contents)
1060        ctrl = self.browser.getControl(name='val_id')
1061        value = ctrl.options[0]
1062        ctrl.getControl(value=value).selected = True
1063        self.browser.getControl("Remove selected", index=0).click()
1064        self.assertTrue('Successfully removed' in self.browser.contents)
1065
1066        # Managers can add online clearance payment tickets
1067        self.browser.open(self.payments_path + '/addop')
1068        self.browser.getControl(name="form.p_category").value = ['clearance']
1069        self.browser.getControl("Create ticket").click()
1070        self.assertMatches('...ticket created...',
1071                           self.browser.contents)
1072
1073        # Managers can approve the payment
1074        self.assertEqual(len(self.app['accesscodes']['CLR-0']),0)
1075        ctrl = self.browser.getControl(name='val_id')
1076        value = ctrl.options[1] # The clearance payment is the second in the table
1077        self.browser.getLink(value).click()
1078        self.browser.open(self.browser.url + '/approve')
1079        self.assertMatches('...Payment approved...',
1080                          self.browser.contents)
1081        expected = '''...
1082        <td>
1083          <span>Paid</span>
1084        </td>...'''
1085        self.assertMatches(expected,self.browser.contents)
1086        # The new CLR-0 pin has been created
1087        self.assertEqual(len(self.app['accesscodes']['CLR-0']),1)
1088        pin = self.app['accesscodes']['CLR-0'].keys()[0]
1089        ac = self.app['accesscodes']['CLR-0'][pin]
1090        self.assertEqual(ac.owner, self.student_id)
1091        self.assertEqual(ac.cost, 3456.0)
1092
1093        # Managers can add online transcript payment tickets
1094        self.browser.open(self.payments_path + '/addop')
1095        self.browser.getControl(name="form.p_category").value = ['transcript']
1096        self.browser.getControl("Create ticket").click()
1097        self.assertMatches('...ticket created...',
1098                           self.browser.contents)
1099
1100        # Managers can approve the payment
1101        self.assertEqual(len(self.app['accesscodes']['TSC-0']),0)
1102        ctrl = self.browser.getControl(name='val_id')
1103        value = ctrl.options[2] # The clearance payment is the third in the table
1104        self.browser.getLink(value).click()
1105        self.browser.open(self.browser.url + '/approve')
1106        self.assertMatches('...Payment approved...',
1107                          self.browser.contents)
1108        expected = '''...
1109        <td>
1110          <span>Paid</span>
1111        </td>...'''
1112        self.assertMatches(expected,self.browser.contents)
1113        # The new CLR-0 pin has been created
1114        self.assertEqual(len(self.app['accesscodes']['TSC-0']),1)
1115        pin = self.app['accesscodes']['TSC-0'].keys()[0]
1116        ac = self.app['accesscodes']['TSC-0'][pin]
1117        self.assertEqual(ac.owner, self.student_id)
1118        self.assertEqual(ac.cost, 4567.0)
1119        return
1120
1121    def test_add_transfer_payment(self):
1122        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1123        self.browser.open(self.payments_path)
1124        self.browser.getLink("Add current session payment ticket").click()
1125        self.browser.getControl(name="form.p_category").value = ['transfer']
1126        self.browser.getControl(name="new_programme").value = 'my new study course'
1127        self.browser.getControl("Create ticket").click()
1128        self.assertMatches('...ticket created...',
1129                           self.browser.contents)
1130        ctrl = self.browser.getControl(name='val_id')
1131        value = ctrl.options[0]
1132        self.browser.getLink(value).click()
1133        self.assertMatches('...my new study course...',
1134                           self.browser.contents)
1135        self.assertEqual(self.student['payments'][value].p_item, u'my new study course')
1136
1137    def test_manage_payments_bypass_ac_creation(self):
1138        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1139        self.browser.open(self.payments_path)
1140        IWorkflowState(self.student).setState('cleared')
1141        self.browser.getLink("Add current session payment ticket").click()
1142        self.browser.getControl(name="form.p_category").value = ['schoolfee']
1143        self.browser.getControl("Create ticket").click()
1144        ctrl = self.browser.getControl(name='val_id')
1145        value = ctrl.options[0]
1146        self.browser.getLink(value).click()
1147        payment_url = self.browser.url
1148        logfile = os.path.join(
1149            self.app['datacenter'].storage, 'logs', 'students.log')
1150        # The ticket can be found in the payments_catalog
1151        cat = queryUtility(ICatalog, name='payments_catalog')
1152        results = list(cat.searchResults(p_state=('unpaid', 'unpaid')))
1153        self.assertTrue(len(results), 1)
1154        self.assertTrue(results[0] is self.student['payments'][value])
1155        # Managers can approve the payment
1156        self.browser.open(payment_url)
1157        self.browser.getLink("Approve payment").click()
1158        self.assertMatches('...Payment approved...',
1159                          self.browser.contents)
1160        # Approval is logged in students.log ...
1161        logcontent = open(logfile).read()
1162        self.assertTrue(
1163            'zope.mgr - students.browser.OnlinePaymentApproveView '
1164            '- K1000000 - schoolfee payment approved'
1165            in logcontent)
1166        # ... and in payments.log
1167        logfile = os.path.join(
1168            self.app['datacenter'].storage, 'logs', 'payments.log')
1169        logcontent = open(logfile).read()
1170        self.assertTrue(
1171            '"zope.mgr",K1000000,%s,schoolfee,40000.0,AP,,,,,,\n' % value
1172            in logcontent)
1173        # Student is in state school fee paid, no activation
1174        # code was necessary.
1175        self.assertEqual(self.student.state, 'school fee paid')
1176        self.assertEqual(len(self.app['accesscodes']['SFE-0']),0)
1177        return
1178
1179    def test_payment_disabled(self):
1180        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1181        self.browser.open(self.payments_path)
1182        IWorkflowState(self.student).setState('cleared')
1183        self.browser.getLink("Add current session payment ticket").click()
1184        self.browser.getControl(name="form.p_category").value = ['schoolfee']
1185        self.browser.getControl("Create ticket").click()
1186        self.assertMatches('...ticket created...',
1187                           self.browser.contents)
1188        self.app['configuration']['2004'].payment_disabled = ['sf_all']
1189        self.browser.getLink("Add current session payment ticket").click()
1190        self.browser.getControl(name="form.p_category").value = ['schoolfee']
1191        self.browser.getControl("Create ticket").click()
1192        self.assertMatches('...This category of payments has been disabled...',
1193                           self.browser.contents)
1194        return
1195
1196    def test_manage_balance_payments(self):
1197
1198        # Login
1199        #self.browser.open(self.login_path)
1200        #self.browser.getControl(name="form.login").value = self.student_id
1201        #self.browser.getControl(name="form.password").value = 'spwd'
1202        #self.browser.getControl("Login").click()
1203
1204        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1205        self.browser.open(self.payments_path)
1206
1207        # Managers can add balance school fee payment tickets in any state.
1208        IWorkflowState(self.student).setState('courses registered')
1209        self.browser.open(self.payments_path)
1210        self.browser.getLink("Add balance payment ticket").click()
1211
1212        # Balance payment form is provided
1213        self.assertEqual(self.student.current_session, 2004)
1214        self.browser.getControl(name="form.p_category").value = ['schoolfee']
1215        self.browser.getControl(name="form.balance_session").value = ['2004']
1216        self.browser.getControl(name="form.balance_level").value = ['300']
1217        self.browser.getControl(name="form.balance_amount").value = '-567.8'
1218        self.browser.getControl("Create ticket").click()
1219        self.assertMatches('...Amount must be greater than 0...',
1220                           self.browser.contents)
1221        self.browser.getControl(name="form.balance_amount").value = '0'
1222        self.browser.getControl("Create ticket").click()
1223        self.assertMatches('...Amount must be greater than 0...',
1224                           self.browser.contents)
1225        self.browser.getControl(name="form.balance_amount").value = '567.8'
1226        self.browser.getControl("Create ticket").click()
1227        self.assertMatches('...ticket created...',
1228                           self.browser.contents)
1229        ctrl = self.browser.getControl(name='val_id')
1230        value = ctrl.options[0]
1231        self.browser.getLink(value).click()
1232        self.assertMatches('...Amount Authorized...',
1233                           self.browser.contents)
1234        self.assertEqual(self.student['payments'][value].amount_auth, 567.8)
1235        # Payment attributes are properly set
1236        self.assertEqual(self.student['payments'][value].p_session, 2004)
1237        self.assertEqual(self.student['payments'][value].p_level, 300)
1238        self.assertEqual(self.student['payments'][value].p_item, u'Balance')
1239        self.assertEqual(self.student['payments'][value].p_category, 'schoolfee')
1240        # Adding payment tickets is logged.
1241        logfile = os.path.join(
1242            self.app['datacenter'].storage, 'logs', 'students.log')
1243        logcontent = open(logfile).read()
1244        self.assertTrue('zope.mgr - students.browser.BalancePaymentAddFormPage '
1245                        '- K1000000 - added: %s' % value in logcontent)
1246
1247    def test_manage_accommodation(self):
1248        logfile = os.path.join(
1249            self.app['datacenter'].storage, 'logs', 'students.log')
1250        # Managers can add online booking fee payment tickets and open the
1251        # callback view (see test_manage_payments)
1252        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1253        self.browser.open(self.payments_path)
1254        self.browser.getLink("Add current session payment ticket").click()
1255        self.browser.getControl(name="form.p_category").value = ['bed_allocation']
1256        # If student is not in accommodation session, payment cannot be processed
1257        self.app['hostels'].accommodation_session = 2011
1258        self.browser.getControl("Create ticket").click()
1259        self.assertMatches('...Your current session does not match...',
1260                           self.browser.contents)
1261        self.app['hostels'].accommodation_session = 2004
1262        self.browser.getControl(name="form.p_category").value = ['bed_allocation']
1263        self.browser.getControl("Create ticket").click()
1264        ctrl = self.browser.getControl(name='val_id')
1265        value = ctrl.options[0]
1266        self.browser.getLink(value).click()
1267        self.browser.open(self.browser.url + '/approve')
1268        # The new HOS-0 pin has been created
1269        self.assertEqual(len(self.app['accesscodes']['HOS-0']),1)
1270        pin = self.app['accesscodes']['HOS-0'].keys()[0]
1271        ac = self.app['accesscodes']['HOS-0'][pin]
1272        self.assertEqual(ac.owner, self.student_id)
1273        parts = pin.split('-')[1:]
1274        sfeseries, sfenumber = parts
1275        # Managers can use HOS code and book a bed space with it
1276        self.browser.open(self.acco_path)
1277        self.browser.getControl("Book accommodation").click()
1278        self.assertMatches('...You are in the wrong...',
1279                           self.browser.contents)
1280        IWorkflowInfo(self.student).fireTransition('admit')
1281        # An existing HOS code can only be used if students
1282        # are in accommodation session
1283        self.student['studycourse'].current_session = 2003
1284        self.browser.getControl("Book accommodation").click()
1285        self.assertMatches('...Your current session does not match...',
1286                           self.browser.contents)
1287        self.student['studycourse'].current_session = 2004
1288        # All requirements are met and ticket can be created
1289        self.browser.getControl("Book accommodation").click()
1290        self.assertMatches('...Activation Code:...',
1291                           self.browser.contents)
1292        self.browser.getControl(name="ac_series").value = sfeseries
1293        self.browser.getControl(name="ac_number").value = sfenumber
1294        self.browser.getControl("Create bed ticket").click()
1295        self.assertMatches('...Hall 1, Block A, Room 101, Bed A...',
1296                           self.browser.contents)
1297        # Bed has been allocated
1298        bed1 = self.app['hostels']['hall-1']['hall-1_A_101_A']
1299        self.assertTrue(bed1.owner == self.student_id)
1300        # BedTicketAddPage is now blocked
1301        self.browser.getControl("Book accommodation").click()
1302        self.assertMatches('...You already booked a bed space...',
1303            self.browser.contents)
1304        # The bed ticket displays the data correctly
1305        self.browser.open(self.acco_path + '/2004')
1306        self.assertMatches('...Hall 1, Block A, Room 101, Bed A...',
1307                           self.browser.contents)
1308        self.assertMatches('...2004/2005...', self.browser.contents)
1309        self.assertMatches('...regular_male_fr...', self.browser.contents)
1310        self.assertMatches('...%s...' % pin, self.browser.contents)
1311        # Booking is properly logged
1312        logcontent = open(logfile).read()
1313        self.assertTrue('zope.mgr - students.browser.BedTicketAddPage '
1314            '- K1000000 - booked: hall-1_A_101_A' in logcontent)
1315        # Managers can relocate students if the student's bed_type has changed
1316        self.browser.getLink("Relocate student").click()
1317        self.assertMatches(
1318            "...Student can't be relocated...", self.browser.contents)
1319        self.student.sex = u'f'
1320        self.browser.getLink("Relocate student").click()
1321        self.assertMatches(
1322            "...Hall 1, Block A, Room 101, Bed B...", self.browser.contents)
1323        self.assertTrue(bed1.owner == NOT_OCCUPIED)
1324        bed2 = self.app['hostels']['hall-1']['hall-1_A_101_B']
1325        self.assertTrue(bed2.owner == self.student_id)
1326        self.assertTrue(self.student['accommodation'][
1327            '2004'].bed_type == u'regular_female_fr')
1328        # Relocation is properly logged
1329        logcontent = open(logfile).read()
1330        self.assertTrue('zope.mgr - students.accommodation.BedTicket '
1331            '- K1000000 - relocated: hall-1_A_101_B' in logcontent)
1332        # The payment object still shows the original payment item
1333        payment_id = self.student['payments'].keys()[0]
1334        payment = self.student['payments'][payment_id]
1335        self.assertTrue(payment.p_item == u'regular_male_fr')
1336        # Managers can relocate students if the bed's bed_type has changed
1337        bed1.bed_type = u'regular_female_fr'
1338        bed2.bed_type = u'regular_male_fr'
1339        notify(grok.ObjectModifiedEvent(bed1))
1340        notify(grok.ObjectModifiedEvent(bed2))
1341        self.browser.getLink("Relocate student").click()
1342        self.assertMatches(
1343            "...Student relocated...", self.browser.contents)
1344        self.assertMatches(
1345            "... Hall 1, Block A, Room 101, Bed A...", self.browser.contents)
1346        self.assertMatches(bed1.owner, self.student_id)
1347        self.assertMatches(bed2.owner, NOT_OCCUPIED)
1348        # Managers can't relocate students if bed is reserved
1349        self.student.sex = u'm'
1350        bed1.bed_type = u'regular_female_reserved'
1351        notify(grok.ObjectModifiedEvent(bed1))
1352        self.browser.getLink("Relocate student").click()
1353        self.assertMatches(
1354            "...Students in reserved beds can't be relocated...",
1355            self.browser.contents)
1356        # Managers can relocate students if booking has been cancelled but
1357        # other bed space has been manually allocated after cancellation
1358        old_owner = bed1.releaseBed()
1359        self.assertMatches(old_owner, self.student_id)
1360        bed2.owner = self.student_id
1361        self.browser.open(self.acco_path + '/2004')
1362        self.assertMatches(
1363            "...booking cancelled...", self.browser.contents)
1364        self.browser.getLink("Relocate student").click()
1365        # We didn't informed the catalog therefore the new owner is not found
1366        self.assertMatches(
1367            "...There is no free bed in your category regular_male_fr...",
1368            self.browser.contents)
1369        # Now we fire the event properly
1370        notify(grok.ObjectModifiedEvent(bed2))
1371        self.browser.getLink("Relocate student").click()
1372        self.assertMatches(
1373            "...Student relocated...", self.browser.contents)
1374        self.assertMatches(
1375            "... Hall 1, Block A, Room 101, Bed B...", self.browser.contents)
1376          # Managers can delete bed tickets
1377        self.browser.open(self.acco_path)
1378        ctrl = self.browser.getControl(name='val_id')
1379        value = ctrl.options[0]
1380        ctrl.getControl(value=value).selected = True
1381        self.browser.getControl("Remove selected", index=0).click()
1382        self.assertMatches('...Successfully removed...', self.browser.contents)
1383        # The bed has been properly released by the event handler
1384        self.assertMatches(bed1.owner, NOT_OCCUPIED)
1385        self.assertMatches(bed2.owner, NOT_OCCUPIED)
1386        return
1387
1388    def test_manage_workflow(self):
1389        # Managers can pass through the whole workflow
1390        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1391        student = self.app['students'][self.student_id]
1392        self.browser.open(self.trigtrans_path)
1393        self.assertTrue(student.clearance_locked)
1394        self.browser.getControl(name="transition").value = ['admit']
1395        self.browser.getControl("Save").click()
1396        self.assertTrue(student.clearance_locked)
1397        self.browser.getControl(name="transition").value = ['start_clearance']
1398        self.browser.getControl("Save").click()
1399        self.assertFalse(student.clearance_locked)
1400        self.browser.getControl(name="transition").value = ['request_clearance']
1401        self.browser.getControl("Save").click()
1402        self.assertTrue(student.clearance_locked)
1403        self.browser.getControl(name="transition").value = ['clear']
1404        self.browser.getControl("Save").click()
1405        # Managers approve payment, they do not pay
1406        self.assertFalse('pay_first_school_fee' in self.browser.contents)
1407        self.browser.getControl(
1408            name="transition").value = ['approve_first_school_fee']
1409        self.browser.getControl("Save").click()
1410        self.browser.getControl(name="transition").value = ['reset6']
1411        self.browser.getControl("Save").click()
1412        # In state returning the pay_school_fee transition triggers some
1413        # changes of attributes
1414        self.browser.getControl(name="transition").value = ['approve_school_fee']
1415        self.browser.getControl("Save").click()
1416        self.assertEqual(student['studycourse'].current_session, 2005) # +1
1417        self.assertEqual(student['studycourse'].current_level, 200) # +100
1418        self.assertEqual(student['studycourse'].current_verdict, '0') # 0 = Zero = not set
1419        self.assertEqual(student['studycourse'].previous_verdict, 'A')
1420        self.browser.getControl(name="transition").value = ['register_courses']
1421        self.browser.getControl("Save").click()
1422        self.browser.getControl(name="transition").value = ['validate_courses']
1423        self.browser.getControl("Save").click()
1424        self.browser.getControl(name="transition").value = ['return']
1425        self.browser.getControl("Save").click()
1426        return
1427
1428    def test_manage_pg_workflow(self):
1429        # Managers can pass through the whole workflow
1430        IWorkflowState(self.student).setState('school fee paid')
1431        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1432        self.browser.open(self.trigtrans_path)
1433        self.assertTrue('<option value="reset6">' in self.browser.contents)
1434        self.assertTrue('<option value="register_courses">' in self.browser.contents)
1435        self.assertTrue('<option value="reset5">' in self.browser.contents)
1436        self.certificate.study_mode = 'pg_ft'
1437        self.browser.open(self.trigtrans_path)
1438        self.assertFalse('<option value="reset6">' in self.browser.contents)
1439        self.assertFalse('<option value="register_courses">' in self.browser.contents)
1440        self.assertTrue('<option value="reset5">' in self.browser.contents)
1441        return
1442
1443    def test_manage_import(self):
1444        # Managers can import student data files
1445        datacenter_path = 'http://localhost/app/datacenter'
1446        # Prepare a csv file for students
1447        open('students.csv', 'wb').write(
1448"""firstname,lastname,reg_number,date_of_birth,matric_number,email,phone,sex,password
1449Aaren,Pieri,1,1990-01-02,100000,aa@aa.ng,1234,m,mypwd1
1450Claus,Finau,2,1990-01-03,100001,aa@aa.ng,1234,m,mypwd1
1451Brit,Berson,3,1990-01-04,100001,aa@aa.ng,1234,m,mypwd1
1452""")
1453        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1454        self.browser.open(datacenter_path)
1455        self.browser.getLink('Upload data').click()
1456        filecontents = StringIO(open('students.csv', 'rb').read())
1457        filewidget = self.browser.getControl(name='uploadfile:file')
1458        filewidget.add_file(filecontents, 'text/plain', 'students.csv')
1459        self.browser.getControl(name='SUBMIT').click()
1460        self.browser.getLink('Process data').click()
1461        self.browser.getLink("Switch maintenance mode").click()
1462        button = lookup_submit_value(
1463            'select', 'students_zope.mgr.csv', self.browser)
1464        button.click()
1465        importerselect = self.browser.getControl(name='importer')
1466        modeselect = self.browser.getControl(name='mode')
1467        importerselect.getControl('Student Processor').selected = True
1468        modeselect.getControl(value='create').selected = True
1469        self.browser.getControl('Proceed to step 3').click()
1470        self.assertTrue('Header fields OK' in self.browser.contents)
1471        self.browser.getControl('Perform import').click()
1472        self.assertTrue('Processing of 1 rows failed' in self.browser.contents)
1473        self.assertTrue('Successfully processed 2 rows' in self.browser.contents)
1474        self.assertTrue('Batch processing finished' in self.browser.contents)
1475        open('studycourses.csv', 'wb').write(
1476"""reg_number,matric_number,certificate,current_session,current_level
14771,,CERT1,2008,100
1478,100001,CERT1,2008,100
1479,100002,CERT1,2008,100
1480""")
1481        self.browser.open(datacenter_path)
1482        self.browser.getLink('Upload data').click()
1483        filecontents = StringIO(open('studycourses.csv', 'rb').read())
1484        filewidget = self.browser.getControl(name='uploadfile:file')
1485        filewidget.add_file(filecontents, 'text/plain', 'studycourses.csv')
1486        self.browser.getControl(name='SUBMIT').click()
1487        self.browser.getLink('Process data').click()
1488        # Meanwhile maintenance mode is disabled again.
1489        self.browser.getLink("Switch maintenance mode").click()
1490        button = lookup_submit_value(
1491            'select', 'studycourses_zope.mgr.csv', self.browser)
1492        button.click()
1493        importerselect = self.browser.getControl(name='importer')
1494        modeselect = self.browser.getControl(name='mode')
1495        importerselect.getControl(
1496            'StudentStudyCourse Processor (update only)').selected = True
1497        modeselect.getControl(value='create').selected = True
1498        self.browser.getControl('Proceed to step 3').click()
1499        self.assertTrue('Update mode only' in self.browser.contents)
1500        self.browser.getControl('Proceed to step 3').click()
1501        self.assertTrue('Header fields OK' in self.browser.contents)
1502        self.browser.getControl('Perform import').click()
1503        self.assertTrue('Processing of 1 rows failed' in self.browser.contents)
1504        self.assertTrue('Successfully processed 2 rows'
1505                        in self.browser.contents)
1506        # The students are properly indexed and we can
1507        # thus find a student in  the department
1508        self.browser.open(self.manage_container_path)
1509        self.browser.getControl(name="searchtype").value = ['depcode']
1510        self.browser.getControl(name="searchterm").value = 'dep1'
1511        self.browser.getControl("Find student(s)").click()
1512        self.assertTrue('Aaren Pieri' in self.browser.contents)
1513        # We can search for a new student by name ...
1514        self.browser.getControl(name="searchtype").value = ['fullname']
1515        self.browser.getControl(name="searchterm").value = 'Claus'
1516        self.browser.getControl("Find student(s)").click()
1517        self.assertTrue('Claus Finau' in self.browser.contents)
1518        # ... and check if the imported password has been properly set
1519        ctrl = self.browser.getControl(name='entries')
1520        value = ctrl.options[0]
1521        claus = self.app['students'][value]
1522        self.assertTrue(IUserAccount(claus).checkPassword('mypwd1'))
1523        return
1524
1525    def init_clearance_officer(self):
1526        # Create clearance officer
1527        self.app['users'].addUser('mrclear', SECRET)
1528        self.app['users']['mrclear'].email = 'mrclear@foo.ng'
1529        self.app['users']['mrclear'].title = 'Carlo Pitter'
1530        # Clearance officers need not necessarily to get
1531        # the StudentsOfficer site role
1532        #prmglobal = IPrincipalRoleManager(self.app)
1533        #prmglobal.assignRoleToPrincipal('waeup.StudentsOfficer', 'mrclear')
1534        # Assign local ClearanceOfficer role
1535        self.department = self.app['faculties']['fac1']['dep1']
1536        prmlocal = IPrincipalRoleManager(self.department)
1537        prmlocal.assignRoleToPrincipal('waeup.local.ClearanceOfficer', 'mrclear')
1538        IWorkflowState(self.student).setState('clearance started')
1539        # Add another student for testing
1540        other_student = Student()
1541        other_student.firstname = u'Dep2'
1542        other_student.lastname = u'Student'
1543        self.app['students'].addStudent(other_student)
1544        self.other_student_path = (
1545            'http://localhost/app/students/%s' % other_student.student_id)
1546        # Login as clearance officer
1547        self.browser.open(self.login_path)
1548        self.browser.getControl(name="form.login").value = 'mrclear'
1549        self.browser.getControl(name="form.password").value = SECRET
1550        self.browser.getControl("Login").click()
1551
1552    def test_handle_clearance_by_co(self):
1553        self.init_clearance_officer()
1554        self.assertMatches('...You logged in...', self.browser.contents)
1555        # CO is landing on index page.
1556        self.assertEqual(self.browser.url, 'http://localhost/app/index')
1557        # CO can see his roles
1558        self.browser.getLink("My Roles").click()
1559        self.assertMatches(
1560            '...<div>Academics Officer (view only)</div>...',
1561            self.browser.contents)
1562        # But not his local role ...
1563        self.assertFalse('Clearance Officer' in self.browser.contents)
1564        # ... because we forgot to notify the department that the local role
1565        # has changed.
1566        notify(LocalRoleSetEvent(
1567            self.department, 'waeup.local.ClearanceOfficer', 'mrclear',
1568            granted=True))
1569        self.browser.open('http://localhost/app/users/mrclear/my_roles')
1570        self.assertTrue('Clearance Officer' in self.browser.contents)
1571        self.assertMatches(
1572            '...<a href="http://localhost/app/faculties/fac1/dep1">...',
1573            self.browser.contents)
1574        # CO can view the student ...
1575        self.browser.open(self.clearance_path)
1576        self.assertEqual(self.browser.headers['Status'], '200 Ok')
1577        self.assertEqual(self.browser.url, self.clearance_path)
1578        # ... but not other students.
1579        self.assertRaises(
1580            Unauthorized, self.browser.open, self.other_student_path)
1581        # Clearance is disabled for this session.
1582        self.browser.open(self.clearance_path)
1583        self.assertFalse('Clear student' in self.browser.contents)
1584        self.browser.open(self.student_path + '/clear')
1585        self.assertTrue('Clearance is disabled for this session'
1586            in self.browser.contents)
1587        self.app['configuration']['2004'].clearance_enabled = True
1588        # Only in state clearance requested the CO does see the 'Clear' button.
1589        self.browser.open(self.clearance_path)
1590        self.assertFalse('Clear student' in self.browser.contents)
1591        self.browser.open(self.student_path + '/clear')
1592        self.assertTrue('Student is in wrong state.'
1593            in self.browser.contents)
1594        IWorkflowInfo(self.student).fireTransition('request_clearance')
1595        self.browser.open(self.clearance_path)
1596        self.assertTrue('Clear student' in self.browser.contents)
1597        self.browser.getLink("Clear student").click()
1598        self.assertTrue('Student has been cleared' in self.browser.contents)
1599        self.assertTrue('cleared' in self.browser.contents)
1600        self.browser.open(self.history_path)
1601        self.assertTrue('Cleared by Carlo Pitter' in self.browser.contents)
1602        # Hide real name.
1603        self.app['users']['mrclear'].public_name = 'My Public Name'
1604        self.browser.open(self.clearance_path)
1605        self.browser.getLink("Reject clearance").click()
1606        self.assertEqual(
1607            self.browser.url, self.student_path + '/reject_clearance')
1608        # Type comment why.
1609        self.browser.getControl(name="form.officer_comment").value = (
1610            'Dear Student,\n'
1611            'You did not fill properly.')
1612        self.browser.getControl("Save comment").click()
1613        self.assertTrue('Clearance has been annulled' in self.browser.contents)
1614        url = ('http://localhost/app/students/K1000000/'
1615              'contactstudent?body=Dear+Student%2C%0AYou+did+not+fill+properly.'
1616              '&subject=Clearance+has+been+annulled.')
1617        # CO does now see the prefilled contact form and can send a message.
1618        self.assertEqual(self.browser.url, url)
1619        self.assertTrue('clearance started' in self.browser.contents)
1620        self.assertTrue('name="form.subject" size="20" type="text" '
1621            'value="Clearance has been annulled."'
1622            in self.browser.contents)
1623        self.assertTrue('name="form.body" rows="10" >Dear Student,'
1624            in self.browser.contents)
1625        self.browser.getControl("Send message now").click()
1626        self.assertTrue('Your message has been sent' in self.browser.contents)
1627        # The comment has been stored ...
1628        self.assertEqual(self.student.officer_comment,
1629            u'Dear Student,\nYou did not fill properly.')
1630        # ... and logged.
1631        logfile = os.path.join(
1632            self.app['datacenter'].storage, 'logs', 'students.log')
1633        logcontent = open(logfile).read()
1634        self.assertTrue(
1635            'INFO - mrclear - students.browser.StudentRejectClearancePage - '
1636            'K1000000 - comment: Dear Student,<br>You did not fill '
1637            'properly.\n' in logcontent)
1638        self.browser.open(self.history_path)
1639        self.assertTrue("Reset to 'clearance started' by My Public Name" in
1640            self.browser.contents)
1641        IWorkflowInfo(self.student).fireTransition('request_clearance')
1642        self.browser.open(self.clearance_path)
1643        self.browser.getLink("Reject clearance").click()
1644        self.browser.getControl("Save comment").click()
1645        self.assertTrue('Clearance request has been rejected'
1646            in self.browser.contents)
1647        self.assertTrue('clearance started' in self.browser.contents)
1648        # The CO can't clear students if not in state
1649        # clearance requested.
1650        self.browser.open(self.student_path + '/clear')
1651        self.assertTrue('Student is in wrong state'
1652            in self.browser.contents)
1653        # The CO can go to his department throug the my_roles page ...
1654        self.browser.open('http://localhost/app/users/mrclear/my_roles')
1655        self.browser.getLink("http://localhost/app/faculties/fac1/dep1").click()
1656        # ... and view the list of students.
1657        self.browser.getLink("Show students").click()
1658        self.browser.getControl(name="session").value = ['2004']
1659        self.browser.getControl(name="level").value = ['200']
1660        self.browser.getControl("Show").click()
1661        self.assertFalse(self.student_id in self.browser.contents)
1662        self.browser.getControl(name="session").value = ['2004']
1663        self.browser.getControl(name="level").value = ['100']
1664        self.browser.getControl("Show").click()
1665        self.assertTrue(self.student_id in self.browser.contents)
1666        # The comment is indicated by 'yes'.
1667        self.assertTrue('<td><span>yes</span></td>' in self.browser.contents)
1668        # Check if the enquiries form is not pre-filled with officer_comment
1669        # (regression test).
1670        self.browser.getLink("Logout").click()
1671        self.browser.open('http://localhost/app/enquiries')
1672        self.assertFalse(
1673            'You did not fill properly'
1674            in self.browser.contents)
1675        # When a student is cleared the comment is automatically deleted
1676        IWorkflowInfo(self.student).fireTransition('request_clearance')
1677        IWorkflowInfo(self.student).fireTransition('clear')
1678        self.assertEqual(self.student.officer_comment, None)
1679        return
1680
1681    def test_handle_mass_clearance_by_co(self):
1682        self.init_clearance_officer()
1683        # Additional setups according to test above
1684        notify(LocalRoleSetEvent(
1685            self.department, 'waeup.local.ClearanceOfficer', 'mrclear',
1686            granted=True))
1687        self.app['configuration']['2004'].clearance_enabled = True
1688        IWorkflowState(self.student).setState('clearance requested')
1689        # Update the catalog
1690        notify(grok.ObjectModifiedEvent(self.student))
1691        # The CO can go to the department and clear all students in department
1692        self.browser.open('http://localhost/app/faculties/fac1/dep1')
1693        self.browser.getLink("Clear all students").click()
1694        self.assertTrue('1 students have been cleared' in self.browser.contents)
1695        self.browser.open(self.history_path)
1696        self.assertTrue('Cleared by Carlo Pitter' in self.browser.contents)
1697        logfile = os.path.join(
1698            self.app['datacenter'].storage, 'logs', 'students.log')
1699        logcontent = open(logfile).read()
1700        self.assertTrue(
1701            'INFO - mrclear - K1000000 - Cleared' in logcontent)
1702        self.browser.open('http://localhost/app/faculties/fac1/dep1')
1703        self.browser.getLink("Clear all students").click()
1704        self.assertTrue('0 students have been cleared' in self.browser.contents)
1705        return
1706
1707    def test_handle_courses_by_ca(self):
1708        self.app['users'].addUser('mrsadvise', SECRET)
1709        self.app['users']['mrsadvise'].email = 'mradvise@foo.ng'
1710        self.app['users']['mrsadvise'].title = u'Helen Procter'
1711        # Assign local CourseAdviser100 role for a certificate
1712        cert = self.app['faculties']['fac1']['dep1'].certificates['CERT1']
1713        prmlocal = IPrincipalRoleManager(cert)
1714        prmlocal.assignRoleToPrincipal('waeup.local.CourseAdviser100', 'mrsadvise')
1715        IWorkflowState(self.student).setState('school fee paid')
1716        # Login as course adviser.
1717        self.browser.open(self.login_path)
1718        self.browser.getControl(name="form.login").value = 'mrsadvise'
1719        self.browser.getControl(name="form.password").value = SECRET
1720        self.browser.getControl("Login").click()
1721        self.assertMatches('...You logged in...', self.browser.contents)
1722        # CO can see his roles.
1723        self.browser.getLink("My Roles").click()
1724        self.assertMatches(
1725            '...<div>Academics Officer (view only)</div>...',
1726            self.browser.contents)
1727        # But not his local role ...
1728        self.assertFalse('Course Adviser' in self.browser.contents)
1729        # ... because we forgot to notify the certificate that the local role
1730        # has changed.
1731        notify(LocalRoleSetEvent(
1732            cert, 'waeup.local.CourseAdviser100', 'mrsadvise', granted=True))
1733        self.browser.open('http://localhost/app/users/mrsadvise/my_roles')
1734        self.assertTrue('Course Adviser 100L' in self.browser.contents)
1735        self.assertMatches(
1736            '...<a href="http://localhost/app/faculties/fac1/dep1/certificates/CERT1">...',
1737            self.browser.contents)
1738        # CA can view the student ...
1739        self.browser.open(self.student_path)
1740        self.assertEqual(self.browser.headers['Status'], '200 Ok')
1741        self.assertEqual(self.browser.url, self.student_path)
1742        # ... but not other students.
1743        other_student = Student()
1744        other_student.firstname = u'Dep2'
1745        other_student.lastname = u'Student'
1746        self.app['students'].addStudent(other_student)
1747        other_student_path = (
1748            'http://localhost/app/students/%s' % other_student.student_id)
1749        self.assertRaises(
1750            Unauthorized, self.browser.open, other_student_path)
1751        # We add study level 110 to the student's studycourse.
1752        studylevel = StudentStudyLevel()
1753        studylevel.level = 110
1754        self.student['studycourse'].addStudentStudyLevel(
1755            cert,studylevel)
1756        L110_student_path = self.studycourse_path + '/110'
1757        # The CA can neither see the Validate nor the Edit button.
1758        self.browser.open(L110_student_path)
1759        self.assertFalse('Validate courses' in self.browser.contents)
1760        self.assertFalse('Edit' in self.browser.contents)
1761        IWorkflowInfo(self.student).fireTransition('register_courses')
1762        self.browser.open(L110_student_path)
1763        self.assertFalse('Validate courses' in self.browser.contents)
1764        self.assertFalse('Edit' in self.browser.contents)
1765        # Only in state courses registered and only if the current level
1766        # corresponds with the name of the study level object
1767        # the 100L CA does see the 'Validate' button but not
1768        # the edit button.
1769        self.student['studycourse'].current_level = 110
1770        self.browser.open(L110_student_path)
1771        self.assertFalse('Edit' in self.browser.contents)
1772        self.assertTrue('Validate courses' in self.browser.contents)
1773        # But a 100L CA does not see the button at other levels.
1774        studylevel2 = StudentStudyLevel()
1775        studylevel2.level = 200
1776        self.student['studycourse'].addStudentStudyLevel(
1777            cert,studylevel2)
1778        L200_student_path = self.studycourse_path + '/200'
1779        self.browser.open(L200_student_path)
1780        self.assertFalse('Edit' in self.browser.contents)
1781        self.assertFalse('Validate courses' in self.browser.contents)
1782        self.browser.open(L110_student_path)
1783        self.browser.getLink("Validate courses").click()
1784        self.assertTrue('Course list has been validated' in self.browser.contents)
1785        self.assertTrue('courses validated' in self.browser.contents)
1786        self.assertEqual(self.student['studycourse']['110'].validated_by,
1787            'Helen Procter')
1788        self.assertMatches(
1789            '<YYYY-MM-DD hh:mm:ss>',
1790            self.student['studycourse']['110'].validation_date.strftime(
1791                "%Y-%m-%d %H:%M:%S"))
1792        self.browser.getLink("Reject courses").click()
1793        self.assertTrue('Course list request has been annulled.'
1794            in self.browser.contents)
1795        urlmessage = 'Course+list+request+has+been+annulled.'
1796        self.assertEqual(self.browser.url, self.student_path +
1797            '/contactstudent?subject=%s' % urlmessage)
1798        self.assertTrue('school fee paid' in self.browser.contents)
1799        self.assertTrue(self.student['studycourse']['110'].validated_by is None)
1800        self.assertTrue(self.student['studycourse']['110'].validation_date is None)
1801        IWorkflowInfo(self.student).fireTransition('register_courses')
1802        self.browser.open(L110_student_path)
1803        self.browser.getLink("Reject courses").click()
1804        self.assertTrue('Course list has been unregistered'
1805            in self.browser.contents)
1806        self.assertTrue('school fee paid' in self.browser.contents)
1807        # CA does now see the contact form and can send a message.
1808        self.browser.getControl(name="form.subject").value = 'Important subject'
1809        self.browser.getControl(name="form.body").value = 'Course list rejected'
1810        self.browser.getControl("Send message now").click()
1811        self.assertTrue('Your message has been sent' in self.browser.contents)
1812        # The CA does now see the Edit button and can edit
1813        # current study level.
1814        self.browser.open(L110_student_path)
1815        self.browser.getLink("Edit").click()
1816        self.assertTrue('Edit course list of 100 (Year 1) on 1st probation'
1817            in self.browser.contents)
1818        # The CA can't validate courses if not in state
1819        # courses registered.
1820        self.browser.open(L110_student_path + '/validate_courses')
1821        self.assertTrue('Student is in the wrong state'
1822            in self.browser.contents)
1823        # The CA can go to his certificate through the my_roles page ...
1824        self.browser.open('http://localhost/app/users/mrsadvise/my_roles')
1825        self.browser.getLink(
1826            "http://localhost/app/faculties/fac1/dep1/certificates/CERT1").click()
1827        # ... and view the list of students.
1828        self.browser.getLink("Show students").click()
1829        self.browser.getControl(name="session").value = ['2004']
1830        self.browser.getControl(name="level").value = ['100']
1831        self.browser.getControl("Show").click()
1832        self.assertTrue(self.student_id in self.browser.contents)
1833
1834    def test_change_current_mode(self):
1835        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1836        self.browser.open(self.clearance_path)
1837        self.assertFalse('Employer' in self.browser.contents)
1838        self.browser.open(self.manage_clearance_path)
1839        self.assertFalse('Employer' in self.browser.contents)
1840        self.browser.open(self.edit_clearance_path)
1841        self.assertFalse('Employer' in self.browser.contents)
1842        # Now we change the study mode of the certificate and a different
1843        # interface is used by clearance views.
1844        self.certificate.study_mode = 'pg_ft'
1845        # Invariants are not being checked here?!
1846        self.certificate.end_level = 100
1847        self.browser.open(self.clearance_path)
1848        self.assertTrue('Employer' in self.browser.contents)
1849        self.browser.open(self.manage_clearance_path)
1850        self.assertTrue('Employer' in self.browser.contents)
1851        IWorkflowState(self.student).setState('clearance started')
1852        self.browser.open(self.edit_clearance_path)
1853        self.assertTrue('Employer' in self.browser.contents)
1854
1855    def test_find_students_in_faculties(self):
1856        # Create local students manager in faculty
1857        self.app['users'].addUser('mrmanager', SECRET)
1858        self.app['users']['mrmanager'].email = 'mrmanager@foo.ng'
1859        self.app['users']['mrmanager'].title = u'Volk Wagen'
1860        # Assign LocalStudentsManager role for faculty
1861        fac = self.app['faculties']['fac1']
1862        prmlocal = IPrincipalRoleManager(fac)
1863        prmlocal.assignRoleToPrincipal(
1864            'waeup.local.LocalStudentsManager', 'mrmanager')
1865        notify(LocalRoleSetEvent(
1866            fac, 'waeup.local.LocalStudentsManager', 'mrmanager',
1867            granted=True))
1868        # Login as manager
1869        self.browser.open(self.login_path)
1870        self.browser.getControl(name="form.login").value = 'mrmanager'
1871        self.browser.getControl(name="form.password").value = SECRET
1872        self.browser.getControl("Login").click()
1873        self.assertMatches('...You logged in...', self.browser.contents)
1874        # Manager can see his roles
1875        self.browser.getLink("My Roles").click()
1876        self.assertMatches(
1877            '...<span>Students Manager</span>...',
1878            self.browser.contents)
1879        # The manager can go to his faculty
1880        self.browser.getLink(
1881            "http://localhost/app/faculties/fac1").click()
1882        # and find students
1883        self.browser.getLink("Find students").click()
1884        self.browser.getControl("Find student").click()
1885        self.assertTrue('Empty search string' in self.browser.contents)
1886        self.browser.getControl(name="searchtype").value = ['student_id']
1887        self.browser.getControl(name="searchterm").value = self.student_id
1888        self.browser.getControl("Find student").click()
1889        self.assertTrue('Anna Tester' in self.browser.contents)
1890
1891    def test_activate_deactivate_buttons(self):
1892        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1893        self.browser.open(self.student_path)
1894        self.browser.getLink("Deactivate").click()
1895        self.assertTrue(
1896            'Student account has been deactivated.' in self.browser.contents)
1897        self.assertTrue(
1898            'Base Data (account deactivated)' in self.browser.contents)
1899        self.assertTrue(self.student.suspended)
1900        self.browser.getLink("Activate").click()
1901        self.assertTrue(
1902            'Student account has been activated.' in self.browser.contents)
1903        self.assertFalse(
1904            'Base Data (account deactivated)' in self.browser.contents)
1905        self.assertFalse(self.student.suspended)
1906        # History messages have been added ...
1907        self.browser.getLink("History").click()
1908        self.assertTrue(
1909            'Student account deactivated by Manager<br />' in self.browser.contents)
1910        self.assertTrue(
1911            'Student account activated by Manager<br />' in self.browser.contents)
1912        # ... and actions have been logged.
1913        logfile = os.path.join(
1914            self.app['datacenter'].storage, 'logs', 'students.log')
1915        logcontent = open(logfile).read()
1916        self.assertTrue('zope.mgr - students.browser.StudentDeactivateView - '
1917                        'K1000000 - account deactivated' in logcontent)
1918        self.assertTrue('zope.mgr - students.browser.StudentActivateView - '
1919                        'K1000000 - account activated' in logcontent)
1920
1921    def test_manage_student_transfer(self):
1922        # Add second certificate
1923        self.certificate2 = createObject('waeup.Certificate')
1924        self.certificate2.code = u'CERT2'
1925        self.certificate2.study_mode = 'ug_ft'
1926        self.certificate2.start_level = 999
1927        self.certificate2.end_level = 999
1928        self.app['faculties']['fac1']['dep1'].certificates.addCertificate(
1929            self.certificate2)
1930
1931        # Add study level to old study course
1932        studylevel = createObject(u'waeup.StudentStudyLevel')
1933        studylevel.level = 200
1934        self.student['studycourse'].addStudentStudyLevel(
1935            self.certificate, studylevel)
1936        studylevel = createObject(u'waeup.StudentStudyLevel')
1937        studylevel.level = 999
1938        self.student['studycourse'].addStudentStudyLevel(
1939            self.certificate, studylevel)
1940
1941        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1942        self.browser.open(self.student_path)
1943        self.browser.getLink("Transfer").click()
1944        self.browser.getControl(name="form.certificate").value = ['CERT2']
1945        self.browser.getControl(name="form.current_session").value = ['2011']
1946        self.browser.getControl(name="form.current_level").value = ['200']
1947        self.browser.getControl("Transfer").click()
1948        self.assertTrue(
1949            'Current level does not match certificate levels'
1950            in self.browser.contents)
1951        self.browser.getControl(name="form.current_level").value = ['999']
1952        self.browser.getControl("Transfer").click()
1953        self.assertTrue('Successfully transferred' in self.browser.contents)
1954        # The catalog has been updated
1955        cat = queryUtility(ICatalog, name='students_catalog')
1956        results = list(
1957            cat.searchResults(
1958            certcode=('CERT2', 'CERT2')))
1959        self.assertTrue(results[0] is self.student)
1960        results = list(
1961            cat.searchResults(
1962            current_session=(2011, 2011)))
1963        self.assertTrue(results[0] is self.student)
1964        # Add study level to new study course
1965        studylevel = createObject(u'waeup.StudentStudyLevel')
1966        studylevel.level = 999
1967        self.student['studycourse'].addStudentStudyLevel(
1968            self.certificate, studylevel)
1969
1970        # Edit and add pages are locked for old study courses
1971        self.browser.open(self.student_path + '/studycourse/manage')
1972        self.assertFalse('The requested form is locked' in self.browser.contents)
1973        self.browser.open(self.student_path + '/studycourse_1/manage')
1974        self.assertTrue('The requested form is locked' in self.browser.contents)
1975
1976        self.browser.open(self.student_path + '/studycourse/start_session')
1977        self.assertFalse('The requested form is locked' in self.browser.contents)
1978        self.browser.open(self.student_path + '/studycourse_1/start_session')
1979        self.assertTrue('The requested form is locked' in self.browser.contents)
1980
1981        IWorkflowState(self.student).setState('school fee paid')
1982        self.browser.open(self.student_path + '/studycourse/add')
1983        self.assertFalse('The requested form is locked' in self.browser.contents)
1984        self.browser.open(self.student_path + '/studycourse_1/add')
1985        self.assertTrue('The requested form is locked' in self.browser.contents)
1986
1987        self.browser.open(self.student_path + '/studycourse/999/manage')
1988        self.assertFalse('The requested form is locked' in self.browser.contents)
1989        self.browser.open(self.student_path + '/studycourse_1/999/manage')
1990        self.assertTrue('The requested form is locked' in self.browser.contents)
1991
1992        self.browser.open(self.student_path + '/studycourse/999/validate_courses')
1993        self.assertFalse('The requested form is locked' in self.browser.contents)
1994        self.browser.open(self.student_path + '/studycourse_1/999/validate_courses')
1995        self.assertTrue('The requested form is locked' in self.browser.contents)
1996
1997        self.browser.open(self.student_path + '/studycourse/999/reject_courses')
1998        self.assertFalse('The requested form is locked' in self.browser.contents)
1999        self.browser.open(self.student_path + '/studycourse_1/999/reject_courses')
2000        self.assertTrue('The requested form is locked' in self.browser.contents)
2001
2002        self.browser.open(self.student_path + '/studycourse/999/add')
2003        self.assertFalse('The requested form is locked' in self.browser.contents)
2004        self.browser.open(self.student_path + '/studycourse_1/999/add')
2005        self.assertTrue('The requested form is locked' in self.browser.contents)
2006
2007        self.browser.open(self.student_path + '/studycourse/999/edit')
2008        self.assertFalse('The requested form is locked' in self.browser.contents)
2009        self.browser.open(self.student_path + '/studycourse_1/999/edit')
2010        self.assertTrue('The requested form is locked' in self.browser.contents)
2011
2012        # Revert transfer
2013        self.browser.open(self.student_path + '/studycourse_1')
2014        self.browser.getLink("Reactivate").click()
2015        self.browser.getControl("Revert now").click()
2016        self.assertTrue('Previous transfer reverted' in self.browser.contents)
2017        results = list(
2018            cat.searchResults(
2019            certcode=('CERT1', 'CERT1')))
2020        self.assertTrue(results[0] is self.student)
2021        self.assertEqual([i for i in self.student.keys()],
2022            [u'accommodation', u'payments', u'studycourse'])
2023
2024    def test_login_as_student(self):
2025        # StudentImpersonators can login as student
2026        # Create clearance officer
2027        self.app['users'].addUser('mrofficer', SECRET)
2028        self.app['users']['mrofficer'].email = 'mrofficer@foo.ng'
2029        self.app['users']['mrofficer'].title = 'Harry Actor'
2030        prmglobal = IPrincipalRoleManager(self.app)
2031        prmglobal.assignRoleToPrincipal('waeup.StudentImpersonator', 'mrofficer')
2032        prmglobal.assignRoleToPrincipal('waeup.StudentsManager', 'mrofficer')
2033        # Login as student impersonator
2034        self.browser.open(self.login_path)
2035        self.browser.getControl(name="form.login").value = 'mrofficer'
2036        self.browser.getControl(name="form.password").value = SECRET
2037        self.browser.getControl("Login").click()
2038        self.assertMatches('...You logged in...', self.browser.contents)
2039        self.browser.open(self.student_path)
2040        self.browser.getLink("Login as").click()
2041        self.browser.getControl("Set password now").click()
2042        temp_password = self.browser.getControl(name='form.password').value
2043        self.browser.getControl("Login now").click()
2044        self.assertMatches(
2045            '...You successfully logged in as...', self.browser.contents)
2046        # We are logged in as student and can see the 'My Data' tab
2047        self.assertMatches(
2048            '...<a href="#" class="dropdown-toggle" data-toggle="dropdown">...',
2049            self.browser.contents)
2050        self.assertMatches(
2051            '...My Data...',
2052            self.browser.contents)
2053        self.browser.getLink("Logout").click()
2054        # The student can't login with the original password ...
2055        self.browser.open(self.login_path)
2056        self.browser.getControl(name="form.login").value = self.student_id
2057        self.browser.getControl(name="form.password").value = 'spwd'
2058        self.browser.getControl("Login").click()
2059        self.assertMatches(
2060            '...Your account has been temporarily deactivated...',
2061            self.browser.contents)
2062        # ... but with the temporary password
2063        self.browser.open(self.login_path)
2064        self.browser.getControl(name="form.login").value = self.student_id
2065        self.browser.getControl(name="form.password").value = temp_password
2066        self.browser.getControl("Login").click()
2067        self.assertMatches('...You logged in...', self.browser.contents)
2068        # Creation of temp_password is properly logged
2069        logfile = os.path.join(
2070            self.app['datacenter'].storage, 'logs', 'students.log')
2071        logcontent = open(logfile).read()
2072        self.assertTrue(
2073            'mrofficer - students.browser.LoginAsStudentStep1 - K1000000 - '
2074            'temp_password generated: %s' % temp_password in logcontent)
2075
2076    def test_transcripts(self):
2077        studylevel = createObject(u'waeup.StudentStudyLevel')
2078        studylevel.level = 100
2079        studylevel.level_session = 2005
2080        self.student['studycourse'].entry_mode = 'ug_ft'
2081        self.student['studycourse'].addStudentStudyLevel(
2082            self.certificate, studylevel)
2083        studylevel2 = createObject(u'waeup.StudentStudyLevel')
2084        studylevel2.level = 110
2085        studylevel2.level_session = 2006
2086        self.student['studycourse'].addStudentStudyLevel(
2087            self.certificate, studylevel2)
2088        # Add second course (COURSE has been added automatically)
2089        courseticket = createObject('waeup.CourseTicket')
2090        courseticket.code = 'ANYCODE'
2091        courseticket.title = u'Any TITLE'
2092        courseticket.credits = 13
2093        courseticket.score = 66
2094        courseticket.semester = 1
2095        courseticket.dcode = u'ANYDCODE'
2096        courseticket.fcode = u'ANYFCODE'
2097        self.student['studycourse']['110']['COURSE2'] = courseticket
2098        self.student['studycourse']['100']['COURSE1'].score = 55
2099        self.assertEqual(self.student['studycourse']['100'].gpa_params_rectified[0], 3.0)
2100        self.assertEqual(self.student['studycourse']['110'].gpa_params_rectified[0], 4.0)
2101        # Get transcript data
2102        td = self.student['studycourse'].getTranscriptData()
2103        self.assertEqual(td[0][0]['level_key'], '100')
2104        self.assertEqual(td[0][0]['sgpa'], 3.0)
2105        self.assertEqual(td[0][0]['level'].level, 100)
2106        self.assertEqual(td[0][0]['level'].level_session, 2005)
2107        self.assertEqual(td[0][0]['tickets_1'][0].code, 'COURSE1')
2108        self.assertEqual(td[0][1]['level_key'], '110')
2109        self.assertEqual(td[0][1]['sgpa'], 4.0)
2110        self.assertEqual(td[0][1]['level'].level, 110)
2111        self.assertEqual(td[0][1]['level'].level_session, 2006)
2112        self.assertEqual(td[0][1]['tickets_1'][0].code, 'ANYCODE')
2113        self.assertEqual(td[1], 3.5652173913043477)
2114        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
2115        self.browser.open(self.student_path + '/studycourse/transcript')
2116        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2117        self.assertTrue('Transcript' in self.browser.contents)
2118        # Officers can open the pdf transcript
2119        self.browser.open(self.student_path + '/studycourse/transcript.pdf')
2120        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2121        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2122        path = os.path.join(samples_dir(), 'transcript.pdf')
2123        open(path, 'wb').write(self.browser.contents)
2124        print "Sample PDF transcript.pdf written to %s" % path
2125
2126    def test_process_transcript(self):
2127        IWorkflowState(self.student).setState('transcript requested')
2128        notify(grok.ObjectModifiedEvent(self.student))
2129        self.student['studycourse'].transcript_comment = (
2130            u'On 07/08/2013 08:59:54 UTC K1000000 wrote:\n\nComment line 1 \n'
2131            'Comment line2\n\nDispatch Address:\nAddress line 1 \n'
2132            'Address line2\n\n')
2133        # Create officer with both roles
2134        self.app['users'].addUser('mrtranscript', SECRET)
2135        self.app['users']['mrtranscript'].email = 'mrtranscript@foo.ng'
2136        self.app['users']['mrtranscript'].title = 'Ruth Gordon'
2137        prmglobal = IPrincipalRoleManager(self.app)
2138        prmglobal.assignRoleToPrincipal('waeup.TranscriptOfficer', 'mrtranscript')
2139        prmglobal.assignRoleToPrincipal('waeup.StudentsManager', 'mrtranscript')
2140        prmglobal.assignRoleToPrincipal('waeup.TranscriptSignee', 'mrtranscript')
2141        # Login
2142        self.browser.open(self.login_path)
2143        self.browser.getControl(name="form.login").value = 'mrtranscript'
2144        self.browser.getControl(name="form.password").value = SECRET
2145        self.browser.getControl("Login").click()
2146        self.assertMatches('...You logged in...', self.browser.contents)
2147        # Officer can see his roles
2148        self.browser.getLink("My Roles").click()
2149        self.assertMatches(
2150            '...<div>Transcript Officer</div>...',
2151            self.browser.contents)
2152        # Officer can search for students in state 'transcript requested'
2153        self.browser.open(self.container_path)
2154        self.browser.getControl(name="searchtype").value = [
2155            'transcript requested']
2156        self.browser.getControl("Find student(s)").click()
2157        self.assertTrue('Anna Tester' in self.browser.contents)
2158        self.browser.getLink("K1000000").click()
2159        self.assertFalse('Release transcript request' in self.browser.contents)
2160        # Officers can still edit studycourse, studylevel and course tickets.
2161        self.browser.open(self.studycourse_path + '/manage')
2162        self.assertTrue('Undergraduate Full-Time</option>'
2163            in self.browser.contents)
2164        self.browser.getControl(name="form.certificate").value = ['CERT1']
2165        self.browser.getControl(name="form.current_session").value = ['2004']
2166        self.browser.getControl(name="form.current_verdict").value = ['A']
2167        self.browser.getControl(name="form.entry_mode").value = ['ug_ft']
2168        self.browser.getControl("Save").click()
2169        self.browser.getControl(name="form.current_level").value = ['100']
2170        self.browser.getControl("Save").click()
2171        self.browser.getControl(name="addlevel").value = ['100']
2172        self.browser.getControl(name="level_session").value = ['2004']
2173        self.browser.getControl("Add study level").click()
2174        self.browser.getLink("100").click()
2175        self.browser.getLink("Manage").click()
2176        self.browser.getControl(name="form.level_session").value = ['2002']
2177        self.browser.getControl("Save").click()
2178        self.browser.getLink("COURSE1").click()
2179        self.browser.getLink("Manage").click()
2180        self.browser.getControl("Save").click()
2181        self.assertTrue('Form has been saved' in self.browser.contents)
2182        # Officer can edit transcript remarks and validate the transcript
2183        self.browser.open(self.studycourse_path + '/transcript')
2184        self.browser.getLink("Validate transcript").click()
2185        self.browser.getLink("Edit").click()
2186        self.assertEqual(
2187            self.browser.url, self.studycourse_path + '/100/remark')
2188        self.browser.getControl(
2189            name="form.transcript_remark").value = 'Oh, the student failed'
2190        self.browser.getControl(
2191            "Save remark and go and back to transcript validation page").click()
2192        self.assertEqual(
2193            self.browser.url,
2194            self.studycourse_path + '/validate_transcript#tab4')
2195        self.assertEqual(self.student['studycourse']['100'].transcript_remark,
2196            'Oh, the student failed')
2197        self.browser.getControl("Save comment and validate transcript").click()
2198        # After validation all manage forms are locked.
2199        self.browser.open(self.studycourse_path + '/manage')
2200        self.assertTrue('The requested form is locked' in self.browser.contents)
2201        self.assertFalse('Undergraduate Full-Time</option>'
2202            in self.browser.contents)
2203        self.browser.open(self.studycourse_path + '/100/manage')
2204        self.assertTrue('The requested form is locked' in self.browser.contents)
2205        self.browser.open(self.studycourse_path + '/100/COURSE1/manage')
2206        self.assertTrue('The requested form is locked' in self.browser.contents)
2207        self.browser.open(self.studycourse_path + '/100/remark')
2208        self.assertTrue('The requested form is locked' in self.browser.contents)
2209
2210        # Transcript can be signed if officer has the permission to sign
2211        #self.browser.open(self.studycourse_path + '/transcript')
2212        #self.assertFalse('Sign transcript' in self.browser.contents)
2213        #prmglobal = IPrincipalRoleManager(self.app)
2214        #prmglobal.assignRoleToPrincipal('waeup.TranscriptSignee', 'mrtranscript')
2215
2216        self.browser.open(self.studycourse_path + '/transcript')
2217        self.browser.getLink("Sign transcript electronically").click()
2218        # Transcript signing has been logged ...
2219        logfile = os.path.join(
2220            self.app['datacenter'].storage, 'logs', 'students.log')
2221        logcontent = open(logfile).read()
2222        self.assertTrue(
2223            'mrtranscript - students.browser.StudentTranscriptSignView - '
2224            'K1000000 - Transcript signed' in logcontent)
2225        # ... appears in the student's history ...
2226        self.browser.open(self.history_path)
2227        self.assertTrue('Transcript signed by Ruth Gordon'
2228            in self.browser.contents)
2229        # ... and is also stored in the transcript_signee attribute.
2230        self.assertTrue(
2231            u'Electronically signed by Ruth Gordon (mrtranscript) on '
2232            in self.student['studycourse'].transcript_signees)
2233        # Officer can release the transcript
2234        self.browser.open(self.studycourse_path + '/transcript')
2235        self.browser.getLink("Release transcript").click()
2236        self.assertTrue(' UTC K1000000 wrote:<br><br>Comment line 1 <br>'
2237        'Comment line2<br><br>Dispatch Address:<br>Address line 1 <br>'
2238        'Address line2<br><br></p>' in self.browser.contents)
2239        self.browser.getControl(name="comment").value = (
2240            'Hello,\nYour transcript has been sent to the address provided.')
2241        self.browser.getControl("Save comment and release transcript").click()
2242        self.assertTrue(
2243            'UTC mrtranscript wrote:\n\nHello,\nYour transcript has '
2244            'been sent to the address provided.\n\n'
2245            in self.student['studycourse'].transcript_comment)
2246        # The comment has been logged
2247        logfile = os.path.join(
2248            self.app['datacenter'].storage, 'logs', 'students.log')
2249        logcontent = open(logfile).read()
2250        self.assertTrue(
2251            'mrtranscript - students.browser.StudentTranscriptReleaseFormPage - '
2252            'K1000000 - comment: Hello,<br>'
2253            'Your transcript has been sent to the address provided'
2254            in logcontent)
2255        # File has been stored in the file system
2256        # Check if transcript exists in the file system and is a PDF file
2257        storage = getUtility(IExtFileStore)
2258        file_id = IFileStoreNameChooser(
2259            self.student).chooseName(attr='final_transcript.pdf')
2260        pdf = storage.getFile(file_id).read()
2261        self.assertTrue(len(pdf) > 0)
2262        self.assertEqual(pdf[:8], '%PDF-1.4')
2263        # Copy the file to samples_dir
2264        path = os.path.join(samples_dir(), 'final_transcript.pdf')
2265        open(path, 'wb').write(pdf)
2266        print "Sample PDF final_transcript.pdf written to %s" % path
2267        # Check if there is an transcript pdf link in UI
2268        self.browser.open(self.student_path)
2269        self.assertTrue('Final Transcript' in self.browser.contents)
2270        self.browser.getLink("Final Transcript").click()
2271        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2272        self.assertEqual(self.browser.headers['Content-Type'],
2273                         'application/pdf')
2274        # Transcript views are no longer accessible
2275        self.browser.open(self.studycourse_path)
2276        self.assertFalse('studycourse/transcript' in self.browser.contents)
2277        self.browser.open(self.studycourse_path + '/transcript')
2278        self.assertTrue('Forbidden!' in self.browser.contents)
2279        self.browser.open(self.studycourse_path + '/transcript.pdf')
2280        self.assertTrue('Forbidden!' in self.browser.contents)
2281        # If we reset the transcript process
2282        # (can't be done by transcript officer), the file will be deleted
2283        IWorkflowInfo(self.student).fireTransition('reset11')
2284        self.browser.open(self.student_path)
2285        self.assertFalse('Final Transcript' in self.browser.contents)
2286        # ... and transcript process information has been removed
2287        self.assertEqual(self.student['studycourse'].transcript_comment, None)
2288        self.assertEqual(self.student['studycourse'].transcript_signees, None)
2289
2290    def test_landingpage_transcript_officer(self):
2291        IWorkflowState(self.student).setState('transcript requested')
2292        notify(grok.ObjectModifiedEvent(self.student))
2293        # Create transcript officer
2294        self.app['users'].addUser('mrtranscript', SECRET)
2295        self.app['users']['mrtranscript'].email = 'mrtranscript@foo.ng'
2296        self.app['users']['mrtranscript'].title = 'Ruth Gordon'
2297        # We assign transcript officer role at faculty level
2298        fac = self.app['faculties']['fac1']
2299        prmlocal = IPrincipalRoleManager(fac)
2300        prmlocal.assignRoleToPrincipal(
2301            'waeup.local.TranscriptOfficer', 'mrtranscript')
2302        notify(LocalRoleSetEvent(
2303            fac, 'waeup.local.TranscriptOfficer', 'mrtranscript', granted=True))
2304        # Login as transcript officer
2305        self.browser.open(self.login_path)
2306        self.browser.getControl(name="form.login").value = 'mrtranscript'
2307        self.browser.getControl(name="form.password").value = SECRET
2308        self.browser.getControl("Login").click()
2309        self.assertMatches('...You logged in...', self.browser.contents)
2310        # Officer is on landing page and does see the transcript link
2311        self.assertTrue(
2312            'http://localhost/app/students/K1000000/studycourse/transcript'
2313            in self.browser.contents)
2314        self.browser.getLink("K1000000").click()
2315        self.assertTrue(
2316            'Anna Tester: Transcript Data' in self.browser.contents)
2317        # Officer is on transcript page and can validate the transcript
2318        self.browser.getLink("Validate transcript").click()
2319        self.browser.getControl("Save comment and validate transcript").click()
2320        self.assertTrue(
2321            '<div class="alert alert-success">Transcript validated.</div>'
2322            in self.browser.contents)
2323        # Officer is still on transcript page and can release the transcript
2324        self.browser.getLink("Release transcript").click()
2325        self.browser.getControl("Save comment and release transcript").click()
2326        self.assertTrue(
2327            '<div class="alert alert-success">'
2328            'Transcript released and final transcript file saved.</div>'
2329            in self.browser.contents)
2330
2331    def test_landingpage_transcript_signee(self):
2332        IWorkflowState(self.student).setState('transcript validated')
2333        notify(grok.ObjectModifiedEvent(self.student))
2334        # Create transcript signee
2335        self.app['users'].addUser('mrtranscript', SECRET)
2336        self.app['users']['mrtranscript'].email = 'mrtranscript@foo.ng'
2337        self.app['users']['mrtranscript'].title = 'Ruth Gordon'
2338        # We assign transcript officer role at faculty level
2339        fac = self.app['faculties']['fac1']
2340        prmlocal = IPrincipalRoleManager(fac)
2341        prmlocal.assignRoleToPrincipal(
2342            'waeup.local.TranscriptSignee', 'mrtranscript')
2343        notify(LocalRoleSetEvent(
2344            fac, 'waeup.local.TranscriptSignee', 'mrtranscript', granted=True))
2345        # Login as transcript officer
2346        self.browser.open(self.login_path)
2347        self.browser.getControl(name="form.login").value = 'mrtranscript'
2348        self.browser.getControl(name="form.password").value = SECRET
2349        self.browser.getControl("Login").click()
2350        self.assertMatches('...You logged in...', self.browser.contents)
2351        # Officer is on landing page and does see the transcript link
2352        self.assertTrue(
2353            'http://localhost/app/students/K1000000/studycourse/transcript'
2354            in self.browser.contents)
2355        self.browser.getLink("K1000000").click()
2356        self.assertTrue(
2357            'Anna Tester: Transcript Data' in self.browser.contents)
2358        # Officer is on transcript page and can sign the transcript
2359        self.browser.getLink("Sign transcript").click()
2360        self.assertTrue(
2361            '<div class="alert alert-success">Transcript signed.</div>'
2362            in self.browser.contents)
2363        # Officer is still on transcript page
2364        self.assertTrue(
2365            'Anna Tester: Transcript Data' in self.browser.contents)
2366        # Officer can sign the transcript only once
2367        self.browser.getLink("Sign transcript").click()
2368        self.assertTrue(
2369            '<div class="alert alert-warning">'
2370            'You have already signed this transcript.</div>'
2371            in self.browser.contents)
2372        # Signature can be seen on transcript page
2373        self.assertTrue(
2374            'Electronically signed by Ruth Gordon (mrtranscript) on'
2375            in self.browser.contents)
2376
2377    def test_update_coursetickets(self):
2378        IWorkflowState(self.student).setState('school fee paid')
2379        studylevel = createObject(u'waeup.StudentStudyLevel')
2380        studylevel.level = 100
2381        studylevel.level_session = 2015
2382        self.student['studycourse'].entry_mode = 'ug_ft'
2383        self.student['studycourse'].addStudentStudyLevel(
2384            self.certificate, studylevel)
2385        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
2386        self.browser.open(
2387            'http://localhost/app/faculties/fac1/dep1/courses/COURSE1/')
2388        self.assertFalse(
2389            'Update session 2015/2016 credits' in self.browser.contents)
2390        self.app['configuration'].current_academic_session = 2015
2391        self.browser.open(
2392            'http://localhost/app/faculties/fac1/dep1/courses/COURSE1/')
2393        self.browser.getLink("Update session 2015/2016 credits").click()
2394        self.assertTrue(
2395            'No course ticket found.' in self.browser.contents)
2396        logfile = os.path.join(
2397            self.app['datacenter'].storage, 'logs', 'main.log')
2398        logcontent = open(logfile).read()
2399        self.assertTrue(
2400            'zope.mgr - browser.pages.UpdateCourseTicketsView - '
2401            'course tickets updated: COURSE1' in logcontent)
2402        studylevel['COURSE1'].credits = 12
2403        self.browser.getLink("Update session 2015/2016 credits").click()
2404        self.assertTrue(
2405            'No course ticket found.' in self.browser.contents)
2406        studylevel.level_session = 2015
2407        self.student['studycourse'].current_session = 2015
2408        self.browser.getLink("Update session 2015/2016 credits").click()
2409        self.assertTrue(
2410            '1 course ticket(s) updated.' in self.browser.contents)
2411        logfile = os.path.join(
2412            self.app['datacenter'].storage, 'logs', 'students.log')
2413        logcontent = open(logfile).read()
2414        self.assertTrue(
2415            'zope.mgr - students.utils.StudentsUtils - '
2416            'K1000000 100/COURSE1 credits updated (10->12)' in logcontent)
2417        return
2418
2419
2420class StudentUITests(StudentsFullSetup):
2421    # Tests for Student class views and pages
2422
2423    def test_student_change_password(self):
2424        # Students can change the password
2425        self.student.personal_updated = datetime.utcnow()
2426        self.browser.open(self.login_path)
2427        self.browser.getControl(name="form.login").value = self.student_id
2428        self.browser.getControl(name="form.password").value = 'spwd'
2429        self.browser.getControl("Login").click()
2430        self.assertEqual(self.browser.url, self.student_path)
2431        self.assertTrue('You logged in' in self.browser.contents)
2432        # Change password
2433        self.browser.getLink("Change password").click()
2434        self.browser.getControl(name="change_password").value = 'pw'
2435        self.browser.getControl(
2436            name="change_password_repeat").value = 'pw'
2437        self.browser.getControl("Save").click()
2438        self.assertTrue('Password must have at least' in self.browser.contents)
2439        self.browser.getControl(name="change_password").value = 'new_password'
2440        self.browser.getControl(
2441            name="change_password_repeat").value = 'new_passssword'
2442        self.browser.getControl("Save").click()
2443        self.assertTrue('Passwords do not match' in self.browser.contents)
2444        self.browser.getControl(name="change_password").value = 'new_password'
2445        self.browser.getControl(
2446            name="change_password_repeat").value = 'new_password'
2447        self.browser.getControl("Save").click()
2448        self.assertTrue('Password changed' in self.browser.contents)
2449        # We are still logged in. Changing the password hasn't thrown us out.
2450        self.browser.getLink("Base Data").click()
2451        self.assertEqual(self.browser.url, self.student_path)
2452        # We can logout
2453        self.browser.getLink("Logout").click()
2454        self.assertTrue('You have been logged out' in self.browser.contents)
2455        self.assertEqual(self.browser.url, 'http://localhost/app/index')
2456        # We can login again with the new password
2457        self.browser.getLink("Login").click()
2458        self.browser.open(self.login_path)
2459        self.browser.getControl(name="form.login").value = self.student_id
2460        self.browser.getControl(name="form.password").value = 'new_password'
2461        self.browser.getControl("Login").click()
2462        self.assertEqual(self.browser.url, self.student_path)
2463        self.assertTrue('You logged in' in self.browser.contents)
2464        return
2465
2466    def test_forbidden_name(self):
2467        self.student.lastname = u'<TAG>Tester</TAG>'
2468        self.browser.open(self.login_path)
2469        self.browser.getControl(name="form.login").value = self.student_id
2470        self.browser.getControl(name="form.password").value = 'spwd'
2471        self.browser.getControl("Login").click()
2472        self.assertTrue('XXX: Base Data' in self.browser.contents)
2473        self.assertTrue('&lt;TAG&gt;Tester&lt;/TAG&gt;' in self.browser.contents)
2474        self.assertFalse('<TAG>Tester</TAG>' in self.browser.contents)
2475        return
2476
2477    def test_setpassword(self):
2478        # Set password for first-time access
2479        student = Student()
2480        student.reg_number = u'123456'
2481        student.firstname = u'Klaus'
2482        student.lastname = u'Tester'
2483        self.app['students'].addStudent(student)
2484        setpassword_path = 'http://localhost/app/setpassword'
2485        student_path = 'http://localhost/app/students/%s' % student.student_id
2486        self.browser.open(setpassword_path)
2487        self.browser.getControl(name="ac_series").value = self.existing_pwdseries
2488        self.browser.getControl(name="ac_number").value = self.existing_pwdnumber
2489        self.browser.getControl(name="reg_number").value = '223456'
2490        self.browser.getControl("Set").click()
2491        self.assertMatches('...No student found...',
2492                           self.browser.contents)
2493        self.browser.getControl(name="reg_number").value = '123456'
2494        self.browser.getControl(name="ac_number").value = '999999'
2495        self.browser.getControl("Set").click()
2496        self.assertMatches('...Access code is invalid...',
2497                           self.browser.contents)
2498        self.browser.getControl(name="ac_number").value = self.existing_pwdnumber
2499        self.browser.getControl("Set").click()
2500        self.assertMatches('...Password has been set. Your Student Id is...',
2501                           self.browser.contents)
2502        self.browser.getControl("Set").click()
2503        self.assertMatches(
2504            '...Password has already been set. Your Student Id is...',
2505            self.browser.contents)
2506        existing_pwdpin = self.pwdpins[1]
2507        parts = existing_pwdpin.split('-')[1:]
2508        existing_pwdseries, existing_pwdnumber = parts
2509        self.browser.getControl(name="ac_series").value = existing_pwdseries
2510        self.browser.getControl(name="ac_number").value = existing_pwdnumber
2511        self.browser.getControl(name="reg_number").value = '123456'
2512        self.browser.getControl("Set").click()
2513        self.assertMatches(
2514            '...You are using the wrong Access Code...',
2515            self.browser.contents)
2516        # The student can login with the new credentials
2517        self.browser.open(self.login_path)
2518        self.browser.getControl(name="form.login").value = student.student_id
2519        self.browser.getControl(
2520            name="form.password").value = self.existing_pwdnumber
2521        self.browser.getControl("Login").click()
2522        self.assertEqual(self.browser.url, student_path)
2523        self.assertTrue('You logged in' in self.browser.contents)
2524        return
2525
2526    def test_student_login(self):
2527        # Student cant login if their password is not set
2528        self.student.password = None
2529        self.browser.open(self.login_path)
2530        self.browser.getControl(name="form.login").value = self.student_id
2531        self.browser.getControl(name="form.password").value = 'spwd'
2532        self.browser.getControl("Login").click()
2533        self.assertTrue(
2534            'You entered invalid credentials.' in self.browser.contents)
2535        # We set the password again
2536        IUserAccount(
2537            self.app['students'][self.student_id]).setPassword('spwd')
2538        # Students can't login if their account is suspended/deactivated
2539        self.student.suspended = True
2540        self.browser.open(self.login_path)
2541        self.browser.getControl(name="form.login").value = self.student_id
2542        self.browser.getControl(name="form.password").value = 'spwd'
2543        self.browser.getControl("Login").click()
2544        self.assertMatches(
2545            '...<div class="alert alert-warning">'
2546            'Your account has been deactivated.</div>...', self.browser.contents)
2547        # If suspended_comment is set this message will be flashed instead
2548        self.student.suspended_comment = u'Aetsch baetsch!'
2549        self.browser.getControl(name="form.login").value = self.student_id
2550        self.browser.getControl(name="form.password").value = 'spwd'
2551        self.browser.getControl("Login").click()
2552        self.assertMatches(
2553            '...<div class="alert alert-warning">Aetsch baetsch!</div>...',
2554            self.browser.contents)
2555        self.student.suspended = False
2556        # Students can't login if a temporary password has been set and
2557        # is not expired
2558        self.app['students'][self.student_id].setTempPassword(
2559            'anybody', 'temp_spwd')
2560        self.browser.open(self.login_path)
2561        self.browser.getControl(name="form.login").value = self.student_id
2562        self.browser.getControl(name="form.password").value = 'spwd'
2563        self.browser.getControl("Login").click()
2564        self.assertMatches(
2565            '...Your account has been temporarily deactivated...',
2566            self.browser.contents)
2567        # The student can login with the temporary password
2568        self.browser.open(self.login_path)
2569        self.browser.getControl(name="form.login").value = self.student_id
2570        self.browser.getControl(name="form.password").value = 'temp_spwd'
2571        self.browser.getControl("Login").click()
2572        self.assertMatches(
2573            '...You logged in...', self.browser.contents)
2574        # Student can view the base data
2575        self.browser.open(self.student_path)
2576        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2577        self.assertEqual(self.browser.url, self.student_path)
2578        # When the password expires ...
2579        delta = timedelta(minutes=11)
2580        self.app['students'][self.student_id].temp_password[
2581            'timestamp'] = datetime.utcnow() - delta
2582        self.app['students'][self.student_id]._p_changed = True
2583        # ... the student will be automatically logged out
2584        self.assertRaises(
2585            Unauthorized, self.browser.open, self.student_path)
2586        # Then the student can login with the original password
2587        self.browser.open(self.login_path)
2588        self.browser.getControl(name="form.login").value = self.student_id
2589        self.browser.getControl(name="form.password").value = 'spwd'
2590        self.browser.getControl("Login").click()
2591        self.assertMatches(
2592            '...You logged in...', self.browser.contents)
2593
2594    def test_maintenance_mode(self):
2595        config = grok.getSite()['configuration']
2596        self.browser.open(self.login_path)
2597        self.browser.getControl(name="form.login").value = self.student_id
2598        self.browser.getControl(name="form.password").value = 'spwd'
2599        self.browser.getControl("Login").click()
2600        # Student logged in.
2601        self.assertTrue('You logged in' in self.browser.contents)
2602        self.assertTrue("Anna Tester" in self.browser.contents)
2603        # If maintenance mode is enabled, student is immediately logged out.
2604        config.maintmode_enabled_by = u'any_user'
2605        self.assertRaises(
2606            Unauthorized, self.browser.open, 'http://localhost/app/faculties')
2607        self.browser.open('http://localhost/app/login')
2608        self.assertTrue('The portal is in maintenance mode' in self.browser.contents)
2609        # Student really can't login if maintenance mode is enabled.
2610        self.browser.open(self.login_path)
2611        self.browser.getControl(name="form.login").value = self.student_id
2612        self.browser.getControl(name="form.password").value = 'spwd'
2613        self.browser.getControl("Login").click()
2614        # A second warning is raised.
2615        self.assertTrue(
2616            'The portal is in maintenance mode. You can\'t login!'
2617            in self.browser.contents)
2618        return
2619
2620    def test_student_clearance(self):
2621        # Student cant login if their password is not set
2622        IWorkflowInfo(self.student).fireTransition('admit')
2623        self.browser.open(self.login_path)
2624        self.browser.getControl(name="form.login").value = self.student_id
2625        self.browser.getControl(name="form.password").value = 'spwd'
2626        self.browser.getControl("Login").click()
2627        self.assertMatches(
2628            '...You logged in...', self.browser.contents)
2629        # Admitted student can upload a passport picture
2630        self.browser.open(self.student_path + '/change_portrait')
2631        ctrl = self.browser.getControl(name='passportuploadedit')
2632        file_obj = open(SAMPLE_IMAGE, 'rb')
2633        file_ctrl = ctrl.mech_control
2634        file_ctrl.add_file(file_obj, filename='my_photo.jpg')
2635        self.browser.getControl(
2636            name='upload_passportuploadedit').click()
2637        self.assertTrue(
2638            'src="http://localhost/app/students/K1000000/passport.jpg"'
2639            in self.browser.contents)
2640        # Students can open admission letter
2641        self.browser.getLink("Base Data").click()
2642        self.browser.getLink("Download admission letter").click()
2643        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2644        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2645        path = os.path.join(samples_dir(), 'admission_slip.pdf')
2646        open(path, 'wb').write(self.browser.contents)
2647        print "Sample PDF admission_slip.pdf written to %s" % path
2648        # Student can view the clearance data
2649        self.browser.open(self.student_path)
2650        self.browser.getLink("Clearance Data").click()
2651        # Student can't open clearance edit form before starting clearance
2652        self.browser.open(self.student_path + '/cedit')
2653        self.assertMatches('...The requested form is locked...',
2654                           self.browser.contents)
2655        self.browser.getLink("Clearance Data").click()
2656        self.browser.getLink("Start clearance").click()
2657        self.student.phone = None
2658        # Uups, we forgot to fill the phone fields
2659        self.browser.getControl("Start clearance").click()
2660        self.assertMatches('...Phone number is missing...',
2661                           self.browser.contents)
2662        self.browser.open(self.student_path + '/edit_base')
2663        self.browser.getControl(name="form.phone.ext").value = '12345'
2664        self.browser.getControl("Save").click()
2665        self.browser.open(self.student_path + '/start_clearance')
2666        self.browser.getControl(name="ac_series").value = '3'
2667        self.browser.getControl(name="ac_number").value = '4444444'
2668        self.browser.getControl("Start clearance now").click()
2669        self.assertMatches('...Activation code is invalid...',
2670                           self.browser.contents)
2671        self.browser.getControl(name="ac_series").value = self.existing_clrseries
2672        self.browser.getControl(name="ac_number").value = self.existing_clrnumber
2673        # Owner is Hans Wurst, AC can't be invalidated
2674        self.browser.getControl("Start clearance now").click()
2675        self.assertMatches('...You are not the owner of this access code...',
2676                           self.browser.contents)
2677        # Set the correct owner
2678        self.existing_clrac.owner = self.student_id
2679        # clr_code might be set (and thus returns None) due importing
2680        # an empty clr_code column.
2681        self.student.clr_code = None
2682        self.browser.getControl("Start clearance now").click()
2683        self.assertMatches('...Clearance process has been started...',
2684                           self.browser.contents)
2685        self.browser.getControl(name="form.date_of_birth").value = '09/10/1961'
2686        self.browser.getControl("Save", index=0).click()
2687        # Student can view the clearance data
2688        self.browser.getLink("Clearance Data").click()
2689        # and go back to the edit form
2690        self.browser.getLink("Edit").click()
2691        # Students can upload documents
2692        ctrl = self.browser.getControl(name='birthcertificateupload')
2693        file_obj = open(SAMPLE_IMAGE, 'rb')
2694        file_ctrl = ctrl.mech_control
2695        file_ctrl.add_file(file_obj, filename='my_birth_certificate.jpg')
2696        self.browser.getControl(
2697            name='upload_birthcertificateupload').click()
2698        self.assertTrue(
2699            'href="http://localhost/app/students/K1000000/birth_certificate"'
2700            in self.browser.contents)
2701        # Students can open clearance slip
2702        self.browser.getLink("View").click()
2703        self.browser.getLink("Download clearance slip").click()
2704        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2705        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2706        # Students can request clearance
2707        self.browser.open(self.edit_clearance_path)
2708        self.browser.getControl("Save and request clearance").click()
2709        self.browser.getControl(name="ac_series").value = self.existing_clrseries
2710        self.browser.getControl(name="ac_number").value = self.existing_clrnumber
2711        self.browser.getControl("Request clearance now").click()
2712        self.assertMatches('...Clearance has been requested...',
2713                           self.browser.contents)
2714        # Student can't reopen clearance form after requesting clearance
2715        self.browser.open(self.student_path + '/cedit')
2716        self.assertMatches('...The requested form is locked...',
2717                           self.browser.contents)
2718
2719    def test_student_course_registration(self):
2720        # Student cant login if their password is not set
2721        IWorkflowInfo(self.student).fireTransition('admit')
2722        self.browser.open(self.login_path)
2723        self.browser.getControl(name="form.login").value = self.student_id
2724        self.browser.getControl(name="form.password").value = 'spwd'
2725        self.browser.getControl("Login").click()
2726        # Student can't add study level if not in state 'school fee paid'
2727        self.browser.open(self.student_path + '/studycourse/add')
2728        self.assertMatches('...The requested form is locked...',
2729                           self.browser.contents)
2730        # ... and must be transferred first
2731        IWorkflowState(self.student).setState('school fee paid')
2732        # Now students can add the current study level
2733        self.browser.getLink("Study Course").click()
2734        self.student['studycourse'].current_level = None
2735        self.browser.getLink("Add course list").click()
2736        self.assertMatches('...Your data are incomplete...',
2737                           self.browser.contents)
2738        self.student['studycourse'].current_level = 100
2739        self.browser.getLink("Add course list").click()
2740        self.assertMatches('...Add current level 100 (Year 1)...',
2741                           self.browser.contents)
2742        self.browser.getControl("Create course list now").click()
2743        # A level with one course ticket was created
2744        self.assertEqual(self.student['studycourse']['100'].number_of_tickets, 1)
2745        self.browser.getLink("100").click()
2746        self.browser.getLink("Edit course list").click()
2747        self.browser.getLink("here").click()
2748        self.browser.getControl(name="form.course").value = ['COURSE1']
2749        self.browser.getControl("Add course ticket").click()
2750        self.assertMatches('...The ticket exists...',
2751                           self.browser.contents)
2752        self.student['studycourse'].current_level = 200
2753        self.browser.getLink("Study Course").click()
2754        self.browser.getLink("Add course list").click()
2755        self.assertMatches('...Add current level 200 (Year 2)...',
2756                           self.browser.contents)
2757        self.browser.getControl("Create course list now").click()
2758        self.browser.getLink("200").click()
2759        self.browser.getLink("Edit course list").click()
2760        self.browser.getLink("here").click()
2761        self.browser.getControl(name="form.course").value = ['COURSE1']
2762        self.course.credits = 100
2763        self.browser.getControl("Add course ticket").click()
2764        self.assertMatches(
2765            '...Maximum credits exceeded...', self.browser.contents)
2766        self.course.credits = 10
2767        self.browser.getControl("Add course ticket").click()
2768        self.assertMatches('...The ticket exists...',
2769                           self.browser.contents)
2770        # Indeed the ticket exists as carry-over course from level 100
2771        # since its score was 0
2772        self.assertTrue(
2773            self.student['studycourse']['200']['COURSE1'].carry_over is True)
2774        self.assertTrue(
2775            self.student['studycourse']['200']['COURSE1'].course_category is None)
2776        # Students can open the pdf course registration slip
2777        self.browser.open(self.student_path + '/studycourse/200')
2778        self.browser.getLink("Download course registration slip").click()
2779        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2780        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2781        path = os.path.join(samples_dir(), 'course_registration_slip.pdf')
2782        open(path, 'wb').write(self.browser.contents)
2783        print "Sample PDF course_registration_slip.pdf written to %s" % path
2784        # Students can remove course tickets
2785        self.browser.open(self.student_path + '/studycourse/200/edit')
2786        self.browser.getControl("Remove selected", index=0).click()
2787        self.assertTrue('No ticket selected' in self.browser.contents)
2788        # No ticket can be selected since the carry-over course is a core course
2789        self.assertRaises(
2790            LookupError, self.browser.getControl, name='val_id')
2791        self.student['studycourse']['200']['COURSE1'].mandatory = False
2792        self.browser.open(self.student_path + '/studycourse/200/edit')
2793        # Course list can't be registered if total_credits exceeds max_credits
2794        self.student['studycourse']['200']['COURSE1'].credits = 60
2795        self.browser.getControl("Register course list").click()
2796        self.assertTrue('Maximum credits exceeded' in self.browser.contents)
2797        # Student can now remove the ticket
2798        ctrl = self.browser.getControl(name='val_id')
2799        ctrl.getControl(value='COURSE1').selected = True
2800        self.browser.getControl("Remove selected", index=0).click()
2801        self.assertTrue('Successfully removed' in self.browser.contents)
2802        # Removing course tickets is properly logged
2803        logfile = os.path.join(
2804            self.app['datacenter'].storage, 'logs', 'students.log')
2805        logcontent = open(logfile).read()
2806        self.assertTrue('K1000000 - students.browser.StudyLevelEditFormPage '
2807        '- K1000000 - level 200 - removed: COURSE1' in logcontent)
2808        # They can add the same ticket using the edit page directly.
2809        # We can do the same by adding the course on the manage page directly
2810        self.browser.getControl(name="course").value = 'COURSE1'
2811        self.browser.getControl("Add course ticket").click()
2812        # Adding course tickets is logged
2813        logfile = os.path.join(
2814            self.app['datacenter'].storage, 'logs', 'students.log')
2815        logcontent = open(logfile).read()
2816        self.assertTrue('K1000000 - students.browser.StudyLevelEditFormPage - '
2817            'K1000000 - level 200 - added: COURSE1|200|2004' in logcontent)
2818        # Course list can be registered
2819        self.browser.getControl("Register course list").click()
2820        self.assertTrue('Course list has been registered' in self.browser.contents)
2821        self.assertEqual(self.student.state, 'courses registered')
2822        # Course list can be unregistered
2823        self.browser.getLink("Unregister courses").click()
2824        self.assertEqual(self.student.state, 'school fee paid')
2825        self.assertTrue('Course list has been unregistered' in self.browser.contents)
2826        self.browser.open(self.student_path + '/studycourse/200/unregister_courses')
2827        self.assertTrue('You are in the wrong state' in self.browser.contents)
2828        # Students can view the transcript
2829        #self.browser.open(self.studycourse_path)
2830        #self.browser.getLink("Transcript").click()
2831        #self.browser.getLink("Academic Transcript").click()
2832        #self.assertEqual(self.browser.headers['Status'], '200 Ok')
2833        #self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2834        return
2835
2836    def test_student_ticket_update(self):
2837        IWorkflowState(self.student).setState('school fee paid')
2838        self.student['studycourse'].current_level = 100
2839        self.browser.open(self.login_path)
2840        self.browser.getControl(name="form.login").value = self.student_id
2841        self.browser.getControl(name="form.password").value = 'spwd'
2842        self.browser.getControl("Login").click()
2843        # Now students can add the current study level
2844        self.browser.getLink("Study Course").click()
2845        self.browser.getLink("Add course list").click()
2846        self.assertMatches('...Add current level 100 (Year 1)...',
2847                           self.browser.contents)
2848        self.browser.getControl("Create course list now").click()
2849        # A level with one course ticket was created
2850        self.assertEqual(
2851            self.student['studycourse']['100'].number_of_tickets, 1)
2852        self.browser.getLink("100").click()
2853        self.assertTrue('<td>Unnamed Course</td>' in self.browser.contents)
2854        self.browser.getLink("Edit course list").click()
2855        self.browser.getControl("Update all tickets").click()
2856        self.assertTrue('All course tickets updated.' in self.browser.contents)
2857        # ... nothing has changed
2858        self.assertTrue('<td>Unnamed Course</td>' in self.browser.contents)
2859        # We change the title of the course
2860        self.course.title = u'New Title'
2861        self.browser.getControl("Update all tickets").click()
2862        self.assertTrue('<td>New Title</td>' in self.browser.contents)
2863        # We remove the course
2864        del self.app['faculties']['fac1']['dep1'].courses['COURSE1']
2865        self.browser.getControl("Update all tickets").click()
2866        self.assertTrue(' <td>New Title (course cancelled)</td>'
2867            in self.browser.contents)
2868        # Course ticket invalidation has been logged
2869        logfile = os.path.join(
2870            self.app['datacenter'].storage, 'logs', 'students.log')
2871        logcontent = open(logfile).read()
2872        self.assertTrue(
2873            'K1000000 - students.browser.StudyLevelEditFormPage - '
2874            'K1000000 - level 100 - course tickets invalidated: COURSE1'
2875            in logcontent)
2876        return
2877
2878    def test_student_course_already_passed(self):
2879        IWorkflowState(self.student).setState('school fee paid')
2880        self.student['studycourse'].current_level = 100
2881        self.browser.open(self.login_path)
2882        self.browser.getControl(name="form.login").value = self.student_id
2883        self.browser.getControl(name="form.password").value = 'spwd'
2884        self.browser.getControl("Login").click()
2885        # Now students can add the current study level
2886        self.browser.getLink("Study Course").click()
2887        self.browser.getLink("Add course list").click()
2888        self.assertMatches('...Add current level 100 (Year 1)...',
2889                           self.browser.contents)
2890        self.browser.getControl("Create course list now").click()
2891        # A level with one course ticket was created
2892        self.assertEqual(self.student['studycourse']['100'].number_of_tickets, 1)
2893        # We set the score above the passmark
2894        self.student['studycourse']['100'][
2895            'COURSE1'].score = self.student['studycourse']['100'][
2896                'COURSE1'].passmark + 1
2897        # We add a second level
2898        self.student['studycourse'].current_level = 200
2899        self.browser.getLink("Study Course").click()
2900        self.browser.getLink("Add course list").click()
2901        self.assertMatches('...Add current level 200 (Year 2)...',
2902                           self.browser.contents)
2903        self.browser.getControl("Create course list now").click()
2904        self.browser.getLink("200").click()
2905        self.browser.getLink("Edit course list").click()
2906        self.browser.getLink("here").click()
2907        self.browser.getControl(name="form.course").value = ['COURSE1']
2908        self.browser.getControl("Add course ticket").click()
2909        self.assertTrue(
2910            'Course has already been passed at previous level'
2911            in self.browser.contents)
2912        self.assertEqual(self.student['studycourse']['200'].number_of_tickets, 0)
2913        # We set the score below the passmark
2914        self.student['studycourse']['100'][
2915            'COURSE1'].score = self.student['studycourse']['100'][
2916                'COURSE1'].passmark - 1
2917        self.browser.getControl("Add course ticket").click()
2918        self.assertTrue(
2919            'Successfully added COURSE1' in self.browser.contents)
2920        self.assertEqual(self.student['studycourse']['200'].number_of_tickets, 1)
2921        return
2922
2923    def test_student_course_registration_outstanding(self):
2924        self.course = createObject('waeup.Course')
2925        self.course.code = 'COURSE2'
2926        self.course.semester = 1
2927        self.course.credits = 45
2928        self.course.passmark = 40
2929        self.app['faculties']['fac1']['dep1'].courses.addCourse(
2930            self.course)
2931        IWorkflowState(self.student).setState('school fee paid')
2932        self.browser.open(self.login_path)
2933        self.browser.getControl(name="form.login").value = self.student_id
2934        self.browser.getControl(name="form.password").value = 'spwd'
2935        self.browser.getControl("Login").click()
2936        self.browser.open(self.student_path + '/studycourse/add')
2937        self.browser.getControl("Create course list now").click()
2938        self.assertEqual(self.student['studycourse']['100'].number_of_tickets, 1)
2939        self.student['studycourse'].current_level = 200
2940        self.browser.getLink("Study Course").click()
2941        self.browser.getLink("Add course list").click()
2942        self.assertMatches('...Add current level 200 (Year 2)...',
2943                           self.browser.contents)
2944        self.browser.getControl("Create course list now").click()
2945        self.browser.getLink("200").click()
2946        self.browser.getLink("Edit course list").click()
2947        self.browser.getLink("here").click()
2948        self.browser.getControl(name="form.course").value = ['COURSE2']
2949        self.browser.getControl("Add course ticket").click()
2950        # Carryover COURSE1 in level 200 already has 10 credits
2951        self.assertMatches(
2952            '...Maximum credits exceeded...', self.browser.contents)
2953        # If COURSE1 is outstanding, its credits won't be considered
2954        self.student['studycourse']['200']['COURSE1'].outstanding = True
2955        self.browser.getControl("Add course ticket").click()
2956        self.assertMatches(
2957            '...Successfully added COURSE2...', self.browser.contents)
2958        return
2959
2960    def test_postgraduate_student_access(self):
2961        self.certificate.study_mode = 'pg_ft'
2962        self.certificate.start_level = 999
2963        self.certificate.end_level = 999
2964        self.student['studycourse'].current_level = 999
2965        IWorkflowState(self.student).setState('school fee paid')
2966        self.browser.open(self.login_path)
2967        self.browser.getControl(name="form.login").value = self.student_id
2968        self.browser.getControl(name="form.password").value = 'spwd'
2969        self.browser.getControl("Login").click()
2970        self.assertTrue(
2971            'You logged in.' in self.browser.contents)
2972        # Now students can add the current study level
2973        self.browser.getLink("Study Course").click()
2974        self.browser.getLink("Add course list").click()
2975        self.assertMatches('...Add current level Postgraduate Level...',
2976                           self.browser.contents)
2977        self.browser.getControl("Create course list now").click()
2978        self.assertTrue("You successfully created a new course list"
2979            in self.browser.contents)
2980        # A level with one course ticket was created
2981        self.assertEqual(self.student['studycourse']['999'].number_of_tickets, 0)
2982        self.browser.getLink("Edit course list").click()
2983        self.browser.getLink("here").click()
2984        self.browser.getControl(name="form.course").value = ['COURSE1']
2985        self.browser.getControl("Add course ticket").click()
2986        self.assertMatches('...Successfully added COURSE1...',
2987                           self.browser.contents)
2988        # Postgraduate students can't register course lists
2989        self.browser.getControl("Register course list").click()
2990        self.assertTrue("your course list can't bee registered"
2991            in self.browser.contents)
2992        self.assertEqual(self.student.state, 'school fee paid')
2993        return
2994
2995    def test_student_clearance_wo_clrcode(self):
2996        IWorkflowState(self.student).setState('clearance started')
2997        self.browser.open(self.login_path)
2998        self.browser.getControl(name="form.login").value = self.student_id
2999        self.browser.getControl(name="form.password").value = 'spwd'
3000        self.browser.getControl("Login").click()
3001        self.browser.open(self.edit_clearance_path)
3002        self.browser.getControl(name="form.date_of_birth").value = '09/10/1961'
3003        self.browser.getControl("Save and request clearance").click()
3004        self.assertMatches('...Clearance has been requested...',
3005                           self.browser.contents)
3006
3007    def test_student_clearance_payment(self):
3008        # Login
3009        self.browser.open(self.login_path)
3010        self.browser.getControl(name="form.login").value = self.student_id
3011        self.browser.getControl(name="form.password").value = 'spwd'
3012        self.browser.getControl("Login").click()
3013
3014        # Students can add online clearance payment tickets
3015        self.browser.open(self.payments_path + '/addop')
3016        self.browser.getControl(name="form.p_category").value = ['clearance']
3017        self.browser.getControl("Create ticket").click()
3018        self.assertMatches('...ticket created...',
3019                           self.browser.contents)
3020
3021        # Students can't approve the payment
3022        self.assertEqual(len(self.app['accesscodes']['CLR-0']),0)
3023        ctrl = self.browser.getControl(name='val_id')
3024        value = ctrl.options[0]
3025        self.browser.getLink(value).click()
3026        payment_url = self.browser.url
3027        self.assertRaises(
3028            Unauthorized, self.browser.open, payment_url + '/approve')
3029        # In the base package they can 'use' a fake approval view.
3030        # XXX: I tried to use
3031        # self.student['payments'][value].approveStudentPayment() instead.
3032        # But this function fails in
3033        # w.k.accesscodes.accesscode.create_accesscode.
3034        # grok.getSite returns None in tests.
3035        self.browser.open(payment_url + '/fake_approve')
3036        self.assertMatches('...Payment approved...',
3037                          self.browser.contents)
3038        expected = '''...
3039        <td>
3040          <span>Paid</span>
3041        </td>...'''
3042        expected = '''...
3043        <td>
3044          <span>Paid</span>
3045        </td>...'''
3046        self.assertMatches(expected,self.browser.contents)
3047        payment_id = self.student['payments'].keys()[0]
3048        payment = self.student['payments'][payment_id]
3049        self.assertEqual(payment.p_state, 'paid')
3050        self.assertEqual(payment.r_amount_approved, 3456.0)
3051        self.assertEqual(payment.r_code, 'AP')
3052        self.assertEqual(payment.r_desc, u'Payment approved by Anna Tester')
3053        # The new CLR-0 pin has been created
3054        self.assertEqual(len(self.app['accesscodes']['CLR-0']),1)
3055        pin = self.app['accesscodes']['CLR-0'].keys()[0]
3056        ac = self.app['accesscodes']['CLR-0'][pin]
3057        self.assertEqual(ac.owner, self.student_id)
3058        self.assertEqual(ac.cost, 3456.0)
3059
3060        # Students can open the pdf payment slip
3061        self.browser.open(payment_url + '/payment_slip.pdf')
3062        self.assertEqual(self.browser.headers['Status'], '200 Ok')
3063        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
3064
3065        # The new CLR-0 pin can be used for starting clearance
3066        # but they have to upload a passport picture first
3067        # which is only possible in state admitted
3068        self.browser.open(self.student_path + '/change_portrait')
3069        self.assertMatches('...form is locked...',
3070                          self.browser.contents)
3071        IWorkflowInfo(self.student).fireTransition('admit')
3072        self.browser.open(self.student_path + '/change_portrait')
3073        image = open(SAMPLE_IMAGE, 'rb')
3074        ctrl = self.browser.getControl(name='passportuploadedit')
3075        file_ctrl = ctrl.mech_control
3076        file_ctrl.add_file(image, filename='my_photo.jpg')
3077        self.browser.getControl(
3078            name='upload_passportuploadedit').click()
3079        self.browser.open(self.student_path + '/start_clearance')
3080        parts = pin.split('-')[1:]
3081        clrseries, clrnumber = parts
3082        self.browser.getControl(name="ac_series").value = clrseries
3083        self.browser.getControl(name="ac_number").value = clrnumber
3084        self.browser.getControl("Start clearance now").click()
3085        self.assertMatches('...Clearance process has been started...',
3086                           self.browser.contents)
3087
3088    def test_student_schoolfee_payment(self):
3089        configuration = createObject('waeup.SessionConfiguration')
3090        configuration.academic_session = 2005
3091        self.app['configuration'].addSessionConfiguration(configuration)
3092        # Login
3093        self.browser.open(self.login_path)
3094        self.browser.getControl(name="form.login").value = self.student_id
3095        self.browser.getControl(name="form.password").value = 'spwd'
3096        self.browser.getControl("Login").click()
3097
3098        # Students can add online school fee payment tickets.
3099        IWorkflowState(self.student).setState('returning')
3100        self.browser.open(self.payments_path)
3101        self.assertRaises(
3102            LookupError, self.browser.getControl, name='val_id')
3103        self.browser.getLink("Add current session payment ticket").click()
3104        self.browser.getControl(name="form.p_category").value = ['schoolfee']
3105        self.browser.getControl("Create ticket").click()
3106        self.assertMatches('...ticket created...',
3107                           self.browser.contents)
3108        ctrl = self.browser.getControl(name='val_id')
3109        value = ctrl.options[0]
3110        self.browser.getLink(value).click()
3111        self.assertMatches('...Amount Authorized...',
3112                           self.browser.contents)
3113        self.assertEqual(self.student['payments'][value].amount_auth, 20000.0)
3114        # Payment session and will be calculated as defined
3115        # in w.k.students.utils because we set changed the state
3116        # to returning
3117        self.assertEqual(self.student['payments'][value].p_session, 2005)
3118        self.assertEqual(self.student['payments'][value].p_level, 200)
3119
3120        # Student is the payer of the payment ticket.
3121        payer = IPayer(self.student['payments'][value])
3122        self.assertEqual(payer.display_fullname, 'Anna Tester')
3123        self.assertEqual(payer.id, self.student_id)
3124        self.assertEqual(payer.faculty, 'fac1')
3125        self.assertEqual(payer.department, 'dep1')
3126
3127        # We simulate the approval
3128        self.assertEqual(len(self.app['accesscodes']['SFE-0']),0)
3129        self.browser.open(self.browser.url + '/fake_approve')
3130        self.assertMatches('...Payment approved...',
3131                          self.browser.contents)
3132
3133        ## The new SFE-0 pin can be used for starting new session
3134        #self.browser.open(self.studycourse_path)
3135        #self.browser.getLink('Start new session').click()
3136        #pin = self.app['accesscodes']['SFE-0'].keys()[0]
3137        #parts = pin.split('-')[1:]
3138        #sfeseries, sfenumber = parts
3139        #self.browser.getControl(name="ac_series").value = sfeseries
3140        #self.browser.getControl(name="ac_number").value = sfenumber
3141        #self.browser.getControl("Start now").click()
3142        #self.assertMatches('...Session started...',
3143        #                   self.browser.contents)
3144
3145        self.assertTrue(self.student.state == 'school fee paid')
3146        return
3147
3148    def test_student_bedallocation_payment(self):
3149        # Login
3150        self.browser.open(self.login_path)
3151        self.browser.getControl(name="form.login").value = self.student_id
3152        self.browser.getControl(name="form.password").value = 'spwd'
3153        self.browser.getControl("Login").click()
3154        self.browser.open(self.payments_path)
3155        self.browser.open(self.payments_path + '/addop')
3156        self.browser.getControl(name="form.p_category").value = ['bed_allocation']
3157        self.browser.getControl("Create ticket").click()
3158        self.assertMatches('...ticket created...',
3159                           self.browser.contents)
3160        # Students can remove only online payment tickets which have
3161        # not received a valid callback
3162        self.browser.open(self.payments_path)
3163        ctrl = self.browser.getControl(name='val_id')
3164        value = ctrl.options[0]
3165        ctrl.getControl(value=value).selected = True
3166        self.browser.getControl("Remove selected", index=0).click()
3167        self.assertTrue('Successfully removed' in self.browser.contents)
3168
3169    def test_student_maintenance_payment(self):
3170        # Login
3171        self.browser.open(self.login_path)
3172        self.browser.getControl(name="form.login").value = self.student_id
3173        self.browser.getControl(name="form.password").value = 'spwd'
3174        self.browser.getControl("Login").click()
3175        self.browser.open(self.payments_path)
3176        self.browser.open(self.payments_path + '/addop')
3177        self.browser.getControl(name="form.p_category").value = ['hostel_maintenance']
3178        self.browser.getControl("Create ticket").click()
3179        self.assertMatches('...You have not yet booked accommodation...',
3180                           self.browser.contents)
3181        # We continue this test in test_student_accommodation
3182
3183    def test_student_previous_payments(self):
3184        configuration = createObject('waeup.SessionConfiguration')
3185        configuration.academic_session = 2000
3186        configuration.clearance_fee = 3456.0
3187        configuration.booking_fee = 123.4
3188        self.app['configuration'].addSessionConfiguration(configuration)
3189        configuration2 = createObject('waeup.SessionConfiguration')
3190        configuration2.academic_session = 2003
3191        configuration2.clearance_fee = 3456.0
3192        configuration2.booking_fee = 123.4
3193        self.app['configuration'].addSessionConfiguration(configuration2)
3194        configuration3 = createObject('waeup.SessionConfiguration')
3195        configuration3.academic_session = 2005
3196        configuration3.clearance_fee = 3456.0
3197        configuration3.booking_fee = 123.4
3198        self.app['configuration'].addSessionConfiguration(configuration3)
3199        self.student['studycourse'].entry_session = 2002
3200
3201        # Login
3202        self.browser.open(self.login_path)
3203        self.browser.getControl(name="form.login").value = self.student_id
3204        self.browser.getControl(name="form.password").value = 'spwd'
3205        self.browser.getControl("Login").click()
3206
3207        # Students can add previous school fee payment tickets in any state.
3208        IWorkflowState(self.student).setState('courses registered')
3209        self.browser.open(self.payments_path)
3210        self.browser.getLink("Add previous session payment ticket").click()
3211
3212        # Previous session payment form is provided
3213        self.assertEqual(self.student.current_session, 2004)
3214        self.browser.getControl(name="form.p_category").value = ['schoolfee']
3215        self.browser.getControl(name="form.p_session").value = ['2000']
3216        self.browser.getControl(name="form.p_level").value = ['300']
3217        self.browser.getControl("Create ticket").click()
3218        self.assertMatches('...The previous session must not fall below...',
3219                           self.browser.contents)
3220        self.browser.getControl(name="form.p_category").value = ['schoolfee']
3221        self.browser.getControl(name="form.p_session").value = ['2005']
3222        self.browser.getControl(name="form.p_level").value = ['300']
3223        self.browser.getControl("Create ticket").click()
3224        self.assertMatches('...This is not a previous session...',
3225                           self.browser.contents)
3226
3227        # Students can pay current session school fee.
3228        self.browser.getControl(name="form.p_category").value = ['schoolfee']
3229        self.browser.getControl(name="form.p_session").value = ['2004']
3230        self.browser.getControl(name="form.p_level").value = ['300']
3231        self.browser.getControl("Create ticket").click()
3232        self.assertMatches('...ticket created...',
3233                           self.browser.contents)
3234        ctrl = self.browser.getControl(name='val_id')
3235        value = ctrl.options[0]
3236        self.browser.getLink(value).click()
3237        self.assertMatches('...Amount Authorized...',
3238                           self.browser.contents)
3239        self.assertEqual(self.student['payments'][value].amount_auth, 20000.0)
3240
3241        # Ticket creation is logged.
3242        logfile = os.path.join(
3243            self.app['datacenter'].storage, 'logs', 'students.log')
3244        logcontent = open(logfile).read()
3245        self.assertTrue(
3246            'K1000000 - students.browser.PreviousPaymentAddFormPage - '
3247            'K1000000 - added: %s' % value
3248            in logcontent)
3249
3250        # Payment session is properly set
3251        self.assertEqual(self.student['payments'][value].p_session, 2004)
3252        self.assertEqual(self.student['payments'][value].p_level, 300)
3253
3254        # We simulate the approval
3255        self.browser.open(self.browser.url + '/fake_approve')
3256        self.assertMatches('...Payment approved...',
3257                          self.browser.contents)
3258
3259        # No AC has been created
3260        self.assertEqual(len(self.app['accesscodes']['SFE-0'].keys()), 0)
3261        self.assertTrue(self.student['payments'][value].ac is None)
3262
3263        # Current payment flag is set False
3264        self.assertFalse(self.student['payments'][value].p_current)
3265
3266        # Button and form are not available for students who are in
3267        # states up to cleared
3268        self.student['studycourse'].entry_session = 2004
3269        IWorkflowState(self.student).setState('cleared')
3270        self.browser.open(self.payments_path)
3271        self.assertFalse(
3272            "Add previous session payment ticket" in self.browser.contents)
3273        self.browser.open(self.payments_path + '/addpp')
3274        self.assertTrue(
3275            "No previous payment to be made" in self.browser.contents)
3276        return
3277
3278    def test_postgraduate_student_payments(self):
3279        configuration = createObject('waeup.SessionConfiguration')
3280        configuration.academic_session = 2005
3281        self.app['configuration'].addSessionConfiguration(configuration)
3282        self.certificate.study_mode = 'pg_ft'
3283        self.certificate.start_level = 999
3284        self.certificate.end_level = 999
3285        self.student['studycourse'].current_level = 999
3286        # Login
3287        self.browser.open(self.login_path)
3288        self.browser.getControl(name="form.login").value = self.student_id
3289        self.browser.getControl(name="form.password").value = 'spwd'
3290        self.browser.getControl("Login").click()
3291        # Students can add online school fee payment tickets.
3292        IWorkflowState(self.student).setState('cleared')
3293        self.browser.open(self.payments_path)
3294        self.browser.getLink("Add current session payment ticket").click()
3295        self.browser.getControl(name="form.p_category").value = ['schoolfee']
3296        self.browser.getControl("Create ticket").click()
3297        self.assertMatches('...ticket created...',
3298                           self.browser.contents)
3299        ctrl = self.browser.getControl(name='val_id')
3300        value = ctrl.options[0]
3301        self.browser.getLink(value).click()
3302        self.assertMatches('...Amount Authorized...',
3303                           self.browser.contents)
3304        # Payment session and level are current ones.
3305        # Postgrads have to pay school_fee_1.
3306        self.assertEqual(self.student['payments'][value].amount_auth, 40000.0)
3307        self.assertEqual(self.student['payments'][value].p_session, 2004)
3308        self.assertEqual(self.student['payments'][value].p_level, 999)
3309
3310        # We simulate the approval
3311        self.assertEqual(len(self.app['accesscodes']['SFE-0']),0)
3312        self.browser.open(self.browser.url + '/fake_approve')
3313        self.assertMatches('...Payment approved...',
3314                          self.browser.contents)
3315
3316        ## The new SFE-0 pin can be used for starting session
3317        #self.browser.open(self.studycourse_path)
3318        #self.browser.getLink('Start new session').click()
3319        #pin = self.app['accesscodes']['SFE-0'].keys()[0]
3320        #parts = pin.split('-')[1:]
3321        #sfeseries, sfenumber = parts
3322        #self.browser.getControl(name="ac_series").value = sfeseries
3323        #self.browser.getControl(name="ac_number").value = sfenumber
3324        #self.browser.getControl("Start now").click()
3325        #self.assertMatches('...Session started...',
3326        #                   self.browser.contents)
3327
3328        self.assertTrue(self.student.state == 'school fee paid')
3329
3330        # Postgrad students do not need to register courses the
3331        # can just pay for the next session.
3332        self.browser.open(self.payments_path)
3333        # Remove first payment to be sure that we access the right ticket
3334        del self.student['payments'][value]
3335        self.browser.getLink("Add current session payment ticket").click()
3336        self.browser.getControl(name="form.p_category").value = ['schoolfee']
3337        self.browser.getControl("Create ticket").click()
3338        ctrl = self.browser.getControl(name='val_id')
3339        value = ctrl.options[0]
3340        self.browser.getLink(value).click()
3341        # Payment session has increased by one, payment level remains the same.
3342        # Returning Postgraduates have to pay school_fee_2.
3343        self.assertEqual(self.student['payments'][value].amount_auth, 20000.0)
3344        self.assertEqual(self.student['payments'][value].p_session, 2005)
3345        self.assertEqual(self.student['payments'][value].p_level, 999)
3346
3347        # Student is still in old session
3348        self.assertEqual(self.student.current_session, 2004)
3349
3350        # We do not need to pay the ticket if any other
3351        # SFE pin is provided
3352        pin_container = self.app['accesscodes']
3353        pin_container.createBatch(
3354            datetime.utcnow(), 'some_userid', 'SFE', 9.99, 1)
3355        pin = pin_container['SFE-1'].values()[0].representation
3356        sfeseries, sfenumber = pin.split('-')[1:]
3357        # The new SFE-1 pin can be used for starting new session
3358        self.browser.open(self.studycourse_path)
3359        self.browser.getLink('Start new session').click()
3360        self.browser.getControl(name="ac_series").value = sfeseries
3361        self.browser.getControl(name="ac_number").value = sfenumber
3362        self.browser.getControl("Start now").click()
3363        self.assertMatches('...Session started...',
3364                           self.browser.contents)
3365        self.assertTrue(self.student.state == 'school fee paid')
3366        # Student is in new session
3367        self.assertEqual(self.student.current_session, 2005)
3368        self.assertEqual(self.student['studycourse'].current_level, 999)
3369        return
3370
3371    def test_student_accommodation(self):
3372        # Create a second hostel with one bed
3373        hostel = Hostel()
3374        hostel.hostel_id = u'hall-2'
3375        hostel.hostel_name = u'Hall 2'
3376        self.app['hostels'].addHostel(hostel)
3377        bed = Bed()
3378        bed.bed_id = u'hall-2_A_101_A'
3379        bed.bed_number = 1
3380        bed.owner = NOT_OCCUPIED
3381        bed.bed_type = u'regular_female_fr'
3382        self.app['hostels'][hostel.hostel_id].addBed(bed)
3383        self.app['hostels'].allocation_expiration = 7
3384
3385        self.browser.open(self.login_path)
3386        self.browser.getControl(name="form.login").value = self.student_id
3387        self.browser.getControl(name="form.password").value = 'spwd'
3388        self.browser.getControl("Login").click()
3389        # Students can add online booking fee payment tickets and open the
3390        # callback view (see test_manage_payments).
3391        self.browser.getLink("Payments").click()
3392        self.browser.getLink("Add current session payment ticket").click()
3393        self.browser.getControl(name="form.p_category").value = ['bed_allocation']
3394        self.browser.getControl("Create ticket").click()
3395        ctrl = self.browser.getControl(name='val_id')
3396        value = ctrl.options[0]
3397        self.browser.getLink(value).click()
3398        self.browser.open(self.browser.url + '/fake_approve')
3399        # The new HOS-0 pin has been created.
3400        self.assertEqual(len(self.app['accesscodes']['HOS-0']),1)
3401        pin = self.app['accesscodes']['HOS-0'].keys()[0]
3402        ac = self.app['accesscodes']['HOS-0'][pin]
3403        parts = pin.split('-')[1:]
3404        sfeseries, sfenumber = parts
3405        # Students can use HOS code and book a bed space with it ...
3406        self.browser.open(self.acco_path)
3407        # ... but not if booking period has expired ...
3408        self.app['hostels'].enddate = datetime.now(pytz.utc)
3409        self.browser.getControl("Book accommodation").click()
3410        self.assertMatches('...Outside booking period: ...',
3411                           self.browser.contents)
3412        self.app['hostels'].enddate = datetime.now(pytz.utc) + timedelta(days=10)
3413        # ... or student data are incomplete ...
3414        self.student['studycourse'].current_level = None
3415        self.browser.getControl("Book accommodation").click()
3416        self.assertMatches('...Your data are incomplete...',
3417            self.browser.contents)
3418        self.student['studycourse'].current_level = 100
3419        # ... or student is not the an allowed state ...
3420        self.browser.getControl("Book accommodation").click()
3421        self.assertMatches('...You are in the wrong...',
3422                           self.browser.contents)
3423        # Students can still not see the disired hostel selector.
3424        self.assertFalse('desired hostel' in self.browser.contents)
3425        IWorkflowInfo(self.student).fireTransition('admit')
3426        # Students can now see the disired hostel selector.
3427        self.browser.reload()
3428        self.browser.open(self.acco_path)
3429        self.assertTrue('desired hostel' in self.browser.contents)
3430        self.browser.getControl(name="hostel").value = ['hall-2']
3431        self.browser.getControl("Save").click()
3432        self.assertTrue('selection has been saved' in self.browser.contents)
3433        self.assertTrue('<option selected="selected" value="hall-2">'
3434            in self.browser.contents)
3435        self.browser.getControl("Book accommodation").click()
3436        self.assertMatches('...Activation Code:...',
3437                           self.browser.contents)
3438        # Student can't use faked ACs ...
3439        self.browser.getControl(name="ac_series").value = u'nonsense'
3440        self.browser.getControl(name="ac_number").value = sfenumber
3441        self.browser.getControl("Create bed ticket").click()
3442        self.assertMatches('...Activation code is invalid...',
3443                           self.browser.contents)
3444        # ... or ACs owned by somebody else.
3445        ac.owner = u'Anybody'
3446        self.browser.getControl(name="ac_series").value = sfeseries
3447        self.browser.getControl(name="ac_number").value = sfenumber
3448        # There is no free bed space and the bed selector does not appear
3449        self.assertFalse('<option value="hall-1_A_101_A">'
3450            in self.browser.contents)
3451        self.browser.getControl("Create bed ticket").click()
3452        # Hostel 2 has only a bed for women.
3453        self.assertTrue('There is no free bed in your category regular_male_fr.'
3454            in self.browser.contents)
3455        self.browser.getControl(name="hostel").value = ['hall-1']
3456        self.browser.getControl("Save").click()
3457        self.browser.getControl("Book accommodation").click()
3458        # Student can't use faked ACs ...
3459        self.browser.getControl(name="ac_series").value = sfeseries
3460        self.browser.getControl(name="ac_number").value = sfenumber
3461        self.browser.getControl("Create bed ticket").click()
3462        self.assertMatches('...You are not the owner of this access code...',
3463                           self.browser.contents)
3464        # The bed remains empty.
3465        bed = self.app['hostels']['hall-1']['hall-1_A_101_A']
3466        self.assertTrue(bed.owner == NOT_OCCUPIED)
3467        ac.owner = self.student_id
3468        self.browser.open(self.acco_path + '/add')
3469        self.browser.getControl(name="ac_series").value = sfeseries
3470        self.browser.getControl(name="ac_number").value = sfenumber
3471        # Bed can be selected
3472        self.browser.getControl(name="bed").value = ['hall-1_A_101_A']
3473        self.browser.getControl("Create bed ticket").click()
3474        self.assertTrue('Bed ticket created and bed booked'
3475            in self.browser.contents)
3476        # Bed has been allocated.
3477        self.assertTrue(bed.owner == self.student_id)
3478        # BedTicketAddPage is now blocked.
3479        self.browser.getControl("Book accommodation").click()
3480        self.assertMatches('...You already booked a bed space...',
3481            self.browser.contents)
3482        # The bed ticket displays the data correctly.
3483        self.browser.open(self.acco_path + '/2004')
3484        self.assertMatches('...Hall 1, Block A, Room 101, Bed A...',
3485                           self.browser.contents)
3486        self.assertMatches('...2004/2005...', self.browser.contents)
3487        self.assertMatches('...regular_male_fr...', self.browser.contents)
3488        self.assertMatches('...%s...' % pin, self.browser.contents)
3489        # Students can open the pdf slip.
3490        self.browser.open(self.browser.url + '/bed_allocation_slip.pdf')
3491        self.assertEqual(self.browser.headers['Status'], '200 Ok')
3492        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
3493        path = os.path.join(samples_dir(), 'bed_allocation_slip.pdf')
3494        open(path, 'wb').write(self.browser.contents)
3495        print "Sample PDF bed_allocation_slip.pdf written to %s" % path
3496        # Students can't relocate themselves.
3497        self.assertFalse('Relocate' in self.browser.contents)
3498        relocate_path = self.acco_path + '/2004/relocate'
3499        self.assertRaises(
3500            Unauthorized, self.browser.open, relocate_path)
3501        # Students can't see the Remove button and check boxes.
3502        self.browser.open(self.acco_path)
3503        self.assertFalse('Remove' in self.browser.contents)
3504        self.assertFalse('val_id' in self.browser.contents)
3505        # Students can pay maintenance fee now.
3506        self.browser.open(self.payments_path)
3507        self.browser.open(self.payments_path + '/addop')
3508        self.browser.getControl(name="form.p_category").value = ['hostel_maintenance']
3509        self.browser.getControl("Create ticket").click()
3510        self.assertMatches('...Payment ticket created...',
3511                           self.browser.contents)
3512        ctrl = self.browser.getControl(name='val_id')
3513        value = ctrl.options[0]
3514        # Maintennace fee is taken from the hostel object.
3515        self.assertEqual(self.student['payments'][value].amount_auth, 876.0)
3516        # If the hostel's maintenance fee isn't set, the fee is
3517        # taken from the session configuration object.
3518        self.app['hostels']['hall-1'].maint_fee = 0.0
3519        self.browser.open(self.payments_path + '/addop')
3520        self.browser.getControl(name="form.p_category").value = ['hostel_maintenance']
3521        self.browser.getControl("Create ticket").click()
3522        ctrl = self.browser.getControl(name='val_id')
3523        value = ctrl.options[1]
3524        self.assertEqual(self.student['payments'][value].amount_auth, 987.0)
3525        # The bedticket is aware of successfull maintenance fee payment
3526        bedticket = self.student['accommodation']['2004']
3527        self.assertFalse(bedticket.maint_payment_made)
3528        self.student['payments'][value].approve()
3529        self.assertTrue(bedticket.maint_payment_made)
3530        return
3531
3532    def test_change_password_request(self):
3533        self.browser.open('http://localhost/app/changepw')
3534        self.browser.getControl(name="form.identifier").value = '123'
3535        self.browser.getControl(name="form.email").value = 'aa@aa.ng'
3536        self.browser.getControl("Send login credentials").click()
3537        self.assertTrue('An email with' in self.browser.contents)
3538
3539    def test_student_expired_personal_data(self):
3540        # Login
3541        IWorkflowState(self.student).setState('school fee paid')
3542        delta = timedelta(days=180)
3543        self.student.personal_updated = datetime.utcnow() - delta
3544        self.browser.open(self.login_path)
3545        self.browser.getControl(name="form.login").value = self.student_id
3546        self.browser.getControl(name="form.password").value = 'spwd'
3547        self.browser.getControl("Login").click()
3548        self.assertEqual(self.browser.url, self.student_path)
3549        self.assertTrue(
3550            'You logged in' in self.browser.contents)
3551        # Students don't see personal_updated field in edit form
3552        self.browser.open(self.edit_personal_path)
3553        self.assertFalse('Updated' in self.browser.contents)
3554        self.browser.open(self.personal_path)
3555        self.assertTrue('Updated' in self.browser.contents)
3556        self.browser.getLink("Logout").click()
3557        delta = timedelta(days=181)
3558        self.student.personal_updated = datetime.utcnow() - delta
3559        self.browser.open(self.login_path)
3560        self.browser.getControl(name="form.login").value = self.student_id
3561        self.browser.getControl(name="form.password").value = 'spwd'
3562        self.browser.getControl("Login").click()
3563        self.assertEqual(self.browser.url, self.edit_personal_path)
3564        self.assertTrue(
3565            'Your personal data record is outdated.' in self.browser.contents)
3566
3567    def test_request_transcript(self):
3568        IWorkflowState(self.student).setState('graduated')
3569        self.browser.open(self.login_path)
3570        self.browser.getControl(name="form.login").value = self.student_id
3571        self.browser.getControl(name="form.password").value = 'spwd'
3572        self.browser.getControl("Login").click()
3573        self.assertMatches(
3574            '...You logged in...', self.browser.contents)
3575        # Create payment ticket
3576        self.browser.open(self.payments_path)
3577        self.browser.open(self.payments_path + '/addop')
3578        self.browser.getControl(name="form.p_category").value = ['transcript']
3579        self.browser.getControl("Create ticket").click()
3580        ctrl = self.browser.getControl(name='val_id')
3581        value = ctrl.options[0]
3582        self.browser.getLink(value).click()
3583        self.assertMatches('...Amount Authorized...',
3584                           self.browser.contents)
3585        self.assertEqual(self.student['payments'][value].amount_auth, 4567.0)
3586        # Student is the payer of the payment ticket.
3587        payer = IPayer(self.student['payments'][value])
3588        self.assertEqual(payer.display_fullname, 'Anna Tester')
3589        self.assertEqual(payer.id, self.student_id)
3590        self.assertEqual(payer.faculty, 'fac1')
3591        self.assertEqual(payer.department, 'dep1')
3592        # We simulate the approval and fetch the pin
3593        self.assertEqual(len(self.app['accesscodes']['TSC-0']),0)
3594        self.browser.open(self.browser.url + '/fake_approve')
3595        self.assertMatches('...Payment approved...',
3596                          self.browser.contents)
3597        pin = self.app['accesscodes']['TSC-0'].keys()[0]
3598        parts = pin.split('-')[1:]
3599        tscseries, tscnumber = parts
3600        # Student can use the pin to send the transcript request
3601        self.browser.open(self.student_path)
3602        self.browser.getLink("Request transcript").click()
3603        self.browser.getControl(name="ac_series").value = tscseries
3604        self.browser.getControl(name="ac_number").value = tscnumber
3605        self.browser.getControl(name="comment").value = 'Comment line 1 \nComment line2'
3606        self.browser.getControl(name="address").value = 'Address line 1 \nAddress line2'
3607        self.browser.getControl("Submit").click()
3608        self.assertMatches('...Transcript processing has been started...',
3609                          self.browser.contents)
3610        self.assertEqual(self.student.state, 'transcript requested')
3611        self.assertMatches(
3612            '... UTC K1000000 wrote:\n\nComment line 1 \n'
3613            'Comment line2\n\nDispatch Address:\nAddress line 1 \n'
3614            'Address line2\n\n', self.student['studycourse'].transcript_comment)
3615        # The comment has been logged
3616        logfile = os.path.join(
3617            self.app['datacenter'].storage, 'logs', 'students.log')
3618        logcontent = open(logfile).read()
3619        self.assertTrue(
3620            'K1000000 - students.browser.StudentTranscriptRequestPage - '
3621            'K1000000 - comment: Comment line 1 <br>Comment line2\n'
3622            in logcontent)
3623
3624    def test_late_registration(self):
3625        # Login
3626        delta = timedelta(days=10)
3627        self.app['configuration'][
3628            '2004'].coursereg_deadline = datetime.now(pytz.utc) - delta
3629        IWorkflowState(self.student).setState('school fee paid')
3630        self.browser.open(self.login_path)
3631        self.browser.getControl(name="form.login").value = self.student_id
3632        self.browser.getControl(name="form.password").value = 'spwd'
3633        self.browser.getControl("Login").click()
3634        self.browser.open(self.payments_path)
3635        self.browser.open(self.payments_path + '/addop')
3636        self.browser.getControl(name="form.p_category").value = ['late_registration']
3637        self.browser.getControl("Create ticket").click()
3638        self.assertMatches('...ticket created...',
3639                           self.browser.contents)
3640        self.browser.open(self.payments_path)
3641        ctrl = self.browser.getControl(name='val_id')
3642        value = ctrl.options[0]
3643        self.browser.getLink("Study Course").click()
3644        self.browser.getLink("Add course list").click()
3645        self.assertMatches('...Add current level 100 (Year 1)...',
3646                           self.browser.contents)
3647        self.browser.getControl("Create course list now").click()
3648        self.browser.getLink("100").click()
3649        self.browser.getLink("Edit course list").click()
3650        self.browser.getControl("Register course list").click()
3651        self.assertTrue('Course registration has ended. Please pay' in self.browser.contents)
3652        self.student['payments'][value].approve()
3653        self.browser.getControl("Register course list").click()
3654        self.assertTrue('Course list has been registered' in self.browser.contents)
3655        self.assertEqual(self.student.state, 'courses registered')
3656
3657    def test_former_course(self):
3658        IWorkflowState(self.student).setState('school fee paid')
3659        self.student['studycourse'].current_level = 100
3660        self.browser.open(self.login_path)
3661        self.browser.getControl(name="form.login").value = self.student_id
3662        self.browser.getControl(name="form.password").value = 'spwd'
3663        self.browser.getControl("Login").click()
3664        # Now students can add the current study level
3665        self.browser.getLink("Study Course").click()
3666        self.browser.getLink("Add course list").click()
3667        self.assertMatches('...Add current level 100 (Year 1)...',
3668                           self.browser.contents)
3669        self.browser.getControl("Create course list now").click()
3670        # A level with one course ticket was created
3671        self.assertEqual(
3672            self.student['studycourse']['100'].number_of_tickets, 1)
3673        self.browser.getLink("100").click()
3674        self.assertTrue('<td>Unnamed Course</td>' in self.browser.contents)
3675        self.browser.getLink("Edit course list").click()
3676        del self.student['studycourse']['100']['COURSE1']
3677        # Course can be added again via CourseTicketAddFormPage2
3678        self.browser.getLink("here").click()
3679        self.browser.getControl(name="form.course").value = ['COURSE1']
3680        self.browser.getControl("Add course ticket").click()
3681        self.assertTrue('Successfully added COURSE1' in self.browser.contents)
3682        self.assertEqual(len(self.student['studycourse']['100'].keys()),1)
3683        del self.student['studycourse']['100']['COURSE1']
3684        self.course.former_course = True
3685        self.browser.getLink("here").click()
3686        self.browser.getControl(name="form.course").value = ['COURSE1']
3687        self.browser.getControl("Add course ticket").click()
3688        self.assertTrue('Former courses can\'t be added.' in self.browser.contents)
3689        self.assertEqual(len(self.student['studycourse']['100'].keys()),0)
3690        # Course can be added again via StudyLevelEditFormPage
3691        self.browser.getLink("100").click()
3692        self.browser.getLink("Edit course list").click()
3693        self.browser.getControl(name="course").value = 'COURSE1'
3694        self.browser.getControl("Add course ticket").click()
3695        self.assertTrue('Former courses can\'t be added.' in
3696            self.browser.contents)
3697        self.assertEqual(len(self.student['studycourse']['100'].keys()),0)
3698        # but added if current course
3699        self.course.former_course = False
3700        self.browser.getControl(name="course").value = 'COURSE1'
3701        self.browser.getControl("Add course ticket").click()
3702        self.assertTrue('Successfully added COURSE1' in self.browser.contents)
3703        self.assertEqual(len(self.student['studycourse']['100'].keys()),1)
3704        return
3705
3706class StudentRequestPWTests(StudentsFullSetup):
3707    # Tests for student registration
3708
3709    layer = FunctionalLayer
3710
3711    def test_request_pw(self):
3712        # Student with wrong number can't be found.
3713        self.browser.open('http://localhost/app/requestpw')
3714        self.browser.getControl(name="form.lastname").value = 'Tester'
3715        self.browser.getControl(name="form.number").value = 'anynumber'
3716        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
3717        self.browser.getControl("Send login credentials").click()
3718        self.assertTrue('No student record found.'
3719            in self.browser.contents)
3720        # Anonymous is not informed that lastname verification failed.
3721        # It seems that the record doesn't exist.
3722        self.browser.open('http://localhost/app/requestpw')
3723        self.browser.getControl(name="form.lastname").value = 'Johnny'
3724        self.browser.getControl(name="form.number").value = '123'
3725        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
3726        self.browser.getControl("Send login credentials").click()
3727        self.assertTrue('No student record found.'
3728            in self.browser.contents)
3729        # Even with the correct lastname we can't register if a
3730        # password has been set and used.
3731        self.browser.getControl(name="form.lastname").value = 'Tester'
3732        self.browser.getControl(name="form.number").value = '123'
3733        self.browser.getControl("Send login credentials").click()
3734        self.assertTrue('Your password has already been set and used.'
3735            in self.browser.contents)
3736        self.browser.open('http://localhost/app/requestpw')
3737        self.app['students'][self.student_id].password = None
3738        # The lastname field, used for verification, is not case-sensitive.
3739        self.browser.getControl(name="form.lastname").value = 'tESTer'
3740        self.browser.getControl(name="form.number").value = '123'
3741        self.browser.getControl(name="form.email").value = 'new@yy.zz'
3742        self.browser.getControl("Send login credentials").click()
3743        # Yeah, we succeded ...
3744        self.assertTrue('Your password request was successful.'
3745            in self.browser.contents)
3746        # We can also use the matric_number instead.
3747        self.browser.open('http://localhost/app/requestpw')
3748        self.browser.getControl(name="form.lastname").value = 'tESTer'
3749        self.browser.getControl(name="form.number").value = '234'
3750        self.browser.getControl(name="form.email").value = 'new@yy.zz'
3751        self.browser.getControl("Send login credentials").click()
3752        self.assertTrue('Your password request was successful.'
3753            in self.browser.contents)
3754        # ... and  student can be found in the catalog via the email address
3755        cat = queryUtility(ICatalog, name='students_catalog')
3756        results = list(
3757            cat.searchResults(
3758            email=('new@yy.zz', 'new@yy.zz')))
3759        self.assertEqual(self.student,results[0])
3760        logfile = os.path.join(
3761            self.app['datacenter'].storage, 'logs', 'main.log')
3762        logcontent = open(logfile).read()
3763        self.assertTrue('zope.anybody - students.browser.StudentRequestPasswordPage - '
3764                        '234 (K1000000) - new@yy.zz' in logcontent)
3765        return
3766
3767    def test_student_locked_level_forms(self):
3768
3769        # Add two study levels, one current and one previous
3770        studylevel = createObject(u'waeup.StudentStudyLevel')
3771        studylevel.level = 100
3772        self.student['studycourse'].addStudentStudyLevel(
3773            self.certificate, studylevel)
3774        studylevel = createObject(u'waeup.StudentStudyLevel')
3775        studylevel.level = 200
3776        self.student['studycourse'].addStudentStudyLevel(
3777            self.certificate, studylevel)
3778        IWorkflowState(self.student).setState('school fee paid')
3779        self.student['studycourse'].current_level = 200
3780
3781        self.browser.open(self.login_path)
3782        self.browser.getControl(name="form.login").value = self.student_id
3783        self.browser.getControl(name="form.password").value = 'spwd'
3784        self.browser.getControl("Login").click()
3785
3786        self.browser.open(self.student_path + '/studycourse/200/edit')
3787        self.assertFalse('The requested form is locked' in self.browser.contents)
3788        self.browser.open(self.student_path + '/studycourse/100/edit')
3789        self.assertTrue('The requested form is locked' in self.browser.contents)
3790
3791        self.browser.open(self.student_path + '/studycourse/200/ctadd')
3792        self.assertFalse('The requested form is locked' in self.browser.contents)
3793        self.browser.open(self.student_path + '/studycourse/100/ctadd')
3794        self.assertTrue('The requested form is locked' in self.browser.contents)
3795
3796        IWorkflowState(self.student).setState('courses registered')
3797        self.browser.open(self.student_path + '/studycourse/200/edit')
3798        self.assertTrue('The requested form is locked' in self.browser.contents)
3799        self.browser.open(self.student_path + '/studycourse/200/ctadd')
3800        self.assertTrue('The requested form is locked' in self.browser.contents)
3801
3802
3803class PublicPagesTests(StudentsFullSetup):
3804    # Tests for simple webservices
3805
3806    layer = FunctionalLayer
3807
3808    def test_paymentrequest(self):
3809        payment = createObject('waeup.StudentOnlinePayment')
3810        payment.p_category = u'schoolfee'
3811        payment.p_session = self.student.current_session
3812        payment.p_item = u'My Certificate'
3813        payment.p_id = u'anyid'
3814        self.student['payments']['anykey'] = payment
3815        # Request information about unpaid payment ticket
3816        self.browser.open('http://localhost/app/paymentrequest?P_ID=anyid')
3817        self.assertEqual(self.browser.contents, '-1')
3818        # Request information about paid payment ticket
3819        payment.p_state = u'paid'
3820        notify(grok.ObjectModifiedEvent(payment))
3821        self.browser.open('http://localhost/app/paymentrequest?P_ID=anyid')
3822        self.assertEqual(self.browser.contents,
3823            'FULL_NAME=Anna Tester&FACULTY=fac1&DEPARTMENT=dep1'
3824            '&PAYMENT_ITEM=My Certificate&PAYMENT_CATEGORY=School Fee'
3825            '&ACADEMIC_SESSION=2004/2005&MATRIC_NUMBER=234&REG_NUMBER=123'
3826            '&FEE_AMOUNT=0.0')
3827        self.browser.open('http://localhost/app/paymentrequest?NONSENSE=nonsense')
3828        self.assertEqual(self.browser.contents, '-1')
3829        self.browser.open('http://localhost/app/paymentrequest?P_ID=nonsense')
3830        self.assertEqual(self.browser.contents, '-1')
3831
3832class StudentDataExportTests(StudentsFullSetup, FunctionalAsyncTestCase):
3833    # Tests for StudentsContainer class views and pages
3834
3835    layer = FunctionalLayer
3836
3837    def wait_for_export_job_completed(self):
3838        # helper function waiting until the current export job is completed
3839        manager = getUtility(IJobManager)
3840        job_id = self.app['datacenter'].running_exports[0][0]
3841        job = manager.get(job_id)
3842        wait_for_result(job)
3843        return job_id
3844
3845    def add_payment(self, student):
3846        # get a payment with all fields set
3847        payment = StudentOnlinePayment()
3848        payment.creation_date = datetime(2012, 12, 13)
3849        payment.p_id = 'my-id'
3850        payment.p_category = u'schoolfee'
3851        payment.p_state = 'paid'
3852        payment.ac = u'666'
3853        payment.p_item = u'p-item'
3854        payment.p_level = 100
3855        payment.p_session = curr_year - 6
3856        payment.payment_date = datetime(2012, 12, 13)
3857        payment.amount_auth = 12.12
3858        payment.r_amount_approved = 12.12
3859        payment.r_code = u'r-code'
3860        # XXX: there is no addPayment method to give predictable names
3861        self.payment = student['payments']['my-payment'] = payment
3862        return payment
3863
3864    def test_datacenter_export(self):
3865        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
3866        self.browser.open('http://localhost/app/datacenter/@@exportconfig')
3867        self.browser.getControl(name="exporter").value = ['bursary']
3868        self.browser.getControl(name="session").value = ['2004']
3869        self.browser.getControl(name="level").value = ['100']
3870        self.browser.getControl(name="mode").value = ['ug_ft']
3871        self.browser.getControl(name="payments_start").value = '13/12/2012'
3872        self.browser.getControl(name="payments_end").value = '14/12/2012'
3873        self.browser.getControl("Create CSV file").click()
3874
3875        # When the job is finished and we reload the page...
3876        job_id = self.wait_for_export_job_completed()
3877        # ... the csv file can be downloaded ...
3878        self.browser.open('http://localhost/app/datacenter/@@export')
3879        self.browser.getLink("Download").click()
3880        self.assertEqual(self.browser.headers['content-type'],
3881            'text/csv; charset=UTF-8')
3882        self.assertTrue(
3883            'filename="WAeUP.Kofa_bursary_%s.csv' % job_id in
3884            self.browser.headers['content-disposition'])
3885        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
3886        job_id = self.app['datacenter'].running_exports[0][0]
3887        # ... and discarded
3888        self.browser.open('http://localhost/app/datacenter/@@export')
3889        self.browser.getControl("Discard").click()
3890        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
3891        # Creation, downloading and discarding is logged
3892        logfile = os.path.join(
3893            self.app['datacenter'].storage, 'logs', 'datacenter.log')
3894        logcontent = open(logfile).read()
3895        self.assertTrue(
3896            'zope.mgr - students.browser.DatacenterExportJobContainerJobConfig '
3897            '- exported: bursary (2004, 100, ug_ft, None, None, None, '
3898            '13/12/2012, 14/12/2012, all, all, all, all, all), job_id=%s'
3899            % job_id in logcontent
3900            )
3901        self.assertTrue(
3902            'zope.mgr - browser.pages.ExportCSVView '
3903            '- downloaded: WAeUP.Kofa_bursary_%s.csv, job_id=%s'
3904            % (job_id, job_id) in logcontent
3905            )
3906        self.assertTrue(
3907            'zope.mgr - browser.pages.ExportCSVPage '
3908            '- discarded: job_id=%s' % job_id in logcontent
3909            )
3910
3911    def test_datacenter_export_selected(self):
3912        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
3913        self.browser.open('http://localhost/app/datacenter/@@exportselected')
3914        self.browser.getControl(name="exporter").value = ['students']
3915        self.browser.getControl(name="students").value = 'K1000000'
3916        self.browser.getControl("Create CSV file").click()
3917        # When the job is finished and we reload the page...
3918        job_id = self.wait_for_export_job_completed()
3919        # ... the csv file can be downloaded ...
3920        self.browser.open('http://localhost/app/datacenter/@@export')
3921        self.browser.getLink("Download").click()
3922        self.assertEqual(self.browser.headers['content-type'],
3923            'text/csv; charset=UTF-8')
3924        self.assertTrue(
3925            'filename="WAeUP.Kofa_students_%s.csv' % job_id in
3926            self.browser.headers['content-disposition'])
3927        self.assertTrue(
3928            'adm_code,clr_code,date_of_birth,email,employer,'
3929            'firstname,flash_notice,lastname,matric_number,middlename,nationality,'
3930            'officer_comment,parents_email,perm_address,'
3931            'personal_updated,phone,reg_number,'
3932            'sex,student_id,suspended,suspended_comment,'
3933            'password,state,history,certcode,is_postgrad,'
3934            'current_level,current_session\r\n'
3935            ',,1981-02-04#,aa@aa.ng,,Anna,,Tester,234,,,,,,,'
3936            '1234#,123,m,K1000000,0,,{SSHA}' in self.browser.contents)
3937        self.browser.open('http://localhost/app/datacenter/@@export')
3938        self.browser.getControl("Discard").click()
3939
3940    def test_payment_dates(self):
3941        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
3942        self.browser.open('http://localhost/app/datacenter/@@exportconfig')
3943        self.browser.getControl(name="exporter").value = ['bursary']
3944        self.browser.getControl(name="session").value = ['2004']
3945        self.browser.getControl(name="level").value = ['100']
3946        self.browser.getControl(name="mode").value = ['ug_ft']
3947        self.browser.getControl(name="payments_start").value = '13/12/2012'
3948        # If one payment date is missing, an error message appears
3949        self.browser.getControl(name="payments_end").value = ''
3950        self.browser.getControl("Create CSV file").click()
3951        self.assertTrue('Payment dates do not match format d/m/Y'
3952            in self.browser.contents)
3953
3954    def test_faculties_export(self):
3955        self.add_payment(self.student)
3956        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
3957        facs_path = 'http://localhost/app/faculties'
3958        self.browser.open(facs_path)
3959        self.browser.getLink("Export student data").click()
3960        self.browser.getControl("Set export parameters").click()
3961        self.browser.getControl(name="exporter").value = ['bursary']
3962        self.browser.getControl(name="session").value = ['2004']
3963        self.browser.getControl(name="level").value = ['100']
3964        self.browser.getControl(name="mode").value = ['ug_ft']
3965        self.browser.getControl(name="payments_start").value = '13/12/2012'
3966        self.browser.getControl(name="payments_end").value = '14/12/2012'
3967        self.browser.getControl(name="paycat").value = ['schoolfee']
3968        self.browser.getControl("Create CSV file").click()
3969
3970        # When the job is finished and we reload the page...
3971        job_id = self.wait_for_export_job_completed()
3972        self.browser.open(facs_path + '/exports')
3973        # ... the csv file can be downloaded ...
3974        self.browser.getLink("Download").click()
3975        self.assertEqual(self.browser.headers['content-type'],
3976            'text/csv; charset=UTF-8')
3977        self.assertTrue(
3978            'filename="WAeUP.Kofa_bursary_%s.csv' % job_id in
3979            self.browser.headers['content-disposition'])
3980        self.assertTrue(
3981            '666,12.12,2012-12-13 00:00:00#,schoolfee,[],1,my-id,p-item,100,%s,'
3982            'paid,2012-12-13 00:00:00#,12.12,r-code,,K1000000,234,123,Anna,,'
3983            'Tester,created,2004,2004,,fac1,dep1,CERT1'
3984            %(curr_year-6) in self.browser.contents)
3985        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
3986        job_id = self.app['datacenter'].running_exports[0][0]
3987        # ... and discarded
3988        self.browser.open(facs_path + '/exports')
3989        self.browser.getControl("Discard").click()
3990        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
3991        # Creation, downloading and discarding is logged
3992        logfile = os.path.join(
3993            self.app['datacenter'].storage, 'logs', 'datacenter.log')
3994        logcontent = open(logfile).read()
3995        self.assertTrue(
3996            'zope.mgr - students.browser.FacultiesExportJobContainerJobConfig '
3997            '- exported: bursary (2004, 100, ug_ft, None, None, None, '
3998            '13/12/2012, 14/12/2012, all, all, schoolfee, all, all), job_id=%s'
3999            % job_id in logcontent
4000            )
4001        self.assertTrue(
4002            'zope.mgr - students.browser.ExportJobContainerDownload '
4003            '- downloaded: WAeUP.Kofa_bursary_%s.csv, job_id=%s'
4004            % (job_id, job_id) in logcontent
4005            )
4006        self.assertTrue(
4007            'zope.mgr - students.browser.ExportJobContainerOverview '
4008            '- discarded: job_id=%s' % job_id in logcontent
4009            )
4010        # Officer can also enter student id and gets the same export file
4011        self.browser.open(facs_path)
4012        self.browser.getLink("Export student data").click()
4013        self.browser.getControl("Enter student ids or matric numbers").click()
4014        self.browser.getControl(name="exporter").value = ['bursary']
4015        self.browser.getControl(name="students").value = 'K1000000'
4016        self.browser.getControl("Create CSV file").click()
4017        # When the job is finished and we reload the page...
4018        job_id = self.wait_for_export_job_completed()
4019        # ... the csv file can be downloaded ...
4020        self.browser.open('http://localhost/app/faculties/exports')
4021        self.browser.getLink("Download").click()
4022        self.assertEqual(self.browser.headers['content-type'],
4023            'text/csv; charset=UTF-8')
4024        self.assertTrue(
4025            'filename="WAeUP.Kofa_bursary_%s.csv' % job_id in
4026            self.browser.headers['content-disposition'])
4027        self.assertTrue(
4028            '666,12.12,2012-12-13 00:00:00#,schoolfee,[],1,my-id,p-item,100,%s,'
4029            'paid,2012-12-13 00:00:00#,12.12,r-code,,K1000000,234,123,Anna,,'
4030            'Tester,created,2004,2004,,fac1,dep1,CERT1'
4031            %(curr_year-6) in self.browser.contents)
4032
4033    def test_faculty_export(self):
4034        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
4035        fac1_path = 'http://localhost/app/faculties/fac1'
4036        self.browser.open(fac1_path)
4037        self.browser.getLink("Export student data").click()
4038        self.browser.getControl("Set export parameters").click()
4039        self.browser.getControl(name="exporter").value = ['students']
4040        self.browser.getControl(name="session").value = ['2004']
4041        self.browser.getControl(name="level").value = ['100']
4042        self.browser.getControl(name="mode").value = ['ug_ft']
4043        # The testbrowser does not hide the payment period fields, but
4044        # values are ignored when using the students exporter.
4045        self.browser.getControl(name="payments_start").value = '13/12/2012'
4046        self.browser.getControl(name="payments_end").value = '14/12/2012'
4047        self.browser.getControl("Create CSV file").click()
4048        # When the job is finished and we reload the page...
4049        job_id = self.wait_for_export_job_completed()
4050        self.browser.open(fac1_path + '/exports')
4051        # ... the csv file can be downloaded ...
4052        self.browser.getLink("Download").click()
4053        self.assertEqual(self.browser.headers['content-type'],
4054            'text/csv; charset=UTF-8')
4055        self.assertTrue(
4056            'filename="WAeUP.Kofa_students_%s.csv' % job_id in
4057            self.browser.headers['content-disposition'])
4058        self.assertTrue(
4059            'adm_code,clr_code,date_of_birth,email,employer,'
4060            'firstname,flash_notice,lastname,matric_number,middlename,nationality,'
4061            'officer_comment,parents_email,perm_address,'
4062            'personal_updated,phone,reg_number,'
4063            'sex,student_id,suspended,suspended_comment,'
4064            'password,state,history,certcode,is_postgrad,'
4065            'current_level,current_session\r\n'
4066            ',,1981-02-04#,aa@aa.ng,,Anna,,Tester,234,,,,,,,'
4067            '1234#,123,m,K1000000,0,,{SSHA}' in self.browser.contents)
4068        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
4069        job_id = self.app['datacenter'].running_exports[0][0]
4070        # ... and discarded
4071        self.browser.open(fac1_path + '/exports')
4072        self.browser.getControl("Discard").click()
4073        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
4074        # Creation, downloading and discarding is logged
4075        logfile = os.path.join(
4076            self.app['datacenter'].storage, 'logs', 'datacenter.log')
4077        logcontent = open(logfile).read()
4078        self.assertTrue(
4079            'zope.mgr - students.browser.FacultyExportJobContainerJobConfig '
4080            '- exported: students (2004, 100, ug_ft, fac1, None, None, '
4081            '13/12/2012, 14/12/2012, all, all, all, all, all), job_id=%s'
4082            % job_id in logcontent
4083            )
4084        self.assertTrue(
4085            'zope.mgr - students.browser.ExportJobContainerDownload '
4086            '- downloaded: WAeUP.Kofa_students_%s.csv, job_id=%s'
4087            % (job_id, job_id) in logcontent
4088            )
4089        self.assertTrue(
4090            'zope.mgr - students.browser.ExportJobContainerOverview '
4091            '- discarded: job_id=%s' % job_id in logcontent
4092            )
4093        # Officer can set export parameters but cannot enter student id
4094        # at faculty level
4095        self.browser.open(fac1_path + '/exports')
4096        self.assertTrue("Set export parameters"
4097                         in self.browser.contents)
4098        self.assertFalse("Enter student ids or matric numbers"
4099                         in self.browser.contents)
4100
4101    def test_department_export(self):
4102        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
4103        dep1_path = 'http://localhost/app/faculties/fac1/dep1'
4104        self.browser.open(dep1_path)
4105        self.browser.getLink("Export student data").click()
4106        self.browser.getControl("Set export parameters").click()
4107        self.browser.getControl(name="exporter").value = ['students']
4108        self.browser.getControl(name="session").value = ['2004']
4109        self.browser.getControl(name="level").value = ['100']
4110        self.browser.getControl(name="mode").value = ['ug_ft']
4111        # The testbrowser does not hide the payment period fields, but
4112        # values are ignored when using the students exporter.
4113        self.browser.getControl(name="payments_start").value = '13/12/2012'
4114        self.browser.getControl(name="payments_end").value = '14/12/2012'
4115        self.browser.getControl("Create CSV file").click()
4116
4117        # When the job is finished and we reload the page...
4118        job_id = self.wait_for_export_job_completed()
4119        self.browser.open(dep1_path + '/exports')
4120        # ... the csv file can be downloaded ...
4121        self.browser.getLink("Download").click()
4122        self.assertEqual(self.browser.headers['content-type'],
4123            'text/csv; charset=UTF-8')
4124        self.assertTrue(
4125            'filename="WAeUP.Kofa_students_%s.csv' % job_id in
4126            self.browser.headers['content-disposition'])
4127        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
4128        job_id = self.app['datacenter'].running_exports[0][0]
4129        # ... and discarded
4130        self.browser.open(dep1_path + '/exports')
4131        self.browser.getControl("Discard").click()
4132        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
4133        # Creation, downloading and discarding is logged
4134        logfile = os.path.join(
4135            self.app['datacenter'].storage, 'logs', 'datacenter.log')
4136        logcontent = open(logfile).read()
4137        self.assertTrue(
4138            'zope.mgr - students.browser.DepartmentExportJobContainerJobConfig '
4139            '- exported: students (2004, 100, ug_ft, None, dep1, None, '
4140            '13/12/2012, 14/12/2012, all, all, all, all, all), job_id=%s'
4141            % job_id in logcontent
4142            )
4143        self.assertTrue(
4144            'zope.mgr - students.browser.ExportJobContainerDownload '
4145            '- downloaded: WAeUP.Kofa_students_%s.csv, job_id=%s'
4146            % (job_id, job_id) in logcontent
4147            )
4148        self.assertTrue(
4149            'zope.mgr - students.browser.ExportJobContainerOverview '
4150            '- discarded: job_id=%s' % job_id in logcontent
4151            )
4152
4153    def test_certificate_export(self):
4154        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
4155        cert1_path = 'http://localhost/app/faculties/fac1/dep1/certificates/CERT1'
4156        self.browser.open(cert1_path)
4157        self.browser.getLink("Export student data").click()
4158        self.browser.getControl("Set export parameters").click()
4159        self.browser.getControl(name="exporter").value = ['students']
4160        self.browser.getControl(name="session").value = ['2004']
4161        self.browser.getControl(name="level").value = ['100']
4162        self.browser.getControl("Create CSV file").click()
4163
4164        # When the job is finished and we reload the page...
4165        job_id = self.wait_for_export_job_completed()
4166        self.browser.open(cert1_path + '/exports')
4167        # ... the csv file can be downloaded ...
4168        self.browser.getLink("Download").click()
4169        self.assertEqual(self.browser.headers['content-type'],
4170            'text/csv; charset=UTF-8')
4171        self.assertTrue(
4172            'filename="WAeUP.Kofa_students_%s.csv' % job_id in
4173            self.browser.headers['content-disposition'])
4174        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
4175        job_id = self.app['datacenter'].running_exports[0][0]
4176        # ... and discarded
4177        self.browser.open(cert1_path + '/exports')
4178        self.browser.getControl("Discard").click()
4179        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
4180        # Creation, downloading and discarding is logged
4181        logfile = os.path.join(
4182            self.app['datacenter'].storage, 'logs', 'datacenter.log')
4183        logcontent = open(logfile).read()
4184        self.assertTrue(
4185            'zope.mgr - students.browser.CertificateExportJobContainerJobConfig '
4186            '- exported: students '
4187            '(2004, 100, None, None, None, CERT1, , , None, None, '
4188            'None, None, None), '
4189            'job_id=%s'
4190            % job_id in logcontent
4191            )
4192        self.assertTrue(
4193            'zope.mgr - students.browser.ExportJobContainerDownload '
4194            '- downloaded: WAeUP.Kofa_students_%s.csv, job_id=%s'
4195            % (job_id, job_id) in logcontent
4196            )
4197        self.assertTrue(
4198            'zope.mgr - students.browser.ExportJobContainerOverview '
4199            '- discarded: job_id=%s' % job_id in logcontent
4200            )
4201
4202    def deprecated_test_course_export_students(self):
4203        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
4204        course1_path = 'http://localhost/app/faculties/fac1/dep1/courses/COURSE1'
4205        self.browser.open(course1_path)
4206        self.browser.getLink("Export student data").click()
4207        self.browser.getControl("Set export parameters").click()
4208        self.browser.getControl(name="exporter").value = ['students']
4209        self.browser.getControl(name="session").value = ['2004']
4210        self.browser.getControl(name="level").value = ['100']
4211        self.browser.getControl("Create CSV file").click()
4212
4213        # When the job is finished and we reload the page...
4214        job_id = self.wait_for_export_job_completed()
4215        self.browser.open(course1_path + '/exports')
4216        # ... the csv file can be downloaded ...
4217        self.browser.getLink("Download").click()
4218        self.assertEqual(self.browser.headers['content-type'],
4219            'text/csv; charset=UTF-8')
4220        self.assertTrue(
4221            'filename="WAeUP.Kofa_students_%s.csv' % job_id in
4222            self.browser.headers['content-disposition'])
4223        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
4224        job_id = self.app['datacenter'].running_exports[0][0]
4225        # ... and discarded
4226        self.browser.open(course1_path + '/exports')
4227        self.browser.getControl("Discard").click()
4228        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
4229        # Creation, downloading and discarding is logged
4230        logfile = os.path.join(
4231            self.app['datacenter'].storage, 'logs', 'datacenter.log')
4232        logcontent = open(logfile).read()
4233        self.assertTrue(
4234            'zope.mgr - students.browser.CourseExportJobContainerJobConfig '
4235            '- exported: students (2004, 100, COURSE1), job_id=%s'
4236            % job_id in logcontent
4237            )
4238        self.assertTrue(
4239            'zope.mgr - students.browser.ExportJobContainerDownload '
4240            '- downloaded: WAeUP.Kofa_students_%s.csv, job_id=%s'
4241            % (job_id, job_id) in logcontent
4242            )
4243        self.assertTrue(
4244            'zope.mgr - students.browser.ExportJobContainerOverview '
4245            '- discarded: job_id=%s' % job_id in logcontent
4246            )
4247
4248    def test_course_export_lecturer(self):
4249        # We add study level 100 to the student's studycourse
4250        studylevel = StudentStudyLevel()
4251        studylevel.level = 100
4252        studylevel.level_session = 2004
4253        IWorkflowState(self.student).setState('courses validated')
4254        self.student['studycourse'].addStudentStudyLevel(
4255            self.certificate,studylevel)
4256        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
4257        course1_path = 'http://localhost/app/faculties/fac1/dep1/courses/COURSE1'
4258        self.browser.open(course1_path)
4259        self.browser.getLink("Export student data").click()
4260        self.browser.getControl("Set export parameters").click()
4261        self.assertTrue(
4262            'Academic session not set. Please contact the administrator.'
4263            in self.browser.contents)
4264        self.app['configuration'].current_academic_session = 2004
4265        self.browser.getControl("Set export parameters").click()
4266        self.browser.getControl(name="exporter").value = ['lecturer']
4267        self.browser.getControl(name="session").value = ['2004']
4268        self.browser.getControl(name="level").value = ['100']
4269        self.browser.getControl("Create CSV file").click()
4270        # When the job is finished and we reload the page...
4271        job_id = self.wait_for_export_job_completed()
4272        self.browser.open(course1_path + '/exports')
4273        # ... the csv file can be downloaded ...
4274        self.browser.getLink("Download").click()
4275        self.assertEqual(self.browser.headers['content-type'],
4276            'text/csv; charset=UTF-8')
4277        self.assertTrue(
4278            'filename="WAeUP.Kofa_lecturer_%s.csv' % job_id in
4279            self.browser.headers['content-disposition'])
4280        # ... and contains the course ticket COURSE1
4281        self.assertEqual(self.browser.contents,
4282            'matric_number,student_id,display_fullname,level,code,'
4283            'level_session,score\r\n234,K1000000,Anna Tester,'
4284            '100,COURSE1,2004,\r\n')
4285        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
4286        job_id = self.app['datacenter'].running_exports[0][0]
4287        # Thew job can be discarded
4288        self.browser.open(course1_path + '/exports')
4289        self.browser.getControl("Discard").click()
4290        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
4291        # Creation, downloading and discarding is logged
4292        logfile = os.path.join(
4293            self.app['datacenter'].storage, 'logs', 'datacenter.log')
4294        logcontent = open(logfile).read()
4295        self.assertTrue(
4296            'zope.mgr - students.browser.CourseExportJobContainerJobConfig '
4297            '- exported: lecturer (2004, 100, COURSE1), job_id=%s'
4298            % job_id in logcontent
4299            )
4300        self.assertTrue(
4301            'zope.mgr - students.browser.ExportJobContainerDownload '
4302            '- downloaded: WAeUP.Kofa_lecturer_%s.csv, job_id=%s'
4303            % (job_id, job_id) in logcontent
4304            )
4305        self.assertTrue(
4306            'zope.mgr - students.browser.ExportJobContainerOverview '
4307            '- discarded: job_id=%s' % job_id in logcontent
4308            )
4309
4310    def test_export_departmet_officers(self):
4311        # Create department officer
4312        self.app['users'].addUser('mrdepartment', SECRET)
4313        self.app['users']['mrdepartment'].email = 'mrdepartment@foo.ng'
4314        self.app['users']['mrdepartment'].title = 'Carlo Pitter'
4315        # Assign local role
4316        department = self.app['faculties']['fac1']['dep1']
4317        prmlocal = IPrincipalRoleManager(department)
4318        prmlocal.assignRoleToPrincipal('waeup.local.DepartmentOfficer', 'mrdepartment')
4319        # Login as department officer
4320        self.browser.open(self.login_path)
4321        self.browser.getControl(name="form.login").value = 'mrdepartment'
4322        self.browser.getControl(name="form.password").value = SECRET
4323        self.browser.getControl("Login").click()
4324        self.assertMatches('...You logged in...', self.browser.contents)
4325        self.browser.open("http://localhost/app/faculties/fac1/dep1")
4326        self.browser.getLink("Export student data").click()
4327        self.browser.getControl("Set export parameters").click()
4328        # Only the sfpaymentsoverview exporter is available for department officers
4329        self.assertFalse('<option value="students">' in self.browser.contents)
4330        self.assertTrue(
4331            '<option value="sfpaymentsoverview">' in self.browser.contents)
4332        self.browser.getControl(name="exporter").value = ['sfpaymentsoverview']
4333        self.browser.getControl(name="session").value = ['2004']
4334        self.browser.getControl(name="level").value = ['100']
4335        self.browser.getControl("Create CSV file").click()
4336        self.assertTrue('Export started' in self.browser.contents)
4337        # Thew job can be discarded
4338        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
4339        self.wait_for_export_job_completed()
4340        self.browser.open("http://localhost/app/faculties/fac1/dep1/exports")
4341        self.browser.getControl("Discard").click()
4342        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
4343
4344    def test_export_bursary_officers(self):
4345        self.add_payment(self.student)
4346        # Create bursary officer
4347        self.app['users'].addUser('mrbursary', SECRET)
4348        self.app['users']['mrbursary'].email = 'mrbursary@foo.ng'
4349        self.app['users']['mrbursary'].title = 'Carlo Pitter'
4350        prmglobal = IPrincipalRoleManager(self.app)
4351        prmglobal.assignRoleToPrincipal('waeup.BursaryOfficer', 'mrbursary')
4352        # Login as bursary officer
4353        self.browser.open(self.login_path)
4354        self.browser.getControl(name="form.login").value = 'mrbursary'
4355        self.browser.getControl(name="form.password").value = SECRET
4356        self.browser.getControl("Login").click()
4357        self.assertMatches('...You logged in...', self.browser.contents)
4358        self.browser.getLink("Academics").click()
4359        self.browser.getLink("Export student data").click()
4360        self.browser.getControl("Set export parameters").click()
4361        # Only the bursary exporter is available for bursary officers
4362        # not only at facultiescontainer level ...
4363        self.assertFalse('<option value="students">' in self.browser.contents)
4364        self.assertTrue('<option value="bursary">' in self.browser.contents)
4365        self.browser.getControl(name="exporter").value = ['bursary']
4366        self.browser.getControl(name="session").value = ['2004']
4367        self.browser.getControl(name="level").value = ['100']
4368        self.browser.getControl("Create CSV file").click()
4369        self.assertTrue('Export started' in self.browser.contents)
4370        # ... but also at other levels
4371        self.browser.open('http://localhost/app/faculties/fac1/dep1')
4372        self.browser.getLink("Export student data").click()
4373        self.browser.getControl("Set export parameters").click()
4374        self.assertFalse('<option value="students">' in self.browser.contents)
4375        self.assertTrue('<option value="bursary">' in self.browser.contents)
4376        # Thew job can be downloaded
4377        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
4378        job_id = self.wait_for_export_job_completed()
4379        self.browser.open('http://localhost/app/faculties/exports')
4380        self.browser.getLink("Download").click()
4381        self.assertEqual(self.browser.headers['content-type'],
4382            'text/csv; charset=UTF-8')
4383        self.assertTrue(
4384            'filename="WAeUP.Kofa_bursary_%s.csv' % job_id in
4385            self.browser.headers['content-disposition'])
4386        self.assertTrue(
4387            '666,12.12,2012-12-13 00:00:00#,schoolfee,[],1,my-id,p-item,100,%s,'
4388            'paid,2012-12-13 00:00:00#,12.12,r-code,,K1000000,234,123,Anna,,'
4389            'Tester,created,2004,2004,,fac1,dep1,CERT1'
4390            %(curr_year-6) in self.browser.contents)
4391        # ... and discarded
4392        self.browser.open('http://localhost/app/faculties/exports')
4393        self.browser.getControl("Discard").click()
4394        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
4395        # At Academics level bursary officers can also enter student ids
4396        self.browser.getLink("Academics").click()
4397        self.browser.getLink("Export student data").click()
4398        self.browser.getControl("Enter student ids or matric numbers").click()
4399        self.assertFalse('<option value="students">' in self.browser.contents)
4400        self.browser.getControl(name="exporter").value = ['bursary']
4401        self.browser.getControl(name="students").value = 'K1000000'
4402        self.browser.getControl("Create CSV file").click()
4403        # When the job is finished and we reload the page...
4404        job_id = self.wait_for_export_job_completed()
4405        # ... the csv file can be downloaded ...
4406        self.browser.open('http://localhost/app/faculties/exports')
4407        self.browser.getLink("Download").click()
4408        self.assertEqual(self.browser.headers['content-type'],
4409            'text/csv; charset=UTF-8')
4410        self.assertTrue(
4411            'filename="WAeUP.Kofa_bursary_%s.csv' % job_id in
4412            self.browser.headers['content-disposition'])
4413        self.assertTrue(
4414            '666,12.12,2012-12-13 00:00:00#,schoolfee,[],1,my-id,p-item,100,%s,'
4415            'paid,2012-12-13 00:00:00#,12.12,r-code,,K1000000,234,123,Anna,,'
4416            'Tester,created,2004,2004,,fac1,dep1,CERT1'
4417            %(curr_year-6) in self.browser.contents)
4418
4419    def test_export_accommodation_officers(self):
4420        # Create bursary officer
4421        self.app['users'].addUser('mracco', SECRET)
4422        self.app['users']['mracco'].email = 'mracco@foo.ng'
4423        self.app['users']['mracco'].title = 'Carlo Pitter'
4424        prmglobal = IPrincipalRoleManager(self.app)
4425        prmglobal.assignRoleToPrincipal('waeup.AccommodationOfficer', 'mracco')
4426        # Login as bursary officer
4427        self.browser.open(self.login_path)
4428        self.browser.getControl(name="form.login").value = 'mracco'
4429        self.browser.getControl(name="form.password").value = SECRET
4430        self.browser.getControl("Login").click()
4431        self.assertMatches('...You logged in...', self.browser.contents)
4432        self.browser.getLink("Academics").click()
4433        self.browser.getLink("Export student data").click()
4434        self.browser.getControl("Set export parameters").click()
4435        # accommodationpayments and beds exporters are available
4436        # not only at facultiescontainer level ...
4437        self.assertFalse('<option value="students">' in self.browser.contents)
4438        self.assertTrue('<option value="accommodationpayments">'
4439            in self.browser.contents)
4440        self.assertTrue('<option value="bedtickets">' in self.browser.contents)
4441        self.browser.getControl(
4442            name="exporter").value = ['accommodationpayments']
4443        self.browser.getControl(name="session").value = ['2004']
4444        self.browser.getControl(name="level").value = ['100']
4445        self.browser.getControl("Create CSV file").click()
4446        self.assertTrue('Export started' in self.browser.contents)
4447        # ... but also at other levels
4448        self.browser.open('http://localhost/app/faculties/fac1/dep1')
4449        self.browser.getLink("Export student data").click()
4450        self.browser.getControl("Set export parameters").click()
4451        self.assertFalse('<option value="students">' in self.browser.contents)
4452        self.assertTrue('<option value="accommodationpayments">'
4453            in self.browser.contents)
4454        self.assertTrue('<option value="bedtickets">' in self.browser.contents)
4455        # Thew job can be discarded
4456        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
4457        self.wait_for_export_job_completed()
4458        self.browser.open('http://localhost/app/faculties/exports')
4459        self.browser.getControl("Discard").click()
4460        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
4461
4462
4463UPLOAD_CSV_TEMPLATE = (
4464    'matric_number,student_id,display_fullname,level,code,level_session,'
4465    'score\r\n'
4466    '234,K1000000,Anna Tester,100,COURSE1,2004,%s\r\n')
4467
4468class LecturerUITests(StudentsFullSetup):
4469    # Tests for UI actions when acting as lecturer.
4470
4471    def login_as_lecturer(self):
4472        self.app['users'].addUser('mrslecturer', SECRET)
4473        self.app['users']['mrslecturer'].email = 'mrslecturer@foo.ng'
4474        self.app['users']['mrslecturer'].title = u'Mercedes Benz'
4475        # Add course ticket
4476        self.studylevel = createObject(u'waeup.StudentStudyLevel')
4477        self.studylevel.level = 100
4478        self.studylevel.level_session = 2004
4479        self.student['studycourse'].addStudentStudyLevel(
4480            self.certificate, self.studylevel)
4481        # Assign local Lecturer role for a course.
4482        course = self.app['faculties']['fac1']['dep1'].courses['COURSE1']
4483        prmlocal = IPrincipalRoleManager(course)
4484        prmlocal.assignRoleToPrincipal('waeup.local.Lecturer', 'mrslecturer')
4485        notify(LocalRoleSetEvent(
4486            course, 'waeup.local.Lecturer', 'mrslecturer', granted=True))
4487        # Login as lecturer.
4488        self.browser.open(self.login_path)
4489        self.browser.getControl(name="form.login").value = 'mrslecturer'
4490        self.browser.getControl(
4491            name="form.password").value = SECRET
4492        self.browser.getControl("Login").click()
4493        # Store reused urls/paths
4494        self.course_url = (
4495            'http://localhost/app/faculties/fac1/dep1/courses/COURSE1')
4496        self.edit_scores_url = '%s/edit_scores' % self.course_url
4497        # Set standard parameters
4498        self.app['configuration'].current_academic_session = 2004
4499        self.app['faculties']['fac1']['dep1'].score_editing_disabled = False
4500        IWorkflowState(self.student).setState(VALIDATED)
4501
4502    @property
4503    def stud_log_path(self):
4504        return os.path.join(
4505            self.app['datacenter'].storage, 'logs', 'students.log')
4506
4507    def test_lecturer_lands_on_landing_page(self):
4508        # lecturers can login and will be led to landing page.
4509        self.login_as_lecturer()
4510        self.assertMatches('...You logged in...', self.browser.contents)
4511        self.assertEqual(self.browser.url, URL_LECTURER_LANDING)
4512        self.assertTrue(
4513            "<span>Unnamed Course (COURSE1)</span>"
4514            in self.browser.contents)
4515
4516    def test_lecturer_department_role(self):
4517        # lecturers can login and will be led to landing page also if
4518        # role is assigned at department level.
4519        self.login_as_lecturer()
4520        # we remove the role granted above
4521        course = self.app['faculties']['fac1']['dep1'].courses['COURSE1']
4522        prmlocal = IPrincipalRoleManager(course)
4523        prmlocal.removeRoleFromPrincipal('waeup.local.Lecturer', 'mrslecturer')
4524        notify(LocalRoleSetEvent(
4525            course, 'waeup.local.Lecturer', 'mrslecturer', granted=False))
4526        self.browser.open(URL_LECTURER_LANDING)
4527        # no course appears
4528        self.assertFalse(
4529            "<span>Unnamed Course (COURSE1)</span>"
4530            in self.browser.contents)
4531        # we assign lecturer at department level
4532        dep = self.app['faculties']['fac1']['dep1']
4533        prmlocal = IPrincipalRoleManager(dep)
4534        prmlocal.assignRoleToPrincipal('waeup.local.Lecturer', 'mrslecturer')
4535        notify(LocalRoleSetEvent(
4536            dep, 'waeup.local.Lecturer', 'mrslecturer', granted=True))
4537        self.browser.open(URL_LECTURER_LANDING)
4538        # course appears again
4539        self.assertTrue(
4540            "<span>Unnamed Course (COURSE1)</span>"
4541            in self.browser.contents)
4542
4543    def test_my_roles_link_works(self):
4544        # lecturers can see their roles
4545        self.login_as_lecturer()
4546        self.browser.getLink("My Roles").click()
4547        self.assertTrue(
4548            "<div>Academics Officer (view only)</div>"
4549            in self.browser.contents)
4550        self.assertTrue(
4551            '<a href="%s">' % self.course_url in self.browser.contents)
4552
4553    def test_my_roles_page_contains_backlink(self):
4554        # we can get back from 'My Roles' view to landing page
4555        self.login_as_lecturer()
4556        self.browser.getLink("My Roles").click()
4557        self.browser.getLink("My Courses").click()
4558        self.assertEqual(self.browser.url, URL_LECTURER_LANDING)
4559
4560    def test_lecturers_can_reach_their_courses(self):
4561        # lecturers get links to their courses on the landing page
4562        self.login_as_lecturer()
4563        self.browser.getLink("COURSE1").click()
4564        self.assertEqual(self.browser.url, self.course_url)
4565
4566    def test_lecturers_student_access_is_restricted(self):
4567        # lecturers are not able to change other student data
4568        self.login_as_lecturer()
4569        # Lecturers can neither filter students ...
4570        self.assertRaises(
4571            Unauthorized, self.browser.open, '%s/students' % self.course_url)
4572        # ... nor access the student ...
4573        self.assertRaises(
4574            Unauthorized, self.browser.open, self.student_path)
4575        # ... nor the respective course ticket since editing course
4576        # tickets by lecturers is not feasible.
4577        self.assertTrue('COURSE1' in self.student['studycourse']['100'].keys())
4578        course_ticket_path = self.student_path + '/studycourse/100/COURSE1'
4579        self.assertRaises(
4580            Unauthorized, self.browser.open, course_ticket_path)
4581
4582    def test_score_editing_requires_department_permit(self):
4583        # we get a warning if we try to update score while we are not allowed
4584        self.login_as_lecturer()
4585        self.app['faculties']['fac1']['dep1'].score_editing_disabled = True
4586        self.browser.open(self.course_url)
4587        self.browser.getLink("Update session 2004/2005 scores").click()
4588        self.assertTrue('Score editing disabled' in self.browser.contents)
4589        self.app['faculties']['fac1']['dep1'].score_editing_disabled = False
4590        self.browser.open(self.course_url)
4591        self.browser.getLink("Update session 2004/2005 scores").click()
4592        self.assertFalse('Score editing disabled' in self.browser.contents)
4593
4594    def test_score_editing_requires_validated_students(self):
4595        # we can edit only scores of students whose courses have been
4596        # validated.
4597        self.login_as_lecturer()
4598        # set invalid student state
4599        IWorkflowState(self.student).setState(CREATED)
4600        self.browser.open(self.edit_scores_url)
4601        self.assertRaises(
4602            LookupError, self.browser.getControl, name="scores")
4603        # set valid student state
4604        IWorkflowState(self.student).setState(VALIDATED)
4605        self.browser.open(self.edit_scores_url)
4606        self.assertTrue(
4607            self.browser.getControl(name="scores:list") is not None)
4608
4609    def test_score_editing_offers_only_current_scores(self):
4610        # only scores from current academic session can be edited
4611        self.login_as_lecturer()
4612        IWorkflowState(self.student).setState('courses validated')
4613        # with no academic session set
4614        self.app['configuration'].current_academic_session = None
4615        self.browser.open(self.edit_scores_url)
4616        self.assertRaises(
4617            LookupError, self.browser.getControl, name="scores")
4618        # with wrong academic session set
4619        self.app['configuration'].current_academic_session = 1999
4620        self.browser.open(self.edit_scores_url)
4621        self.assertRaises(
4622            LookupError, self.browser.getControl, name="scores")
4623        # with right academic session set
4624        self.app['configuration'].current_academic_session = 2004
4625        self.browser.reload()
4626        self.assertTrue(
4627            self.browser.getControl(name="scores:list") is not None)
4628        # if level_session of studycourse changes, catalog has been updated
4629        # and student disappears
4630        self.studylevel.level_session = 2005
4631        self.browser.reload()
4632        self.assertRaises(
4633            LookupError, self.browser.getControl, name="scores")
4634
4635    def test_score_editing_can_change_scores(self):
4636        # we can really change scores via edit_scores view
4637        self.login_as_lecturer()
4638        self.assertEqual(
4639            self.student['studycourse']['100']['COURSE1'].score, None)
4640        self.browser.open(self.edit_scores_url)
4641        self.browser.getControl(name="scores:list", index=0).value = '55'
4642        self.browser.getControl("Update scores").click()
4643        # the new value is stored in data
4644        self.assertEqual(
4645            self.student['studycourse']['100']['COURSE1'].score, 55)
4646        # the new value is displayed on page/prefilled in form
4647        self.assertEqual(
4648            self.browser.getControl(name="scores:list", index=0).value, '55')
4649        # The change has been logged
4650        with open(self.stud_log_path, 'r') as fd:
4651            self.assertTrue(
4652                'mrslecturer - students.browser.EditScoresPage - '
4653                'K1000000 100/COURSE1 score updated (55)' in fd.read())
4654
4655    def test_scores_editing_scores_must_be_integers(self):
4656        # Non-integer scores won't be accepted.
4657        self.login_as_lecturer()
4658        self.browser.open(self.edit_scores_url)
4659        self.browser.getControl(name="scores:list", index=0).value = 'abc'
4660        self.browser.getControl("Update scores").click()
4661        self.assertTrue(
4662            'Error: Score(s) of following students have not been updated '
4663            '(only integers are allowed): Anna Tester.'
4664            in self.browser.contents)
4665
4666    def test_scores_editing_allows_score_removal(self):
4667        # we can remove scores, once they were set
4668        self.login_as_lecturer()
4669        # without a prior value, we cannot remove
4670        self.student['studycourse']['100']['COURSE1'].score = None
4671        self.browser.open(self.edit_scores_url)
4672        self.browser.getControl(name="scores:list", index=0).value = ''
4673        self.browser.getControl("Update scores").click()
4674        logcontent = open(self.stud_log_path, 'r').read()
4675        self.assertFalse('COURSE1 score updated (None)' in logcontent)
4676        # now retry with some value set
4677        self.student['studycourse']['100']['COURSE1'].score = 55
4678        self.browser.getControl(name="scores:list", index=0).value = ''
4679        self.browser.getControl("Update scores").click()
4680        logcontent = open(self.stud_log_path, 'r').read()
4681        self.assertTrue('COURSE1 score updated (None)' in logcontent)
4682
4683    def test_lecturer_can_validate_courses(self):
4684        # the form is locked after validation
4685        self.login_as_lecturer()
4686        self.student['studycourse']['100']['COURSE1'].score = None
4687        self.browser.open(self.edit_scores_url)
4688        self.browser.getControl(name="scores:list", index=0).value = ''
4689        self.browser.getControl("Update scores").click()
4690        self.browser.getControl("Validate").click()
4691        self.assertTrue(
4692            'No score has been entered.' in self.browser.contents)
4693        self.browser.open(self.edit_scores_url)
4694        self.browser.getControl(name="scores:list", index=0).value = '66'
4695        self.browser.getControl("Update scores").click()
4696        self.browser.getControl("Validate").click()
4697        self.assertTrue(
4698            'You successfully validated the course results'
4699            in self.browser.contents)
4700        self.assertEqual(self.course.results_validation_session, 2004)
4701        self.assertEqual(self.course.results_validated_by, 'Mercedes Benz')
4702        self.assertEqual(self.browser.url, self.course_url)
4703        # Lecturer can't open edit_scores again
4704        self.browser.getLink("Update session 2004/2005 scores").click()
4705        self.assertEqual(self.browser.url, self.course_url)
4706        self.assertTrue(
4707            'Course results have already been validated'
4708            ' and can no longer be changed.'
4709            in self.browser.contents)
4710        # Also DownloadScoresView is blocked
4711        self.browser.open(self.browser.url + '/download_scores')
4712        self.assertEqual(self.browser.url, self.course_url)
4713        self.assertTrue(
4714            'Course results have already been validated'
4715            ' and can no longer be changed.'
4716            in self.browser.contents)
4717        # Students Manager can open page ...
4718        prmlocal = IPrincipalRoleManager(self.course)
4719        prmlocal.assignRoleToPrincipal(
4720            'waeup.local.LocalStudentsManager', 'mrslecturer')
4721        self.browser.getLink("Update session 2004/2005 scores").click()
4722        self.assertEqual(self.browser.url, self.edit_scores_url)
4723        self.browser.getLink("Download csv file").click()
4724        self.assertEqual(self.browser.headers['Status'], '200 Ok')
4725        self.assertEqual(self.browser.headers['Content-Type'],
4726                         'text/csv; charset=UTF-8')
4727        # ... but can't validate courses a second time
4728        self.browser.open(self.edit_scores_url)
4729        self.browser.getControl("Validate").click()
4730        self.assertTrue(
4731            'Course results have already been validated.'
4732            in self.browser.contents)
4733
4734    def test_lecturers_can_download_course_tickets(self):
4735        # A course ticket slip can be downloaded
4736        self.course.title = (u'Lorem ipsum     dolor sit amet, consectetur     adipisici, '
4737                             u'sed         eiusmod tempor    incidunt ut  labore et dolore')
4738        self.login_as_lecturer()
4739        pdf_url = '%s/coursetickets.pdf' % self.course_url
4740        self.browser.open(pdf_url)
4741        self.assertEqual(self.browser.headers['Status'], '200 Ok')
4742        self.assertEqual(
4743            self.browser.headers['Content-Type'], 'application/pdf')
4744        path = os.path.join(samples_dir(), 'coursetickets.pdf')
4745        open(path, 'wb').write(self.browser.contents)
4746        print "Sample PDF coursetickets.pdf written to %s" % path
4747
4748    def test_lecturers_can_download_attendance_sheet(self):
4749        # A course ticket slip can be downloaded
4750        self.course.title = (u'Lorem ipsum     dolor sit amet, consectetur     adipisici, '
4751                             u'sed         eiusmod tempor    incidunt ut  labore et dolore')
4752        self.student.firstname = u'Emmanuella Woyengifigha Mercy Onosemudiana'
4753        self.student.lastname = u'OYAKEMIEGBEGHA'
4754        self.student.matric_number = u'hdk7gd62i872z27zt27ge'
4755        self.login_as_lecturer()
4756        pdf_url = '%s/attendance.pdf' % self.course_url
4757        self.browser.open(pdf_url)
4758        self.assertEqual(self.browser.headers['Status'], '200 Ok')
4759        self.assertEqual(
4760            self.browser.headers['Content-Type'], 'application/pdf')
4761        path = os.path.join(samples_dir(), 'attendance.pdf')
4762        open(path, 'wb').write(self.browser.contents)
4763        print "Sample PDF attendance.pdf written to %s" % path
4764
4765
4766    def test_lecturers_can_download_scores_as_csv(self):
4767        # Lecturers can download course scores as CSV.
4768        self.login_as_lecturer()
4769        self.browser.open(self.edit_scores_url)
4770        self.browser.getLink("Download csv file").click()
4771        self.assertEqual(self.browser.headers['Status'], '200 Ok')
4772        self.assertEqual(self.browser.headers['Content-Type'],
4773                         'text/csv; charset=UTF-8')
4774        self.assertEqual(self.browser.contents, 'matric_number,student_id,'
4775            'display_fullname,level,code,level_session,score\r\n234,'
4776            'K1000000,Anna Tester,100,COURSE1,2004,\r\n')
4777
4778    def test_scores_csv_upload_available(self):
4779        # lecturers can upload a CSV file to set values.
4780        self.login_as_lecturer()
4781        # set value to change from
4782        self.student['studycourse']['100']['COURSE1'].score = 55
4783        self.browser.open(self.edit_scores_url)
4784        upload_ctrl = self.browser.getControl(name='uploadfile:file')
4785        upload_file = StringIO(UPLOAD_CSV_TEMPLATE % '65')
4786        upload_ctrl.add_file(upload_file, 'text/csv', 'myscores.csv')
4787        self.browser.getControl("Update editable scores from").click()
4788        # value changed
4789        self.assertEqual(
4790            self.student['studycourse']['100']['COURSE1'].score, 65)
4791
4792    def test_scores_csv_upload_ignored(self):
4793        # for many type of file contents we simply ignore uploaded data
4794        self.login_as_lecturer()
4795        self.student['studycourse']['100']['COURSE1'].score = 55
4796        self.browser.open(self.edit_scores_url)
4797        for content, mimetype, name in (
4798                # empty file
4799                ('', 'text/foo', 'my.foo'),
4800                # plain ASCII text, w/o comma
4801                ('abcdef' * 200, 'text/plain', 'my.txt'),
4802                # plain UTF-8 text, with umlauts
4803                ('umlauts: äöü', 'text/plain', 'my.txt'),
4804                # csv file with only a header row
4805                ('student_id,score', 'text/csv', 'my.csv'),
4806                # csv with student_id column missing
4807                ('foo,score\r\nbar,66\r\n', 'text/csv', 'my.csv'),
4808                # csv with score column missing
4809                ('student_id,foo\r\nK1000000,bar\r\n', 'text/csv', 'my.csv'),
4810                # csv with non number as score value
4811                (UPLOAD_CSV_TEMPLATE % 'not-a-number', 'text/csv', 'my.csv'),
4812                ):
4813            upload_ctrl = self.browser.getControl(name='uploadfile:file')
4814            upload_ctrl.add_file(StringIO(content), mimetype, name)
4815            self.browser.getControl("Update scores").click()
4816            self.assertEqual(
4817                self.student['studycourse']['100']['COURSE1'].score, 55)
4818            self.assertFalse(
4819                'Uploaded file contains illegal data' in self.browser.contents)
4820
4821    def test_scores_csv_upload_warn_illegal_chars(self):
4822        # for some types of files we issue a warning if upload data
4823        # contains illegal chars (and ignore the data)
4824        self.login_as_lecturer()
4825        self.student['studycourse']['100']['COURSE1'].score = 55
4826        self.browser.open(self.edit_scores_url)
4827        for content, mimetype, name in (
4828                # plain ASCII text, commas, control chars
4829                ('abv,qwe\n\r\r\t\b\n' * 20, 'text/plain', 'my.txt'),
4830                # image data (like a JPEG image)
4831                (open(SAMPLE_IMAGE, 'rb').read(), 'image/jpg', 'my.jpg'),
4832                ):
4833            upload_ctrl = self.browser.getControl(name='uploadfile:file')
4834            upload_ctrl.add_file(StringIO(content), mimetype, name)
4835            self.browser.getControl("Update editable scores").click()
4836            self.assertEqual(
4837                self.student['studycourse']['100']['COURSE1'].score, 55)
4838            self.assertTrue(
4839                'Uploaded file contains illegal data' in self.browser.contents)
4840
4841class ParentsUITests(StudentsFullSetup):
4842    # Tests for UI actions when acting as parents.
4843
4844    def test_request_ppw(self):
4845        self.app['students'][self.student_id].parents_email = 'par@yy.zz'
4846        self.browser.open('http://localhost/app/requestppw')
4847        self.browser.getControl(name="form.lastname").value = 'tESTer'
4848        self.browser.getControl(name="form.number").value = '123'
4849        self.browser.getControl(name="form.email").value = 'par@yy.zz'
4850        self.browser.getControl("Send temporary login credentials").click()
4851        self.assertTrue('Your password request was successful.'
4852            in self.browser.contents)
4853        logfile = os.path.join(
4854            self.app['datacenter'].storage, 'logs', 'main.log')
4855        logcontent = open(logfile).read()
4856        self.assertTrue('zope.anybody - students.browser.RequestParentsPasswordPage - '
4857                        '123 (K1000000) - par@yy.zz' in logcontent)
4858        return
4859
4860    def test_login_as_parents(self):
4861        # Student login still works after all the changes made
4862        self.browser.open(self.login_path)
4863        self.browser.getControl(name="form.login").value = self.student_id
4864        self.browser.getControl(name="form.password").value = 'spwd'
4865        self.browser.getControl("Login").click()
4866        self.assertTrue('You logged in' in self.browser.contents)
4867        self.browser.open(self.edit_personal_path)
4868        self.browser.getLink("Logout").click()
4869        self.assertTrue('You have been logged out' in self.browser.contents)
4870        # We set parents password
4871        self.app['students'][self.student_id].setParentsPassword('ppwd')
4872        self.browser.open(self.login_path)
4873        # Student can't login with original password
4874        self.browser.getControl(name="form.login").value = self.student_id
4875        self.browser.getControl(name="form.password").value = 'spwd'
4876        self.browser.getControl("Login").click()
4877        self.assertEqual(self.browser.url, self.login_path)
4878        self.assertTrue('Your account has been temporarily deactivated '
4879            'because your parents have logged in.' in self.browser.contents)
4880        # Parents can login with their password
4881        self.browser.open(self.login_path)
4882        self.browser.getControl(name="form.login").value = self.student_id
4883        self.browser.getControl(name="form.password").value = 'ppwd'
4884        self.browser.getControl("Login").click()
4885        self.assertTrue(
4886            'You logged in.' in self.browser.contents)
4887        self.assertTrue(
4888            '<a href="http://localhost/app/students/K1000000">Base Data</a>'
4889            in self.browser.contents)
4890        # They do not see all links ...
4891        self.assertFalse(
4892            '<a href="http://localhost/app/students/K1000000/history">History</a>'
4893            in self.browser.contents)
4894        # ... and can't change anything
4895        self.assertRaises(
4896            Unauthorized, self.browser.open, self.edit_personal_path)
4897        # If the password has expired, parents are logged out and the
4898        # student can login again with the original password
4899        delta = timedelta(minutes=11)
4900        self.app['students'][self.student_id].parents_password[
4901            'timestamp'] = datetime.utcnow() - delta
4902        self.app['students'][self.student_id]._p_changed = True
4903        self.assertRaises(
4904            Unauthorized, self.browser.open, self.student_path)
4905        # Parents login is written to log file
4906        logfile = os.path.join(
4907            self.app['datacenter'].storage, 'logs', 'students.log')
4908        logcontent = open(logfile).read()
4909        self.assertTrue(
4910            'K1000000 - browser.pages.LoginPage - K1000000 - Parents logged in'
4911            in logcontent)
Note: See TracBrowser for help on using the repository browser.