source: main/waeup.kofa/trunk/src/waeup/kofa/students/tests/test_browser.py @ 10637

Last change on this file since 10637 was 10637, checked in by Henrik Bettermann, 11 years ago

Scores can be removed.

  • Property svn:keywords set to Id
File size: 176.6 KB
Line 
1## $Id: test_browser.py 10637 2013-09-22 05:07:40Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""
19Test the student-related UI components.
20"""
21import shutil
22import tempfile
23import pytz
24import base64
25from datetime import datetime, timedelta, date
26from StringIO import StringIO
27import os
28import grok
29from zc.async.testing import wait_for_result
30from zope.event import notify
31from zope.component import createObject, queryUtility, getUtility
32from zope.component.hooks import setSite, clearSite
33from zope.catalog.interfaces import ICatalog
34from zope.security.interfaces import Unauthorized
35from zope.securitypolicy.interfaces import IPrincipalRoleManager
36from zope.testbrowser.testing import Browser
37from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState
38from waeup.kofa.testing import FunctionalLayer, FunctionalTestCase
39from waeup.kofa.app import University
40from waeup.kofa.payments.interfaces import IPayer
41from waeup.kofa.students.interfaces import IStudentsUtils
42from waeup.kofa.students.student import Student
43from waeup.kofa.students.studylevel import StudentStudyLevel
44from waeup.kofa.university.faculty import Faculty
45from waeup.kofa.university.department import Department
46from waeup.kofa.interfaces import IUserAccount, IJobManager
47from waeup.kofa.authentication import LocalRoleSetEvent
48from waeup.kofa.hostels.hostel import Hostel, Bed, NOT_OCCUPIED
49from waeup.kofa.tests.test_async import FunctionalAsyncTestCase
50from waeup.kofa.browser.tests.test_pdf import samples_dir
51
52PH_LEN = 15911  # Length of placeholder file
53
54SAMPLE_IMAGE = os.path.join(os.path.dirname(__file__), 'test_image.jpg')
55SAMPLE_IMAGE_BMP = os.path.join(os.path.dirname(__file__), 'test_image.bmp')
56
57def lookup_submit_value(name, value, browser):
58    """Find a button with a certain value."""
59    for num in range(0, 100):
60        try:
61            button = browser.getControl(name=name, index=num)
62            if button.value.endswith(value):
63                return button
64        except IndexError:
65            break
66    return None
67
68class StudentsFullSetup(FunctionalTestCase):
69    # A test case that only contains a setup and teardown
70    #
71    # Complete setup for students handlings is rather complex and
72    # requires lots of things created before we can start. This is a
73    # setup that does all this, creates a university, creates PINs,
74    # etc.  so that we do not have to bother with that in different
75    # test cases.
76
77    layer = FunctionalLayer
78
79    def setUp(self):
80        super(StudentsFullSetup, self).setUp()
81
82        # Setup a sample site for each test
83        app = University()
84        self.dc_root = tempfile.mkdtemp()
85        app['datacenter'].setStoragePath(self.dc_root)
86
87        # Prepopulate the ZODB...
88        self.getRootFolder()['app'] = app
89        # we add the site immediately after creation to the
90        # ZODB. Catalogs and other local utilities are not setup
91        # before that step.
92        self.app = self.getRootFolder()['app']
93        # Set site here. Some of the following setup code might need
94        # to access grok.getSite() and should get our new app then
95        setSite(app)
96
97        # Add student with subobjects
98        student = createObject('waeup.Student')
99        student.firstname = u'Anna'
100        student.lastname = u'Tester'
101        student.reg_number = u'123'
102        student.matric_number = u'234'
103        student.sex = u'm'
104        student.email = 'aa@aa.ng'
105        student.phone = u'1234'
106        self.app['students'].addStudent(student)
107        self.student_id = student.student_id
108        self.student = self.app['students'][self.student_id]
109
110        # Set password
111        IUserAccount(
112            self.app['students'][self.student_id]).setPassword('spwd')
113
114        self.login_path = 'http://localhost/app/login'
115        self.container_path = 'http://localhost/app/students'
116        self.manage_container_path = self.container_path + '/@@manage'
117        self.add_student_path = self.container_path + '/addstudent'
118        self.student_path = self.container_path + '/' + self.student_id
119        self.manage_student_path = self.student_path + '/manage_base'
120        self.trigtrans_path = self.student_path + '/trigtrans'
121        self.clearance_path = self.student_path + '/view_clearance'
122        self.personal_path = self.student_path + '/view_personal'
123        self.edit_clearance_path = self.student_path + '/cedit'
124        self.manage_clearance_path = self.student_path + '/manage_clearance'
125        self.edit_personal_path = self.student_path + '/edit_personal'
126        self.manage_personal_path = self.student_path + '/manage_personal'
127        self.studycourse_path = self.student_path + '/studycourse'
128        self.payments_path = self.student_path + '/payments'
129        self.acco_path = self.student_path + '/accommodation'
130        self.history_path = self.student_path + '/history'
131
132        # Create 5 access codes with prefix'PWD'
133        pin_container = self.app['accesscodes']
134        pin_container.createBatch(
135            datetime.utcnow(), 'some_userid', 'PWD', 9.99, 5)
136        pins = pin_container['PWD-1'].values()
137        self.pwdpins = [x.representation for x in pins]
138        self.existing_pwdpin = self.pwdpins[0]
139        parts = self.existing_pwdpin.split('-')[1:]
140        self.existing_pwdseries, self.existing_pwdnumber = parts
141        # Create 5 access codes with prefix 'CLR'
142        pin_container.createBatch(
143            datetime.now(), 'some_userid', 'CLR', 9.99, 5)
144        pins = pin_container['CLR-1'].values()
145        pins[0].owner = u'Hans Wurst'
146        self.existing_clrac = pins[0]
147        self.existing_clrpin = pins[0].representation
148        parts = self.existing_clrpin.split('-')[1:]
149        self.existing_clrseries, self.existing_clrnumber = parts
150        # Create 2 access codes with prefix 'HOS'
151        pin_container.createBatch(
152            datetime.now(), 'some_userid', 'HOS', 9.99, 2)
153        pins = pin_container['HOS-1'].values()
154        self.existing_hosac = pins[0]
155        self.existing_hospin = pins[0].representation
156        parts = self.existing_hospin.split('-')[1:]
157        self.existing_hosseries, self.existing_hosnumber = parts
158
159        # Populate university
160        self.certificate = createObject('waeup.Certificate')
161        self.certificate.code = u'CERT1'
162        self.certificate.application_category = 'basic'
163        self.certificate.study_mode = 'ug_ft'
164        self.certificate.start_level = 100
165        self.certificate.end_level = 500
166        self.certificate.school_fee_1 = 40000.0
167        self.certificate.school_fee_2 = 20000.0
168        self.app['faculties']['fac1'] = Faculty(code=u'fac1')
169        self.app['faculties']['fac1']['dep1'] = Department(code=u'dep1')
170        self.app['faculties']['fac1']['dep1'].certificates.addCertificate(
171            self.certificate)
172        self.course = createObject('waeup.Course')
173        self.course.code = 'COURSE1'
174        self.course.semester = 1
175        self.course.credits = 10
176        self.course.passmark = 40
177        self.app['faculties']['fac1']['dep1'].courses.addCourse(
178            self.course)
179        self.app['faculties']['fac1']['dep1'].certificates['CERT1'].addCertCourse(
180            self.course, level=100)
181
182        # Configure university and hostels
183        self.app['hostels'].accommodation_states = ['admitted']
184        self.app['hostels'].accommodation_session = 2004
185        delta = timedelta(days=10)
186        self.app['hostels'].startdate = datetime.now(pytz.utc) - delta
187        self.app['hostels'].enddate = datetime.now(pytz.utc) + delta
188        self.app['configuration'].carry_over = True
189        configuration = createObject('waeup.SessionConfiguration')
190        configuration.academic_session = 2004
191        configuration.clearance_fee = 3456.0
192        configuration.transcript_fee = 4567.0
193        configuration.booking_fee = 123.4
194        configuration.maint_fee = 987.0
195        self.app['configuration'].addSessionConfiguration(configuration)
196
197        # Create a hostel with two beds
198        hostel = Hostel()
199        hostel.hostel_id = u'hall-1'
200        hostel.hostel_name = u'Hall 1'
201        self.app['hostels'].addHostel(hostel)
202        bed = Bed()
203        bed.bed_id = u'hall-1_A_101_A'
204        bed.bed_number = 1
205        bed.owner = NOT_OCCUPIED
206        bed.bed_type = u'regular_male_fr'
207        self.app['hostels'][hostel.hostel_id].addBed(bed)
208        bed = Bed()
209        bed.bed_id = u'hall-1_A_101_B'
210        bed.bed_number = 2
211        bed.owner = NOT_OCCUPIED
212        bed.bed_type = u'regular_female_fr'
213        self.app['hostels'][hostel.hostel_id].addBed(bed)
214
215        # Set study course attributes of test student
216        self.student['studycourse'].certificate = self.certificate
217        self.student['studycourse'].current_session = 2004
218        self.student['studycourse'].entry_session = 2004
219        self.student['studycourse'].current_verdict = 'A'
220        self.student['studycourse'].current_level = 100
221        # Update the catalog
222        notify(grok.ObjectModifiedEvent(self.student))
223
224        # Put the prepopulated site into test ZODB and prepare test
225        # browser
226        self.browser = Browser()
227        self.browser.handleErrors = False
228
229    def tearDown(self):
230        super(StudentsFullSetup, self).tearDown()
231        clearSite()
232        shutil.rmtree(self.dc_root)
233
234
235
236class StudentsContainerUITests(StudentsFullSetup):
237    # Tests for StudentsContainer class views and pages
238
239    layer = FunctionalLayer
240
241    def test_anonymous_access(self):
242        # Anonymous users can't access students containers
243        self.assertRaises(
244            Unauthorized, self.browser.open, self.container_path)
245        self.assertRaises(
246            Unauthorized, self.browser.open, self.manage_container_path)
247        return
248
249    def test_manage_access(self):
250        # Managers can access the view page of students
251        # containers and can perform actions
252        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
253        self.browser.open(self.container_path)
254        self.assertEqual(self.browser.headers['Status'], '200 Ok')
255        self.assertEqual(self.browser.url, self.container_path)
256        self.browser.getLink("Manage student section").click()
257        self.assertEqual(self.browser.headers['Status'], '200 Ok')
258        self.assertEqual(self.browser.url, self.manage_container_path)
259        return
260
261    def test_add_search_delete_students(self):
262        # Managers can add search and remove students
263        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
264        self.browser.open(self.manage_container_path)
265        self.browser.getLink("Add student").click()
266        self.assertEqual(self.browser.headers['Status'], '200 Ok')
267        self.assertEqual(self.browser.url, self.add_student_path)
268        self.browser.getControl(name="form.firstname").value = 'Bob'
269        self.browser.getControl(name="form.lastname").value = 'Tester'
270        self.browser.getControl(name="form.reg_number").value = '123'
271        self.browser.getControl("Create student record").click()
272        self.assertTrue('Registration number exists already'
273            in self.browser.contents)
274        self.browser.getControl(name="form.reg_number").value = '1234'
275        self.browser.getControl("Create student record").click()
276        self.assertTrue('Student record created' in self.browser.contents)
277
278        # Registration and matric numbers must be unique
279        self.browser.getLink("Manage").click()
280        self.browser.getControl(name="form.reg_number").value = '123'
281        self.browser.getControl("Save").click()
282        self.assertMatches('...Registration number exists...',
283                           self.browser.contents)
284        self.browser.getControl(name="form.reg_number").value = '789'
285        self.browser.getControl(name="form.matric_number").value = '234'
286        self.browser.getControl("Save").click()
287        self.assertMatches('...Matriculation number exists...',
288                           self.browser.contents)
289
290        # We can find a student with a certain student_id
291        self.browser.open(self.container_path)
292        self.browser.getControl("Search").click()
293        self.assertTrue('Empty search string' in self.browser.contents)
294        self.browser.getControl(name="searchtype").value = ['student_id']
295        self.browser.getControl(name="searchterm").value = self.student_id
296        self.browser.getControl("Search").click()
297        self.assertTrue('Anna Tester' in self.browser.contents)
298
299        # We can find a student in a certain session
300        self.browser.open(self.container_path)
301        self.browser.getControl(name="searchtype").value = ['current_session']
302        self.browser.getControl(name="searchterm").value = '2004'
303        self.browser.getControl("Search").click()
304        self.assertTrue('Anna Tester' in self.browser.contents)
305        # Session fileds require integer values
306        self.browser.open(self.container_path)
307        self.browser.getControl(name="searchtype").value = ['current_session']
308        self.browser.getControl(name="searchterm").value = '2004/2005'
309        self.browser.getControl("Search").click()
310        self.assertTrue('Only year dates allowed' in self.browser.contents)
311        self.browser.open(self.manage_container_path)
312        self.browser.getControl(name="searchtype").value = ['current_session']
313        self.browser.getControl(name="searchterm").value = '2004/2005'
314        self.browser.getControl("Search").click()
315        self.assertTrue('Only year dates allowed' in self.browser.contents)
316
317        # We can find a student in a certain study_mode
318        self.browser.open(self.container_path)
319        self.browser.getControl(name="searchtype").value = ['current_mode']
320        self.browser.getControl(name="searchterm").value = 'ug_ft'
321        self.browser.getControl("Search").click()
322        self.assertTrue('Anna Tester' in self.browser.contents)
323
324        # We can find a student in a certain department
325        self.browser.open(self.container_path)
326        self.browser.getControl(name="searchtype").value = ['depcode']
327        self.browser.getControl(name="searchterm").value = 'dep1'
328        self.browser.getControl("Search").click()
329        self.assertTrue('Anna Tester' in self.browser.contents)
330
331        # We can find a student by searching for all kind of name parts
332        self.browser.open(self.manage_container_path)
333        self.browser.getControl("Search").click()
334        self.assertTrue('Empty search string' in self.browser.contents)
335        self.browser.getControl(name="searchtype").value = ['fullname']
336        self.browser.getControl(name="searchterm").value = 'Anna Tester'
337        self.browser.getControl("Search").click()
338        self.assertTrue('Anna Tester' in self.browser.contents)
339        self.browser.open(self.manage_container_path)
340        self.browser.getControl(name="searchtype").value = ['fullname']
341        self.browser.getControl(name="searchterm").value = 'Anna'
342        self.browser.getControl("Search").click()
343        self.assertTrue('Anna Tester' in self.browser.contents)
344        self.browser.open(self.manage_container_path)
345        self.browser.getControl(name="searchtype").value = ['fullname']
346        self.browser.getControl(name="searchterm").value = 'Tester'
347        self.browser.getControl("Search").click()
348        self.assertTrue('Anna Tester' in self.browser.contents)
349        self.browser.open(self.manage_container_path)
350        self.browser.getControl(name="searchtype").value = ['fullname']
351        self.browser.getControl(name="searchterm").value = 'An'
352        self.browser.getControl("Search").click()
353        self.assertFalse('Anna Tester' in self.browser.contents)
354        self.browser.open(self.manage_container_path)
355        self.browser.getControl(name="searchtype").value = ['fullname']
356        self.browser.getControl(name="searchterm").value = 'An*'
357        self.browser.getControl("Search").click()
358        self.assertTrue('Anna Tester' in self.browser.contents)
359        self.browser.open(self.manage_container_path)
360        self.browser.getControl(name="searchtype").value = ['fullname']
361        self.browser.getControl(name="searchterm").value = 'tester'
362        self.browser.getControl("Search").click()
363        self.assertTrue('Anna Tester' in self.browser.contents)
364        self.browser.open(self.manage_container_path)
365        self.browser.getControl(name="searchtype").value = ['fullname']
366        self.browser.getControl(name="searchterm").value = 'Tester Ana'
367        self.browser.getControl("Search").click()
368        self.assertFalse('Anna Tester' in self.browser.contents)
369        self.browser.open(self.manage_container_path)
370        self.browser.getControl(name="searchtype").value = ['fullname']
371        self.browser.getControl(name="searchterm").value = 'Tester Anna'
372        self.browser.getControl("Search").click()
373        self.assertTrue('Anna Tester' in self.browser.contents)
374        # The old searchterm will be used again
375        self.browser.getControl("Search").click()
376        self.assertTrue('Anna Tester' in self.browser.contents)
377
378        # We can find suspended students
379        self.student.suspended = True
380        notify(grok.ObjectModifiedEvent(self.student))
381        self.browser.open(self.manage_container_path)
382        self.browser.getControl(name="searchtype").value = ['suspended']
383        self.browser.getControl("Search").click()
384        self.assertTrue('Anna Tester' in self.browser.contents)
385        self.browser.open(self.container_path)
386        self.browser.getControl(name="searchtype").value = ['suspended']
387        self.browser.getControl("Search").click()
388        self.assertTrue('Anna Tester' in self.browser.contents)
389
390        # The catalog is informed when studycourse objects have been
391        # edited
392        self.browser.open(self.studycourse_path + '/manage')
393        self.browser.getControl(name="form.current_session").value = ['2010']
394        self.browser.getControl(name="form.entry_session").value = ['2010']
395        self.browser.getControl(name="form.entry_mode").value = ['ug_ft']
396        self.browser.getControl("Save").click()
397
398        # We can find the student in the new session
399        self.browser.open(self.manage_container_path)
400        self.browser.getControl(name="searchtype").value = ['current_session']
401        self.browser.getControl(name="searchterm").value = '2010'
402        self.browser.getControl("Search").click()
403        self.assertTrue('Anna Tester' in self.browser.contents)
404
405        ctrl = self.browser.getControl(name='entries')
406        ctrl.getControl(value=self.student_id).selected = True
407        self.browser.getControl("Remove selected", index=0).click()
408        self.assertTrue('Successfully removed' in self.browser.contents)
409        self.browser.getControl(name="searchtype").value = ['student_id']
410        self.browser.getControl(name="searchterm").value = self.student_id
411        self.browser.getControl("Search").click()
412        self.assertTrue('No student found' in self.browser.contents)
413
414        self.browser.open(self.container_path)
415        self.browser.getControl(name="searchtype").value = ['student_id']
416        self.browser.getControl(name="searchterm").value = self.student_id
417        self.browser.getControl("Search").click()
418        self.assertTrue('No student found' in self.browser.contents)
419        return
420
421class OfficerUITests(StudentsFullSetup):
422    # Tests for Student class views and pages
423
424    def test_student_properties(self):
425        self.student['studycourse'].current_level = 100
426        self.assertEqual(self.student.current_level, 100)
427        self.student['studycourse'].current_session = 2011
428        self.assertEqual(self.student.current_session, 2011)
429        self.student['studycourse'].current_verdict = 'A'
430        self.assertEqual(self.student.current_verdict, 'A')
431        return
432
433    def test_studylevelmanagepage(self):
434        studylevel = StudentStudyLevel()
435        studylevel.level = 100
436        cert = self.app['faculties']['fac1']['dep1'].certificates['CERT1']
437        self.student['studycourse'].addStudentStudyLevel(
438            cert,studylevel)
439        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
440        self.browser.open(self.studycourse_path + '/100/manage')
441        self.assertEqual(self.browser.url, self.studycourse_path + '/100/manage')
442        self.assertEqual(self.browser.headers['Status'], '200 Ok')
443
444    def test_basic_auth(self):
445        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
446        self.browser.open('http://localhost/app')
447        self.browser.getLink("Logout").click()
448        self.assertTrue('You have been logged out' in self.browser.contents)
449        # But we are still logged in since we've used basic authentication here.
450        # Wikipedia says: Existing browsers retain authentication information
451        # until the tab or browser is closed or the user clears the history.
452        # HTTP does not provide a method for a server to direct clients to
453        # discard these cached credentials. This means that there is no
454        # effective way for a server to "log out" the user without closing
455        # the browser. This is a significant defect that requires browser
456        # manufacturers to support a "logout" user interface element ...
457        self.assertTrue('Manager' in self.browser.contents)
458
459    def test_basic_auth_base64(self):
460        auth_token = base64.b64encode('mgr:mgrpw')
461        self.browser.addHeader('Authorization', 'Basic %s' % auth_token)
462        self.browser.open(self.manage_container_path)
463        self.assertEqual(self.browser.headers['Status'], '200 Ok')
464
465    def test_manage_access(self):
466        # Managers can access the pages of students
467        # and can perform actions
468        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
469        self.browser.open(self.student_path)
470        self.assertEqual(self.browser.headers['Status'], '200 Ok')
471        self.assertEqual(self.browser.url, self.student_path)
472        self.browser.getLink("Trigger").click()
473        self.assertEqual(self.browser.headers['Status'], '200 Ok')
474        # Managers can trigger transitions
475        self.browser.getControl(name="transition").value = ['admit']
476        self.browser.getControl("Save").click()
477        # Managers can edit base
478        self.browser.open(self.student_path)
479        self.browser.getLink("Manage").click()
480        self.assertEqual(self.browser.url, self.manage_student_path)
481        self.assertEqual(self.browser.headers['Status'], '200 Ok')
482        self.browser.getControl(name="form.firstname").value = 'John'
483        self.browser.getControl(name="form.lastname").value = 'Tester'
484        self.browser.getControl(name="form.reg_number").value = '345'
485        self.browser.getControl(name="password").value = 'secret'
486        self.browser.getControl(name="control_password").value = 'secret'
487        self.browser.getControl("Save").click()
488        self.assertMatches('...Form has been saved...',
489                           self.browser.contents)
490        self.browser.open(self.student_path)
491        self.browser.getLink("Clearance Data").click()
492        self.assertEqual(self.browser.headers['Status'], '200 Ok')
493        self.assertEqual(self.browser.url, self.clearance_path)
494        self.browser.getLink("Manage").click()
495        self.assertEqual(self.browser.headers['Status'], '200 Ok')
496        self.assertEqual(self.browser.url, self.manage_clearance_path)
497        self.browser.getControl(name="form.date_of_birth").value = '09/10/1961'
498        self.browser.getControl("Save").click()
499        self.assertMatches('...Form has been saved...',
500                           self.browser.contents)
501
502        self.browser.open(self.student_path)
503        self.browser.getLink("Personal Data").click()
504        self.assertEqual(self.browser.headers['Status'], '200 Ok')
505        self.assertEqual(self.browser.url, self.personal_path)
506        self.browser.getLink("Manage").click()
507        self.assertEqual(self.browser.headers['Status'], '200 Ok')
508        self.assertEqual(self.browser.url, self.manage_personal_path)
509        self.browser.open(self.personal_path)
510        self.assertTrue('Updated' in self.browser.contents)
511        self.browser.getLink("Edit").click()
512        self.assertEqual(self.browser.headers['Status'], '200 Ok')
513        self.assertEqual(self.browser.url, self.edit_personal_path)
514        self.browser.getControl("Save").click()
515        # perm_address is required in IStudentPersonalEdit
516        self.assertMatches('...Required input is missing...',
517                           self.browser.contents)
518        self.browser.getControl(name="form.perm_address").value = 'My address!'
519        self.browser.getControl("Save").click()
520        self.assertMatches('...Form has been saved...',
521                           self.browser.contents)
522
523        # Managers can browse all subobjects
524        self.browser.open(self.student_path)
525        self.browser.getLink("Payments").click()
526        self.assertEqual(self.browser.headers['Status'], '200 Ok')
527        self.assertEqual(self.browser.url, self.payments_path)
528        self.browser.open(self.student_path)
529        self.browser.getLink("Accommodation").click()
530        self.assertEqual(self.browser.headers['Status'], '200 Ok')
531        self.assertEqual(self.browser.url, self.acco_path)
532        self.browser.open(self.student_path)
533        self.browser.getLink("History").click()
534        self.assertEqual(self.browser.headers['Status'], '200 Ok')
535        self.assertEqual(self.browser.url, self.history_path)
536        self.assertMatches('...Admitted by Manager...',
537                           self.browser.contents)
538        # Only the Application Slip does not exist
539        self.assertFalse('Application Slip' in self.browser.contents)
540        return
541
542    def test_manage_contact_student(self):
543        # Managers can contact student
544        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
545        self.student.email = None
546        self.browser.open(self.student_path)
547        self.browser.getLink("Send email").click()
548        self.browser.getControl(name="form.subject").value = 'Important subject'
549        self.browser.getControl(name="form.body").value = 'Hello!'
550        self.browser.getControl("Send message now").click()
551        self.assertTrue('An smtp server error occurred' in self.browser.contents)
552        self.student.email = 'xx@yy.zz'
553        self.browser.getControl("Send message now").click()
554        self.assertTrue('Your message has been sent' in self.browser.contents)
555        return
556
557    def test_manage_remove_department(self):
558        # Lazy student is studying CERT1
559        lazystudent = Student()
560        lazystudent.firstname = u'Lazy'
561        lazystudent.lastname = u'Student'
562        self.app['students'].addStudent(lazystudent)
563        student_id = lazystudent.student_id
564        student_path = self.container_path + '/' + student_id
565        lazystudent['studycourse'].certificate = self.certificate
566        notify(grok.ObjectModifiedEvent(lazystudent))
567        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
568        self.browser.open(student_path + '/studycourse')
569        self.assertTrue('CERT1' in self.browser.contents)
570        # After some years the department is removed
571        del self.app['faculties']['fac1']['dep1']
572        # So CERT1 does no longer exist and lazy student's
573        # certificate reference is removed too
574        self.browser.open(student_path + '/studycourse')
575        self.assertEqual(self.browser.headers['Status'], '200 Ok')
576        self.assertEqual(self.browser.url, student_path + '/studycourse')
577        self.assertFalse('CERT1' in self.browser.contents)
578        self.assertMatches('...<div>--</div>...',
579                           self.browser.contents)
580
581    def test_manage_upload_file(self):
582        # Managers can upload a file via the StudentClearanceManageFormPage
583        # The image is stored even if form has errors
584        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
585        self.browser.open(self.manage_clearance_path)
586        # No birth certificate has been uploaded yet
587        # Browsing the link shows a placerholder image
588        self.browser.open('birth_certificate')
589        self.assertEqual(
590            self.browser.headers['content-type'], 'image/jpeg')
591        self.assertEqual(len(self.browser.contents), PH_LEN)
592        # Create a pseudo image file and select it to be uploaded in form
593        # as birth certificate
594        self.browser.open(self.manage_clearance_path)
595        image = open(SAMPLE_IMAGE, 'rb')
596        ctrl = self.browser.getControl(name='birthcertificateupload')
597        file_ctrl = ctrl.mech_control
598        file_ctrl.add_file(image, filename='my_birth_certificate.jpg')
599        # The Save action does not upload files
600        self.browser.getControl("Save").click() # submit form
601        self.assertFalse(
602            '<a target="image" href="birth_certificate">'
603            in self.browser.contents)
604        # ... but the correct upload submit button does
605        image = open(SAMPLE_IMAGE)
606        ctrl = self.browser.getControl(name='birthcertificateupload')
607        file_ctrl = ctrl.mech_control
608        file_ctrl.add_file(image, filename='my_birth_certificate.jpg')
609        self.browser.getControl(
610            name='upload_birthcertificateupload').click()
611        # There is a correct <img> link included
612        self.assertTrue(
613            '<a target="image" href="birth_certificate">'
614            in self.browser.contents)
615        # Browsing the link shows a real image
616        self.browser.open('birth_certificate')
617        self.assertEqual(
618            self.browser.headers['content-type'], 'image/jpeg')
619        self.assertEqual(len(self.browser.contents), 2787)
620        # Reuploading a file which is bigger than 150k will raise an error
621        self.browser.open(self.manage_clearance_path)
622        # An image > 150K
623        big_image = StringIO(open(SAMPLE_IMAGE, 'rb').read() * 75)
624        ctrl = self.browser.getControl(name='birthcertificateupload')
625        file_ctrl = ctrl.mech_control
626        file_ctrl.add_file(big_image, filename='my_birth_certificate.jpg')
627        self.browser.getControl(
628            name='upload_birthcertificateupload').click()
629        self.assertTrue(
630            'Uploaded file is too big' in self.browser.contents)
631        # we do not rely on filename extensions given by uploaders
632        image = open(SAMPLE_IMAGE, 'rb') # a jpg-file
633        ctrl = self.browser.getControl(name='birthcertificateupload')
634        file_ctrl = ctrl.mech_control
635        # tell uploaded file is bmp
636        file_ctrl.add_file(image, filename='my_birth_certificate.bmp')
637        self.browser.getControl(
638            name='upload_birthcertificateupload').click()
639        self.assertTrue(
640            # jpg file was recognized
641            'File birth_certificate.jpg uploaded.' in self.browser.contents)
642        # File names must meet several conditions
643        bmp_image = open(SAMPLE_IMAGE_BMP, 'rb')
644        ctrl = self.browser.getControl(name='birthcertificateupload')
645        file_ctrl = ctrl.mech_control
646        file_ctrl.add_file(bmp_image, filename='my_birth_certificate.bmp')
647        self.browser.getControl(
648            name='upload_birthcertificateupload').click()
649        self.assertTrue('Only the following extensions are allowed'
650            in self.browser.contents)
651        # Managers can delete files
652        self.browser.getControl(name='delete_birthcertificateupload').click()
653        self.assertTrue(
654            'birth_certificate deleted' in self.browser.contents)
655
656        # Managers can upload a file via the StudentBaseManageFormPage
657        self.browser.open(self.manage_student_path)
658        image = open(SAMPLE_IMAGE_BMP, 'rb')
659        ctrl = self.browser.getControl(name='passportuploadmanage')
660        file_ctrl = ctrl.mech_control
661        file_ctrl.add_file(image, filename='my_photo.bmp')
662        self.browser.getControl(
663            name='upload_passportuploadmanage').click()
664        self.assertTrue('jpg file extension expected'
665            in self.browser.contents)
666        ctrl = self.browser.getControl(name='passportuploadmanage')
667        file_ctrl = ctrl.mech_control
668        image = open(SAMPLE_IMAGE, 'rb')
669        file_ctrl.add_file(image, filename='my_photo.jpg')
670        self.browser.getControl(
671            name='upload_passportuploadmanage').click()
672        self.assertTrue(
673            '<img align="middle" height="125px" src="passport.jpg" />'
674            in self.browser.contents)
675        # We remove the passport file again
676        self.browser.open(self.manage_student_path)
677        self.browser.getControl('Delete').click()
678        self.browser.open(self.student_path + '/clearance_slip.pdf')
679        self.assertEqual(self.browser.headers['Status'], '200 Ok')
680        self.assertEqual(self.browser.headers['Content-Type'],
681                         'application/pdf')
682
683    def test_manage_course_lists(self):
684        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
685        self.browser.open(self.student_path)
686        self.browser.getLink("Study Course").click()
687        self.assertEqual(self.browser.headers['Status'], '200 Ok')
688        self.assertEqual(self.browser.url, self.studycourse_path)
689        self.assertTrue('Undergraduate Full-Time' in self.browser.contents)
690        self.browser.getLink("Manage").click()
691        self.assertTrue('Manage study course' in self.browser.contents)
692        # Before we can select a level, the certificate must
693        # be selected and saved
694        self.browser.getControl(name="form.certificate").value = ['CERT1']
695        self.browser.getControl(name="form.current_session").value = ['2004']
696        self.browser.getControl(name="form.current_verdict").value = ['A']
697        self.browser.getControl(name="form.entry_mode").value = ['ug_ft']
698        self.browser.getControl("Save").click()
699        # Now we can save also the current level which depends on start and end
700        # level of the certificate
701        self.browser.getControl(name="form.current_level").value = ['100']
702        self.browser.getControl("Save").click()
703        # Managers can add and remove any study level (course list)
704        self.browser.getControl(name="addlevel").value = ['100']
705        self.browser.getControl("Add study level").click()
706        self.assertMatches(
707            '...You must select a session...', self.browser.contents)
708        self.browser.getControl(name="addlevel").value = ['100']
709        self.browser.getControl(name="level_session").value = ['2004']
710        self.browser.getControl("Add study level").click()
711        self.assertMatches('...<span>100</span>...', self.browser.contents)
712        self.assertEqual(self.student['studycourse']['100'].level, 100)
713        self.assertEqual(self.student['studycourse']['100'].level_session, 2004)
714        self.browser.getControl(name="addlevel").value = ['100']
715        self.browser.getControl(name="level_session").value = ['2004']
716        self.browser.getControl("Add study level").click()
717        self.assertMatches('...This level exists...', self.browser.contents)
718        self.browser.getControl("Remove selected").click()
719        self.assertMatches(
720            '...No study level selected...', self.browser.contents)
721        self.browser.getControl(name="val_id").value = ['100']
722        self.browser.getControl(name="level_session").value = ['2004']
723        self.browser.getControl("Remove selected").click()
724        self.assertMatches('...Successfully removed...', self.browser.contents)
725        # Removing levels is properly logged
726        logfile = os.path.join(
727            self.app['datacenter'].storage, 'logs', 'students.log')
728        logcontent = open(logfile).read()
729        self.assertTrue('zope.mgr - students.browser.StudyCourseManageFormPage '
730                        '- K1000000 - removed: 100' in logcontent)
731        # Add level again
732        self.browser.getControl(name="addlevel").value = ['100']
733        self.browser.getControl(name="level_session").value = ['2004']
734        self.browser.getControl("Add study level").click()
735
736        # Managers can view and manage course lists
737        self.browser.getLink("100").click()
738        self.assertMatches(
739            '...: Study Level 100 (Year 1)...', self.browser.contents)
740        self.browser.getLink("Manage").click()
741        self.browser.getControl(name="form.level_session").value = ['2002']
742        self.browser.getControl("Save").click()
743        self.browser.getControl("Remove selected").click()
744        self.assertMatches('...No ticket selected...', self.browser.contents)
745        ctrl = self.browser.getControl(name='val_id')
746        ctrl.getControl(value='COURSE1').selected = True
747        self.browser.getControl("Remove selected", index=0).click()
748        self.assertTrue('Successfully removed' in self.browser.contents)
749        # Removing course tickets is properly logged
750        logfile = os.path.join(
751            self.app['datacenter'].storage, 'logs', 'students.log')
752        logcontent = open(logfile).read()
753        self.assertTrue('zope.mgr - students.browser.StudyLevelManageFormPage '
754        '- K1000000 - removed: COURSE1 at 100' in logcontent)
755        self.browser.getLink("here").click()
756        self.browser.getControl(name="form.course").value = ['COURSE1']
757        self.course.credits = 100
758        self.browser.getControl("Add course ticket").click()
759        self.assertMatches(
760            '...Total credits exceed 50...', self.browser.contents)
761        self.course.credits = 10
762        self.browser.getControl("Add course ticket").click()
763        self.assertTrue('Successfully added' in self.browser.contents)
764        # We can do the same by adding the course on the manage page directly
765        del self.student['studycourse']['100']['COURSE1']
766        self.browser.getControl(name="course").value = 'COURSE1'
767        self.browser.getControl("Add course ticket").click()
768        self.assertTrue('Successfully added' in self.browser.contents)
769        self.browser.getLink("here").click()
770        self.browser.getControl(name="form.course").value = ['COURSE1']
771        self.browser.getControl("Add course ticket").click()
772        self.assertTrue('The ticket exists' in self.browser.contents)
773        self.browser.getControl("Cancel").click()
774        self.browser.getLink("COURSE1").click()
775        self.browser.getLink("Manage").click()
776        self.browser.getControl("Save").click()
777        self.assertTrue('Form has been saved' in self.browser.contents)
778        # Grade and weight have been determined
779        self.browser.open(self.studycourse_path + '/100/COURSE1')
780        self.assertFalse('Grade' in self.browser.contents)
781        self.assertFalse('Weight' in self.browser.contents)
782        self.student['studycourse']['100']['COURSE1'].score = 55
783        self.browser.open(self.studycourse_path + '/100/COURSE1')
784        self.assertTrue('Grade' in self.browser.contents)
785        self.assertTrue('Weight' in self.browser.contents)
786        self.assertEqual(self.student['studycourse']['100']['COURSE1'].grade, 'C')
787        self.assertEqual(self.student['studycourse']['100']['COURSE1'].weight, 3)
788        # We add another ticket to check if GPA will be correctly calculated
789        # (and rounded)
790        courseticket = createObject('waeup.CourseTicket')
791        courseticket.code = 'ANYCODE'
792        courseticket.title = u'Any TITLE'
793        courseticket.credits = 13
794        courseticket.score = 66
795        courseticket.semester = 1
796        courseticket.dcode = u'ANYDCODE'
797        courseticket.fcode = u'ANYFCODE'
798        self.student['studycourse']['100']['COURSE2'] = courseticket
799        self.browser.open(self.student_path + '/studycourse/100')
800        # total credits
801        self.assertEqual(self.student['studycourse']['100'].gpa_params_rectified[1], 23)
802        # weigheted credits = 3 * 10 + 4 * 13
803        self.assertEqual(self.student['studycourse']['100'].gpa_params_rectified[2], 82.0)
804        # sgpa = 82 / 23
805        self.assertEqual(self.student['studycourse']['100'].gpa_params_rectified[0], 3.565)
806        # Carry-over courses will be collected when next level is created
807        self.browser.open(self.student_path + '/studycourse/manage')
808        # Add next level
809        self.student['studycourse']['100']['COURSE1'].score = 10
810        self.browser.getControl(name="addlevel").value = ['200']
811        self.browser.getControl(name="level_session").value = ['2005']
812        self.browser.getControl("Add study level").click()
813        self.browser.getLink("200").click()
814        self.assertMatches(
815            '...: Study Level 200 (Year 2)...', self.browser.contents)
816        # Since COURSE1 has score 10 it becomes a carry-over course
817        # in level 200
818        self.assertEqual(
819            sorted(self.student['studycourse']['200'].keys()), [u'COURSE1'])
820        self.assertTrue(
821            self.student['studycourse']['200']['COURSE1'].carry_over)
822        # Passed and failed courses have been counted
823        self.assertEqual(
824            self.student['studycourse']['100'].passed_params,
825            (1, 1, 13, 10, ['COURSE1']))
826        self.assertEqual(
827            self.student['studycourse']['200'].passed_params,
828            (0, 0, 0, 0, []))
829        # And also cumulative params can be calculated. Meanwhile we have the
830        # following courses: COURSE1 and COURSE2 in level 100 and
831        # COURSE1 as carry-over course in level 200.
832        self.assertEqual(
833            self.student['studycourse']['100'].cumulative_params,
834            (2.261, 23, 52.0, 23, 13))
835        # COURSE1 in level 200 is not taken into consideration
836        # when calculating the gpa.
837        self.assertEqual(
838            self.student['studycourse']['200'].cumulative_params,
839            (2.261, 23, 52.0, 33, 13))
840        return
841
842    def test_gpa_calculation_with_carryover(self):
843        studylevel = createObject(u'waeup.StudentStudyLevel')
844        studylevel.level = 100
845        studylevel.level_session = 2005
846        self.student['studycourse'].entry_mode = 'ug_ft'
847        self.student['studycourse'].addStudentStudyLevel(
848            self.certificate, studylevel)
849        # First course has been added automatically.
850        # Set score above passmark.
851        studylevel['COURSE1'].score = studylevel['COURSE1'].passmark + 1
852        # GPA is 1.
853        self.assertEqual(self.student['studycourse']['100'].gpa_params_rectified[0], 1.0)
854        # Set score below passmark.
855        studylevel['COURSE1'].score = studylevel['COURSE1'].passmark - 1
856        # GPA is still 0.
857        self.assertEqual(self.student['studycourse']['100'].gpa_params_rectified[0], 0.0)
858        studylevel2 = createObject(u'waeup.StudentStudyLevel')
859        studylevel2.level = 200
860        studylevel2.level_session = 2006
861        self.student['studycourse'].addStudentStudyLevel(
862            self.certificate, studylevel2)
863        # Carry-over course has been autonatically added.
864        studylevel2['COURSE1'].score = 66
865        # The score of the carry-over course is now used for calculation of the
866        # GPA at level 100 ...
867        self.assertEqual(self.student['studycourse']['100'].gpa_params_rectified[0], 4.0)
868        # ... but not at level 200
869        self.assertEqual(self.student['studycourse']['200'].gpa_params_rectified[0], 0.0)
870        return
871
872    def test_manage_payments(self):
873        # Managers can add online school fee payment tickets
874        # if certain requirements are met
875        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
876        self.browser.open(self.payments_path)
877        IWorkflowState(self.student).setState('cleared')
878        self.browser.getLink("Add current session payment ticket").click()
879        self.browser.getControl(name="form.p_category").value = ['schoolfee']
880        self.browser.getControl("Create ticket").click()
881        self.assertMatches('...ticket created...',
882                           self.browser.contents)
883        ctrl = self.browser.getControl(name='val_id')
884        value = ctrl.options[0]
885        self.browser.getLink(value).click()
886        self.assertMatches('...Amount Authorized...',
887                           self.browser.contents)
888        self.assertEqual(self.student['payments'][value].amount_auth, 40000.0)
889        payment_url = self.browser.url
890
891        # The pdf payment slip can't yet be opened
892        #self.browser.open(payment_url + '/payment_slip.pdf')
893        #self.assertMatches('...Ticket not yet paid...',
894        #                   self.browser.contents)
895
896        # The same payment (with same p_item, p_session and p_category)
897        # can be initialized a second time if the former ticket is not yet paid.
898        self.browser.open(self.payments_path)
899        self.browser.getLink("Add current session payment ticket").click()
900        self.browser.getControl(name="form.p_category").value = ['schoolfee']
901        self.browser.getControl("Create ticket").click()
902        self.assertMatches('...Payment ticket created...',
903                           self.browser.contents)
904
905        # The ticket can be found in the payments_catalog
906        cat = queryUtility(ICatalog, name='payments_catalog')
907        results = list(cat.searchResults(p_state=('unpaid', 'unpaid')))
908        self.assertTrue(len(results), 1)
909        self.assertTrue(results[0] is self.student['payments'][value])
910
911        # Managers can approve the payment
912        self.assertEqual(len(self.app['accesscodes']['SFE-0']),0)
913        self.browser.open(payment_url)
914        self.browser.getLink("Approve payment").click()
915        self.assertMatches('...Payment approved...',
916                          self.browser.contents)
917        # Approval is logged in students.log ...
918        logfile = os.path.join(
919            self.app['datacenter'].storage, 'logs', 'students.log')
920        logcontent = open(logfile).read()
921        self.assertTrue(
922            'zope.mgr - students.browser.OnlinePaymentApprovePage '
923            '- K1000000 - schoolfee payment approved'
924            in logcontent)
925        # ... and in payments.log
926        logfile = os.path.join(
927            self.app['datacenter'].storage, 'logs', 'payments.log')
928        logcontent = open(logfile).read()
929        self.assertTrue(
930            '"zope.mgr",K1000000,%s,schoolfee,40000.0,AP,,,,,,\n' % value
931            in logcontent)
932
933        # The authorized amount has been stored in the access code
934        self.assertEqual(
935            self.app['accesscodes']['SFE-0'].values()[0].cost,40000.0)
936
937        # The catalog has been updated
938        results = list(cat.searchResults(p_state=('unpaid', 'unpaid')))
939        self.assertTrue(len(results), 0)
940        results = list(cat.searchResults(p_state=('paid', 'paid')))
941        self.assertTrue(len(results), 1)
942        self.assertTrue(results[0] is self.student['payments'][value])
943
944        # Payments can't be approved twice
945        self.browser.open(payment_url + '/approve')
946        self.assertMatches('...This ticket has already been paid...',
947                          self.browser.contents)
948
949        # Now the first ticket is paid and no more ticket of same type
950        # (with same p_item, p_session and p_category) can be added
951        self.browser.open(self.payments_path)
952        self.browser.getLink("Add current session payment ticket").click()
953        self.browser.getControl(name="form.p_category").value = ['schoolfee']
954        self.browser.getControl("Create ticket").click()
955        self.assertMatches(
956            '...This type of payment has already been made...',
957            self.browser.contents)
958
959        # Managers can open the pdf payment slip
960        self.browser.open(payment_url)
961        self.browser.getLink("Download payment slip").click()
962        self.assertEqual(self.browser.headers['Status'], '200 Ok')
963        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
964
965        # Managers can remove online school fee payment tickets
966        self.browser.open(self.payments_path)
967        self.browser.getControl("Remove selected").click()
968        self.assertMatches('...No payment selected...', self.browser.contents)
969        ctrl = self.browser.getControl(name='val_id')
970        value = ctrl.options[0]
971        ctrl.getControl(value=value).selected = True
972        self.browser.getControl("Remove selected", index=0).click()
973        self.assertTrue('Successfully removed' in self.browser.contents)
974
975        # Managers can add online clearance payment tickets
976        self.browser.open(self.payments_path + '/addop')
977        self.browser.getControl(name="form.p_category").value = ['clearance']
978        self.browser.getControl("Create ticket").click()
979        self.assertMatches('...ticket created...',
980                           self.browser.contents)
981
982        # Managers can approve the payment
983        self.assertEqual(len(self.app['accesscodes']['CLR-0']),0)
984        ctrl = self.browser.getControl(name='val_id')
985        value = ctrl.options[1] # The clearance payment is the second in the table
986        self.browser.getLink(value).click()
987        self.browser.open(self.browser.url + '/approve')
988        self.assertMatches('...Payment approved...',
989                          self.browser.contents)
990        expected = '''...
991        <td>
992          <span>Paid</span>
993        </td>...'''
994        self.assertMatches(expected,self.browser.contents)
995        # The new CLR-0 pin has been created
996        self.assertEqual(len(self.app['accesscodes']['CLR-0']),1)
997        pin = self.app['accesscodes']['CLR-0'].keys()[0]
998        ac = self.app['accesscodes']['CLR-0'][pin]
999        self.assertEqual(ac.owner, self.student_id)
1000        self.assertEqual(ac.cost, 3456.0)
1001
1002        # Managers can add online transcript payment tickets
1003        self.browser.open(self.payments_path + '/addop')
1004        self.browser.getControl(name="form.p_category").value = ['transcript']
1005        self.browser.getControl("Create ticket").click()
1006        self.assertMatches('...ticket created...',
1007                           self.browser.contents)
1008
1009        # Managers can approve the payment
1010        self.assertEqual(len(self.app['accesscodes']['TSC-0']),0)
1011        ctrl = self.browser.getControl(name='val_id')
1012        value = ctrl.options[2] # The clearance payment is the third in the table
1013        self.browser.getLink(value).click()
1014        self.browser.open(self.browser.url + '/approve')
1015        self.assertMatches('...Payment approved...',
1016                          self.browser.contents)
1017        expected = '''...
1018        <td>
1019          <span>Paid</span>
1020        </td>...'''
1021        self.assertMatches(expected,self.browser.contents)
1022        # The new CLR-0 pin has been created
1023        self.assertEqual(len(self.app['accesscodes']['TSC-0']),1)
1024        pin = self.app['accesscodes']['TSC-0'].keys()[0]
1025        ac = self.app['accesscodes']['TSC-0'][pin]
1026        self.assertEqual(ac.owner, self.student_id)
1027        self.assertEqual(ac.cost, 4567.0)
1028        return
1029
1030    def test_manage_balance_payments(self):
1031
1032        # Login
1033        #self.browser.open(self.login_path)
1034        #self.browser.getControl(name="form.login").value = self.student_id
1035        #self.browser.getControl(name="form.password").value = 'spwd'
1036        #self.browser.getControl("Login").click()
1037
1038        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1039        self.browser.open(self.payments_path)
1040
1041        # Managers can add previous school fee payment tickets in any state.
1042        IWorkflowState(self.student).setState('courses registered')
1043        self.browser.open(self.payments_path)
1044        self.browser.getLink("Add balance payment ticket").click()
1045
1046        # Previous session payment form is provided
1047        self.assertEqual(self.student.current_session, 2004)
1048        self.browser.getControl(name="form.p_category").value = ['schoolfee']
1049        self.browser.getControl(name="form.balance_session").value = ['2004']
1050        self.browser.getControl(name="form.balance_level").value = ['300']
1051        self.browser.getControl(name="form.balance_amount").value = '-567.8'
1052        self.browser.getControl("Create ticket").click()
1053        self.assertMatches('...Amount must be greater than 0...',
1054                           self.browser.contents)
1055        self.browser.getControl(name="form.balance_amount").value = '0'
1056        self.browser.getControl("Create ticket").click()
1057        self.assertMatches('...Amount must be greater than 0...',
1058                           self.browser.contents)
1059        self.browser.getControl(name="form.balance_amount").value = '567.8'
1060        self.browser.getControl("Create ticket").click()
1061        self.assertMatches('...ticket created...',
1062                           self.browser.contents)
1063        ctrl = self.browser.getControl(name='val_id')
1064        value = ctrl.options[0]
1065        self.browser.getLink(value).click()
1066        self.assertMatches('...Amount Authorized...',
1067                           self.browser.contents)
1068        self.assertEqual(self.student['payments'][value].amount_auth, 567.8)
1069        # Payment attributes are properly set
1070        self.assertEqual(self.student['payments'][value].p_session, 2004)
1071        self.assertEqual(self.student['payments'][value].p_level, 300)
1072        self.assertEqual(self.student['payments'][value].p_item, u'Balance')
1073        self.assertEqual(self.student['payments'][value].p_category, 'schoolfee')
1074
1075    def test_manage_accommodation(self):
1076        logfile = os.path.join(
1077            self.app['datacenter'].storage, 'logs', 'students.log')
1078        # Managers can add online booking fee payment tickets and open the
1079        # callback view (see test_manage_payments)
1080        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1081        self.browser.open(self.payments_path)
1082        self.browser.getLink("Add current session payment ticket").click()
1083        self.browser.getControl(name="form.p_category").value = ['bed_allocation']
1084        # If student is not in accommodation session, payment cannot be processed
1085        self.app['hostels'].accommodation_session = 2011
1086        self.browser.getControl("Create ticket").click()
1087        self.assertMatches('...Your current session does not match...',
1088                           self.browser.contents)
1089        self.app['hostels'].accommodation_session = 2004
1090        self.browser.getControl(name="form.p_category").value = ['bed_allocation']
1091        self.browser.getControl("Create ticket").click()
1092        ctrl = self.browser.getControl(name='val_id')
1093        value = ctrl.options[0]
1094        self.browser.getLink(value).click()
1095        self.browser.open(self.browser.url + '/approve')
1096        # The new HOS-0 pin has been created
1097        self.assertEqual(len(self.app['accesscodes']['HOS-0']),1)
1098        pin = self.app['accesscodes']['HOS-0'].keys()[0]
1099        ac = self.app['accesscodes']['HOS-0'][pin]
1100        self.assertEqual(ac.owner, self.student_id)
1101        parts = pin.split('-')[1:]
1102        sfeseries, sfenumber = parts
1103        # Managers can use HOS code and book a bed space with it
1104        self.browser.open(self.acco_path)
1105        self.browser.getLink("Book accommodation").click()
1106        self.assertMatches('...You are in the wrong...',
1107                           self.browser.contents)
1108        IWorkflowInfo(self.student).fireTransition('admit')
1109        # An existing HOS code can only be used if students
1110        # are in accommodation session
1111        self.student['studycourse'].current_session = 2003
1112        self.browser.getLink("Book accommodation").click()
1113        self.assertMatches('...Your current session does not match...',
1114                           self.browser.contents)
1115        self.student['studycourse'].current_session = 2004
1116        # All requirements are met and ticket can be created
1117        self.browser.getLink("Book accommodation").click()
1118        self.assertMatches('...Activation Code:...',
1119                           self.browser.contents)
1120        self.browser.getControl(name="ac_series").value = sfeseries
1121        self.browser.getControl(name="ac_number").value = sfenumber
1122        self.browser.getControl("Create bed ticket").click()
1123        self.assertMatches('...Hall 1, Block A, Room 101, Bed A...',
1124                           self.browser.contents)
1125        # Bed has been allocated
1126        bed1 = self.app['hostels']['hall-1']['hall-1_A_101_A']
1127        self.assertTrue(bed1.owner == self.student_id)
1128        # BedTicketAddPage is now blocked
1129        self.browser.getLink("Book accommodation").click()
1130        self.assertMatches('...You already booked a bed space...',
1131            self.browser.contents)
1132        # The bed ticket displays the data correctly
1133        self.browser.open(self.acco_path + '/2004')
1134        self.assertMatches('...Hall 1, Block A, Room 101, Bed A...',
1135                           self.browser.contents)
1136        self.assertMatches('...2004/2005...', self.browser.contents)
1137        self.assertMatches('...regular_male_fr...', self.browser.contents)
1138        self.assertMatches('...%s...' % pin, self.browser.contents)
1139        # Booking is properly logged
1140        logcontent = open(logfile).read()
1141        self.assertTrue('zope.mgr - students.browser.BedTicketAddPage '
1142            '- K1000000 - booked: hall-1_A_101_A' in logcontent)
1143        # Managers can relocate students if the student's bed_type has changed
1144        self.browser.getLink("Relocate student").click()
1145        self.assertMatches(
1146            "...Student can't be relocated...", self.browser.contents)
1147        self.student.sex = u'f'
1148        self.browser.getLink("Relocate student").click()
1149        self.assertMatches(
1150            "...Hall 1, Block A, Room 101, Bed B...", self.browser.contents)
1151        self.assertTrue(bed1.owner == NOT_OCCUPIED)
1152        bed2 = self.app['hostels']['hall-1']['hall-1_A_101_B']
1153        self.assertTrue(bed2.owner == self.student_id)
1154        self.assertTrue(self.student['accommodation'][
1155            '2004'].bed_type == u'regular_female_fr')
1156        # Relocation is properly logged
1157        logcontent = open(logfile).read()
1158        self.assertTrue('zope.mgr - students.browser.BedTicketRelocationPage '
1159            '- K1000000 - relocated: hall-1_A_101_B' in logcontent)
1160        # The payment object still shows the original payment item
1161        payment_id = self.student['payments'].keys()[0]
1162        payment = self.student['payments'][payment_id]
1163        self.assertTrue(payment.p_item == u'regular_male_fr')
1164        # Managers can relocate students if the bed's bed_type has changed
1165        bed1.bed_type = u'regular_female_fr'
1166        bed2.bed_type = u'regular_male_fr'
1167        notify(grok.ObjectModifiedEvent(bed1))
1168        notify(grok.ObjectModifiedEvent(bed2))
1169        self.browser.getLink("Relocate student").click()
1170        self.assertMatches(
1171            "...Student relocated...", self.browser.contents)
1172        self.assertMatches(
1173            "... Hall 1, Block A, Room 101, Bed A...", self.browser.contents)
1174        self.assertMatches(bed1.owner, self.student_id)
1175        self.assertMatches(bed2.owner, NOT_OCCUPIED)
1176        # Managers can't relocate students if bed is reserved
1177        self.student.sex = u'm'
1178        bed1.bed_type = u'regular_female_reserved'
1179        notify(grok.ObjectModifiedEvent(bed1))
1180        self.browser.getLink("Relocate student").click()
1181        self.assertMatches(
1182            "...Students in reserved beds can't be relocated...",
1183            self.browser.contents)
1184        # Managers can relocate students if booking has been cancelled but
1185        # other bed space has been manually allocated after cancellation
1186        old_owner = bed1.releaseBed()
1187        self.assertMatches(old_owner, self.student_id)
1188        bed2.owner = self.student_id
1189        self.browser.open(self.acco_path + '/2004')
1190        self.assertMatches(
1191            "...booking cancelled...", self.browser.contents)
1192        self.browser.getLink("Relocate student").click()
1193        # We didn't informed the catalog therefore the new owner is not found
1194        self.assertMatches(
1195            "...There is no free bed in your category regular_male_fr...",
1196            self.browser.contents)
1197        # Now we fire the event properly
1198        notify(grok.ObjectModifiedEvent(bed2))
1199        self.browser.getLink("Relocate student").click()
1200        self.assertMatches(
1201            "...Student relocated...", self.browser.contents)
1202        self.assertMatches(
1203            "... Hall 1, Block A, Room 101, Bed B...", self.browser.contents)
1204          # Managers can delete bed tickets
1205        self.browser.open(self.acco_path)
1206        ctrl = self.browser.getControl(name='val_id')
1207        value = ctrl.options[0]
1208        ctrl.getControl(value=value).selected = True
1209        self.browser.getControl("Remove selected", index=0).click()
1210        self.assertMatches('...Successfully removed...', self.browser.contents)
1211        # The bed has been properly released by the event handler
1212        self.assertMatches(bed1.owner, NOT_OCCUPIED)
1213        self.assertMatches(bed2.owner, NOT_OCCUPIED)
1214        return
1215
1216    def test_manage_workflow(self):
1217        # Managers can pass through the whole workflow
1218        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1219        student = self.app['students'][self.student_id]
1220        self.browser.open(self.trigtrans_path)
1221        self.assertTrue(student.clearance_locked)
1222        self.browser.getControl(name="transition").value = ['admit']
1223        self.browser.getControl("Save").click()
1224        self.assertTrue(student.clearance_locked)
1225        self.browser.getControl(name="transition").value = ['start_clearance']
1226        self.browser.getControl("Save").click()
1227        self.assertFalse(student.clearance_locked)
1228        self.browser.getControl(name="transition").value = ['request_clearance']
1229        self.browser.getControl("Save").click()
1230        self.assertTrue(student.clearance_locked)
1231        self.browser.getControl(name="transition").value = ['clear']
1232        self.browser.getControl("Save").click()
1233        # Managers approve payment, they do not pay
1234        self.assertFalse('pay_first_school_fee' in self.browser.contents)
1235        self.browser.getControl(
1236            name="transition").value = ['approve_first_school_fee']
1237        self.browser.getControl("Save").click()
1238        self.browser.getControl(name="transition").value = ['reset6']
1239        self.browser.getControl("Save").click()
1240        # In state returning the pay_school_fee transition triggers some
1241        # changes of attributes
1242        self.browser.getControl(name="transition").value = ['approve_school_fee']
1243        self.browser.getControl("Save").click()
1244        self.assertEqual(student['studycourse'].current_session, 2005) # +1
1245        self.assertEqual(student['studycourse'].current_level, 200) # +100
1246        self.assertEqual(student['studycourse'].current_verdict, '0') # 0 = Zero = not set
1247        self.assertEqual(student['studycourse'].previous_verdict, 'A')
1248        self.browser.getControl(name="transition").value = ['register_courses']
1249        self.browser.getControl("Save").click()
1250        self.browser.getControl(name="transition").value = ['validate_courses']
1251        self.browser.getControl("Save").click()
1252        self.browser.getControl(name="transition").value = ['return']
1253        self.browser.getControl("Save").click()
1254        return
1255
1256    def test_manage_pg_workflow(self):
1257        # Managers can pass through the whole workflow
1258        IWorkflowState(self.student).setState('school fee paid')
1259        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1260        student = self.app['students'][self.student_id]
1261        self.browser.open(self.trigtrans_path)
1262        self.assertTrue('<option value="reset6">' in self.browser.contents)
1263        self.assertTrue('<option value="register_courses">' in self.browser.contents)
1264        self.assertTrue('<option value="reset5">' in self.browser.contents)
1265        self.certificate.study_mode = 'pg_ft'
1266        self.browser.open(self.trigtrans_path)
1267        self.assertFalse('<option value="reset6">' in self.browser.contents)
1268        self.assertFalse('<option value="register_courses">' in self.browser.contents)
1269        self.assertTrue('<option value="reset5">' in self.browser.contents)
1270        return
1271
1272    def test_manage_import(self):
1273        # Managers can import student data files
1274        datacenter_path = 'http://localhost/app/datacenter'
1275        # Prepare a csv file for students
1276        open('students.csv', 'wb').write(
1277"""firstname,lastname,reg_number,date_of_birth,matric_number,email,phone,sex,password
1278Aaren,Pieri,1,1990-01-02,100000,aa@aa.ng,1234,m,mypwd1
1279Claus,Finau,2,1990-01-03,100001,aa@aa.ng,1234,m,mypwd1
1280Brit,Berson,3,1990-01-04,100001,aa@aa.ng,1234,m,mypwd1
1281""")
1282        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1283        self.browser.open(datacenter_path)
1284        self.browser.getLink('Upload data').click()
1285        filecontents = StringIO(open('students.csv', 'rb').read())
1286        filewidget = self.browser.getControl(name='uploadfile:file')
1287        filewidget.add_file(filecontents, 'text/plain', 'students.csv')
1288        self.browser.getControl(name='SUBMIT').click()
1289        self.browser.getLink('Process data').click()
1290        button = lookup_submit_value(
1291            'select', 'students_zope.mgr.csv', self.browser)
1292        button.click()
1293        importerselect = self.browser.getControl(name='importer')
1294        modeselect = self.browser.getControl(name='mode')
1295        importerselect.getControl('Student Processor').selected = True
1296        modeselect.getControl(value='create').selected = True
1297        self.browser.getControl('Proceed to step 3').click()
1298        self.assertTrue('Header fields OK' in self.browser.contents)
1299        self.browser.getControl('Perform import').click()
1300        self.assertTrue('Processing of 1 rows failed' in self.browser.contents)
1301        self.assertTrue('Successfully processed 2 rows' in self.browser.contents)
1302        self.assertTrue('Batch processing finished' in self.browser.contents)
1303        open('studycourses.csv', 'wb').write(
1304"""reg_number,matric_number,certificate,current_session,current_level
13051,,CERT1,2008,100
1306,100001,CERT1,2008,100
1307,100002,CERT1,2008,100
1308""")
1309        self.browser.open(datacenter_path)
1310        self.browser.getLink('Upload data').click()
1311        filecontents = StringIO(open('studycourses.csv', 'rb').read())
1312        filewidget = self.browser.getControl(name='uploadfile:file')
1313        filewidget.add_file(filecontents, 'text/plain', 'studycourses.csv')
1314        self.browser.getControl(name='SUBMIT').click()
1315        self.browser.getLink('Process data').click()
1316        button = lookup_submit_value(
1317            'select', 'studycourses_zope.mgr.csv', self.browser)
1318        button.click()
1319        importerselect = self.browser.getControl(name='importer')
1320        modeselect = self.browser.getControl(name='mode')
1321        importerselect.getControl(
1322            'StudentStudyCourse Processor (update only)').selected = True
1323        modeselect.getControl(value='create').selected = True
1324        self.browser.getControl('Proceed to step 3').click()
1325        self.assertTrue('Update mode only' in self.browser.contents)
1326        self.browser.getControl('Proceed to step 3').click()
1327        self.assertTrue('Header fields OK' in self.browser.contents)
1328        self.browser.getControl('Perform import').click()
1329        self.assertTrue('Processing of 1 rows failed' in self.browser.contents)
1330        self.assertTrue('Successfully processed 2 rows'
1331                        in self.browser.contents)
1332        # The students are properly indexed and we can
1333        # thus find a student in  the department
1334        self.browser.open(self.manage_container_path)
1335        self.browser.getControl(name="searchtype").value = ['depcode']
1336        self.browser.getControl(name="searchterm").value = 'dep1'
1337        self.browser.getControl("Search").click()
1338        self.assertTrue('Aaren Pieri' in self.browser.contents)
1339        # We can search for a new student by name ...
1340        self.browser.getControl(name="searchtype").value = ['fullname']
1341        self.browser.getControl(name="searchterm").value = 'Claus'
1342        self.browser.getControl("Search").click()
1343        self.assertTrue('Claus Finau' in self.browser.contents)
1344        # ... and check if the imported password has been properly set
1345        ctrl = self.browser.getControl(name='entries')
1346        value = ctrl.options[0]
1347        claus = self.app['students'][value]
1348        self.assertTrue(IUserAccount(claus).checkPassword('mypwd1'))
1349        return
1350
1351    def test_handle_clearance_by_co(self):
1352        # Create clearance officer
1353        self.app['users'].addUser('mrclear', 'mrclearsecret')
1354        self.app['users']['mrclear'].email = 'mrclear@foo.ng'
1355        self.app['users']['mrclear'].title = 'Carlo Pitter'
1356        # Clearance officers need not necessarily to get
1357        # the StudentsOfficer site role
1358        #prmglobal = IPrincipalRoleManager(self.app)
1359        #prmglobal.assignRoleToPrincipal('waeup.StudentsOfficer', 'mrclear')
1360        # Assign local ClearanceOfficer role
1361        department = self.app['faculties']['fac1']['dep1']
1362        prmlocal = IPrincipalRoleManager(department)
1363        prmlocal.assignRoleToPrincipal('waeup.local.ClearanceOfficer', 'mrclear')
1364        IWorkflowState(self.student).setState('clearance started')
1365        # Login as clearance officer
1366        self.browser.open(self.login_path)
1367        self.browser.getControl(name="form.login").value = 'mrclear'
1368        self.browser.getControl(name="form.password").value = 'mrclearsecret'
1369        self.browser.getControl("Login").click()
1370        self.assertMatches('...You logged in...', self.browser.contents)
1371        # CO can see his roles
1372        self.browser.getLink("My Roles").click()
1373        self.assertMatches(
1374            '...<div>Academics Officer (view only)</div>...',
1375            self.browser.contents)
1376        #self.assertMatches(
1377        #    '...<div>Students Officer (view only)</div>...',
1378        #    self.browser.contents)
1379        # But not his local role ...
1380        self.assertFalse('Clearance Officer' in self.browser.contents)
1381        # ... because we forgot to notify the department that the local role
1382        # has changed
1383        notify(LocalRoleSetEvent(
1384            department, 'waeup.local.ClearanceOfficer', 'mrclear', granted=True))
1385        self.browser.open('http://localhost/app/users/mrclear/my_roles')
1386        self.assertTrue('Clearance Officer' in self.browser.contents)
1387        self.assertMatches(
1388            '...<a href="http://localhost/app/faculties/fac1/dep1">...',
1389            self.browser.contents)
1390        # CO can view the student ...
1391        self.browser.open(self.clearance_path)
1392        self.assertEqual(self.browser.headers['Status'], '200 Ok')
1393        self.assertEqual(self.browser.url, self.clearance_path)
1394        # ... but not other students
1395        other_student = Student()
1396        other_student.firstname = u'Dep2'
1397        other_student.lastname = u'Student'
1398        self.app['students'].addStudent(other_student)
1399        other_student_path = (
1400            'http://localhost/app/students/%s' % other_student.student_id)
1401        self.assertRaises(
1402            Unauthorized, self.browser.open, other_student_path)
1403        # Clearance is disabled for this session
1404        self.browser.open(self.clearance_path)
1405        self.assertFalse('Clear student' in self.browser.contents)
1406        self.browser.open(self.student_path + '/clear')
1407        self.assertTrue('Clearance is disabled for this session'
1408            in self.browser.contents)
1409        self.app['configuration']['2004'].clearance_enabled = True
1410        # Only in state clearance requested the CO does see the 'Clear' button
1411        self.browser.open(self.clearance_path)
1412        self.assertFalse('Clear student' in self.browser.contents)
1413        IWorkflowInfo(self.student).fireTransition('request_clearance')
1414        self.browser.open(self.clearance_path)
1415        self.assertTrue('Clear student' in self.browser.contents)
1416        self.browser.getLink("Clear student").click()
1417        self.assertTrue('Student has been cleared' in self.browser.contents)
1418        self.assertTrue('cleared' in self.browser.contents)
1419        self.browser.open(self.history_path)
1420        self.assertTrue('Cleared by Carlo Pitter' in self.browser.contents)
1421        # Hide real name.
1422        self.app['users']['mrclear'].public_name = 'My Public Name'
1423        self.browser.open(self.clearance_path)
1424        self.browser.getLink("Reject clearance").click()
1425        self.assertEqual(
1426            self.browser.url, self.student_path + '/reject_clearance')
1427        # Type comment why
1428        self.browser.getControl(name="form.officer_comment").value = """Dear Student,
1429You did not fill properly.
1430"""
1431        self.browser.getControl("Save comment").click()
1432        self.assertTrue('Clearance has been annulled' in self.browser.contents)
1433        url = ('http://localhost/app/students/K1000000/'
1434              'contactstudent?body=Dear+Student%2C%0AYou+did+not+fill+properly.'
1435              '%0A&subject=Clearance+has+been+annulled.')
1436        # CO does now see the prefilled contact form and can send a message
1437        self.assertEqual(self.browser.url, url)
1438        self.assertTrue('clearance started' in self.browser.contents)
1439        self.assertTrue('name="form.subject" size="20" type="text" '
1440            'value="Clearance has been annulled."'
1441            in self.browser.contents)
1442        self.assertTrue('name="form.body" rows="10" >Dear Student,'
1443            in self.browser.contents)
1444        self.browser.getControl("Send message now").click()
1445        self.assertTrue('Your message has been sent' in self.browser.contents)
1446        # The comment has been stored ...
1447        self.assertEqual(self.student.officer_comment,
1448            u'Dear Student,\nYou did not fill properly.\n')
1449        # ... and logged
1450        logfile = os.path.join(
1451            self.app['datacenter'].storage, 'logs', 'students.log')
1452        logcontent = open(logfile).read()
1453        self.assertTrue(
1454            'INFO - mrclear - students.browser.StudentRejectClearancePage - '
1455            'K1000000 - comment: Dear Student,<br>You did not fill '
1456            'properly.<br>\n' in logcontent)
1457        self.browser.open(self.history_path)
1458        self.assertTrue("Reset to 'clearance started' by My Public Name" in
1459            self.browser.contents)
1460        IWorkflowInfo(self.student).fireTransition('request_clearance')
1461        self.browser.open(self.clearance_path)
1462        self.browser.getLink("Reject clearance").click()
1463        self.browser.getControl("Save comment").click()
1464        self.assertTrue('Clearance request has been rejected'
1465            in self.browser.contents)
1466        self.assertTrue('clearance started' in self.browser.contents)
1467        # The CO can't clear students if not in state
1468        # clearance requested
1469        self.browser.open(self.student_path + '/clear')
1470        self.assertTrue('Student is in wrong state'
1471            in self.browser.contents)
1472        # The CO can go to his department throug the my_roles page ...
1473        self.browser.open('http://localhost/app/users/mrclear/my_roles')
1474        self.browser.getLink("http://localhost/app/faculties/fac1/dep1").click()
1475        # ... and view the list of students
1476        self.browser.getLink("Show students").click()
1477        self.browser.getControl(name="session").value = ['2004']
1478        self.browser.getControl(name="level").value = ['200']
1479        self.browser.getControl("Show").click()
1480        self.assertFalse(self.student_id in self.browser.contents)
1481        self.browser.getControl(name="session").value = ['2004']
1482        self.browser.getControl(name="level").value = ['100']
1483        self.browser.getControl("Show").click()
1484        self.assertTrue(self.student_id in self.browser.contents)
1485        # The comment is indicated by 'yes'
1486        self.assertTrue('<td><span>yes</span></td>' in self.browser.contents)
1487        # Check if the enquiries form is not pre-filled with officer_comment
1488        # (regression test)
1489        self.browser.getLink("Logout").click()
1490        self.browser.open('http://localhost/app/enquiries')
1491        self.assertFalse(
1492            'You did not fill properly'
1493            in self.browser.contents)
1494        # When a student is cleared the comment is automatically deleted
1495        IWorkflowInfo(self.student).fireTransition('request_clearance')
1496        IWorkflowInfo(self.student).fireTransition('clear')
1497        self.assertEqual(self.student.officer_comment, None)
1498
1499    def test_handle_courses_by_ca(self):
1500        # Create course adviser
1501        self.app['users'].addUser('mrsadvise', 'mrsadvisesecret')
1502        self.app['users']['mrsadvise'].email = 'mradvise@foo.ng'
1503        self.app['users']['mrsadvise'].title = u'Helen Procter'
1504        # Assign local CourseAdviser100 role for a certificate
1505        cert = self.app['faculties']['fac1']['dep1'].certificates['CERT1']
1506        prmlocal = IPrincipalRoleManager(cert)
1507        prmlocal.assignRoleToPrincipal('waeup.local.CourseAdviser100', 'mrsadvise')
1508        IWorkflowState(self.student).setState('school fee paid')
1509        # Login as course adviser
1510        self.browser.open(self.login_path)
1511        self.browser.getControl(name="form.login").value = 'mrsadvise'
1512        self.browser.getControl(name="form.password").value = 'mrsadvisesecret'
1513        self.browser.getControl("Login").click()
1514        self.assertMatches('...You logged in...', self.browser.contents)
1515        # CO can see his roles
1516        self.browser.getLink("My Roles").click()
1517        self.assertMatches(
1518            '...<div>Academics Officer (view only)</div>...',
1519            self.browser.contents)
1520        # But not his local role ...
1521        self.assertFalse('Course Adviser' in self.browser.contents)
1522        # ... because we forgot to notify the certificate that the local role
1523        # has changed
1524        notify(LocalRoleSetEvent(
1525            cert, 'waeup.local.CourseAdviser100', 'mrsadvise', granted=True))
1526        self.browser.open('http://localhost/app/users/mrsadvise/my_roles')
1527        self.assertTrue('Course Adviser 100L' in self.browser.contents)
1528        self.assertMatches(
1529            '...<a href="http://localhost/app/faculties/fac1/dep1/certificates/CERT1">...',
1530            self.browser.contents)
1531        # CA can view the student ...
1532        self.browser.open(self.student_path)
1533        self.assertEqual(self.browser.headers['Status'], '200 Ok')
1534        self.assertEqual(self.browser.url, self.student_path)
1535        # ... but not other students
1536        other_student = Student()
1537        other_student.firstname = u'Dep2'
1538        other_student.lastname = u'Student'
1539        self.app['students'].addStudent(other_student)
1540        other_student_path = (
1541            'http://localhost/app/students/%s' % other_student.student_id)
1542        self.assertRaises(
1543            Unauthorized, self.browser.open, other_student_path)
1544        # We add study level 110 to the student's studycourse
1545        studylevel = StudentStudyLevel()
1546        studylevel.level = 110
1547        self.student['studycourse'].addStudentStudyLevel(
1548            cert,studylevel)
1549        L110_student_path = self.studycourse_path + '/110'
1550        # The CA can neither see the Validate nor the Edit button
1551        self.browser.open(L110_student_path)
1552        self.assertFalse('Validate courses' in self.browser.contents)
1553        self.assertFalse('Edit' in self.browser.contents)
1554        IWorkflowInfo(self.student).fireTransition('register_courses')
1555        self.browser.open(L110_student_path)
1556        self.assertFalse('Validate courses' in self.browser.contents)
1557        self.assertFalse('Edit' in self.browser.contents)
1558        # Only in state courses registered and only if the current level
1559        # corresponds with the name of the study level object
1560        # the 100L CA does see the 'Validate' button but not
1561        # the edit button
1562        self.student['studycourse'].current_level = 110
1563        self.browser.open(L110_student_path)
1564        self.assertFalse('Edit' in self.browser.contents)
1565        self.assertTrue('Validate courses' in self.browser.contents)
1566        # But a 100L CA does not see the button at other levels
1567        studylevel2 = StudentStudyLevel()
1568        studylevel2.level = 200
1569        self.student['studycourse'].addStudentStudyLevel(
1570            cert,studylevel2)
1571        L200_student_path = self.studycourse_path + '/200'
1572        self.browser.open(L200_student_path)
1573        self.assertFalse('Edit' in self.browser.contents)
1574        self.assertFalse('Validate courses' in self.browser.contents)
1575        self.browser.open(L110_student_path)
1576        self.browser.getLink("Validate courses").click()
1577        self.assertTrue('Course list has been validated' in self.browser.contents)
1578        self.assertTrue('courses validated' in self.browser.contents)
1579        self.assertEqual(self.student['studycourse']['110'].validated_by,
1580            'Helen Procter')
1581        self.assertMatches(
1582            '<YYYY-MM-DD hh:mm:ss>',
1583            self.student['studycourse']['110'].validation_date.strftime(
1584                "%Y-%m-%d %H:%M:%S"))
1585        self.browser.getLink("Reject courses").click()
1586        self.assertTrue('Course list request has been annulled.'
1587            in self.browser.contents)
1588        urlmessage = 'Course+list+request+has+been+annulled.'
1589        self.assertEqual(self.browser.url, self.student_path +
1590            '/contactstudent?subject=%s' % urlmessage)
1591        self.assertTrue('school fee paid' in self.browser.contents)
1592        self.assertTrue(self.student['studycourse']['110'].validated_by is None)
1593        self.assertTrue(self.student['studycourse']['110'].validation_date is None)
1594        IWorkflowInfo(self.student).fireTransition('register_courses')
1595        self.browser.open(L110_student_path)
1596        self.browser.getLink("Reject courses").click()
1597        self.assertTrue('Course list request has been rejected'
1598            in self.browser.contents)
1599        self.assertTrue('school fee paid' in self.browser.contents)
1600        # CA does now see the contact form and can send a message
1601        self.browser.getControl(name="form.subject").value = 'Important subject'
1602        self.browser.getControl(name="form.body").value = 'Course list rejected'
1603        self.browser.getControl("Send message now").click()
1604        self.assertTrue('Your message has been sent' in self.browser.contents)
1605        # The CA does now see the Edit button and can edit
1606        # current study level
1607        self.browser.open(L110_student_path)
1608        self.browser.getLink("Edit").click()
1609        self.assertTrue('Edit course list of 100 (Year 1) on 1st probation'
1610            in self.browser.contents)
1611        # The CA can't validate courses if not in state
1612        # courses registered
1613        self.browser.open(L110_student_path + '/validate_courses')
1614        self.assertTrue('Student is in the wrong state'
1615            in self.browser.contents)
1616        # The CA can go to his certificate through the my_roles page
1617        self.browser.open('http://localhost/app/users/mrsadvise/my_roles')
1618        self.browser.getLink(
1619            "http://localhost/app/faculties/fac1/dep1/certificates/CERT1").click()
1620        # and view the list of students
1621        self.browser.getLink("Show students").click()
1622        self.browser.getControl(name="session").value = ['2004']
1623        self.browser.getControl(name="level").value = ['100']
1624        self.browser.getControl("Show").click()
1625        self.assertTrue(self.student_id in self.browser.contents)
1626
1627    def test_handle_courses_by_lecturer(self):
1628        # Create course lecturer
1629        self.app['users'].addUser('mrslecturer', 'mrslecturersecret')
1630        self.app['users']['mrslecturer'].email = 'mrslecturer@foo.ng'
1631        self.app['users']['mrslecturer'].title = u'Mercedes Benz'
1632        # Assign local Lecturer role for a certificate
1633        course = self.app['faculties']['fac1']['dep1'].courses['COURSE1']
1634        prmlocal = IPrincipalRoleManager(course)
1635        prmlocal.assignRoleToPrincipal('waeup.local.Lecturer', 'mrslecturer')
1636        # Login as lecturer
1637        self.browser.open(self.login_path)
1638        self.browser.getControl(name="form.login").value = 'mrslecturer'
1639        self.browser.getControl(name="form.password").value = 'mrslecturersecret'
1640        self.browser.getControl("Login").click()
1641        self.assertMatches('...You logged in...', self.browser.contents)
1642        # CO can see her roles
1643        self.browser.getLink("My Roles").click()
1644        self.assertMatches(
1645            '...<div>Academics Officer (view only)</div>...',
1646            self.browser.contents)
1647        # But not her local role ...
1648        self.assertFalse('Lecturer' in self.browser.contents)
1649        # ... because we forgot to notify the course that the local role
1650        # has changed
1651        notify(LocalRoleSetEvent(
1652            course, 'waeup.local.Lecturer', 'mrslecturer', granted=True))
1653        self.browser.open('http://localhost/app/users/mrslecturer/my_roles')
1654        self.assertTrue('Lecturer' in self.browser.contents)
1655        self.assertMatches(
1656            '...<a href="http://localhost/app/faculties/fac1/dep1/courses/COURSE1">...',
1657            self.browser.contents)
1658        # The lecturer can go to her course
1659        self.browser.getLink(
1660            "http://localhost/app/faculties/fac1/dep1/courses/COURSE1").click()
1661        # and view the list of students
1662        self.browser.getLink("Show students").click()
1663        self.browser.getControl(name="session").value = ['2004']
1664        self.browser.getControl(name="level").value = ['100']
1665        self.browser.getControl("Show").click()
1666        self.assertTrue('No student found.' in self.browser.contents)
1667        # No student in course so far
1668        self.assertFalse(self.student_id in self.browser.contents)
1669        studylevel = createObject(u'waeup.StudentStudyLevel')
1670        studylevel.level = 100
1671        studylevel.level_session = 2004
1672        self.student['studycourse'].addStudentStudyLevel(
1673            self.certificate, studylevel)
1674        # Now the student has registered the course and can
1675        # be seen by the lecturer.
1676        self.browser.open("http://localhost/app/faculties/fac1/dep1/courses/COURSE1/students")
1677        self.browser.getControl(name="session").value = ['2004']
1678        self.browser.getControl(name="level").value = ['100']
1679        self.browser.getControl("Show").click()
1680        self.assertTrue(self.student_id in self.browser.contents)
1681        # The course ticket can be linked with the course.
1682        self.assertEqual(
1683            self.student['studycourse']['100']['COURSE1'].course,
1684            self.course)
1685        # Lecturer can neither access the student ...
1686        self.assertRaises(
1687            Unauthorized, self.browser.open, self.student_path)
1688        # ... nor the respective course ticket since
1689        # editing course tickets by lecturers is not feasible.
1690        self.assertTrue('COURSE1' in self.student['studycourse']['100'].keys())
1691        course_ticket_path = self.student_path + '/studycourse/100/COURSE1'
1692        self.assertRaises(
1693            Unauthorized, self.browser.open, course_ticket_path)
1694        # Course results can be batch edited via the edit_courses view
1695        self.app['faculties']['fac1']['dep1'].score_editing_disabled = True
1696        self.browser.open("http://localhost/app/faculties/fac1/dep1/courses/COURSE1")
1697        self.browser.getLink("Update scores").click()
1698        self.assertTrue('Score editing disabled' in self.browser.contents)
1699        self.app['faculties']['fac1']['dep1'].score_editing_disabled = False
1700        self.browser.getLink("Update scores").click()
1701        self.assertTrue('Current academic session not set' in self.browser.contents)
1702        self.app['configuration'].current_academic_session = 2004
1703        self.browser.getLink("Update scores").click()
1704        self.assertFalse(
1705            '<input type="text" name="scores" class="span1" />'
1706            in self.browser.contents)
1707        IWorkflowState(self.student).setState('courses validated')
1708        # Student must be in state 'courses validated'
1709        self.browser.open(
1710            "http://localhost/app/faculties/fac1/dep1/courses/COURSE1/edit_scores")
1711        self.assertTrue(
1712            '<input type="text" name="scores" class="span1" />'
1713            in self.browser.contents)
1714        self.browser.getControl(name="scores", index=0).value = '55'
1715        self.browser.getControl("Update scores").click()
1716        # New score has been set
1717        self.assertEqual(
1718            self.student['studycourse']['100']['COURSE1'].score, 55)
1719        # Score editing has been logged
1720        logfile = os.path.join(
1721            self.app['datacenter'].storage, 'logs', 'students.log')
1722        logcontent = open(logfile).read()
1723        self.assertTrue('mrslecturer - students.browser.EditScoresPage - '
1724                        'K1000000 100/COURSE1 score updated (55)' in logcontent)
1725        # Non-integer scores won't be accepted
1726        self.browser.open(
1727            "http://localhost/app/faculties/fac1/dep1/courses/COURSE1/edit_scores")
1728        self.assertTrue('value="55" />' in self.browser.contents)
1729        self.browser.getControl(name="scores", index=0).value = 'abc'
1730        self.browser.getControl("Update scores").click()
1731        self.assertTrue('Error: Score(s) of Anna Tester have not be updated'
1732            in self.browser.contents)
1733        # Scores can be removed
1734        self.browser.open(
1735            "http://localhost/app/faculties/fac1/dep1/courses/COURSE1/edit_scores")
1736        self.browser.getControl(name="scores", index=0).value = ''
1737        self.browser.getControl("Update scores").click()
1738        self.assertEqual(
1739            self.student['studycourse']['100']['COURSE1'].score, None)
1740        logcontent = open(logfile).read()
1741        self.assertTrue('mrslecturer - students.browser.EditScoresPage - '
1742                        'K1000000 100/COURSE1 score updated (None)' in logcontent)
1743
1744    def test_change_current_mode(self):
1745        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1746        self.browser.open(self.clearance_path)
1747        self.assertFalse('Employer' in self.browser.contents)
1748        self.browser.open(self.manage_clearance_path)
1749        self.assertFalse('Employer' in self.browser.contents)
1750        self.student.clearance_locked = False
1751        self.browser.open(self.edit_clearance_path)
1752        self.assertFalse('Employer' in self.browser.contents)
1753        # Now we change the study mode of the certificate and a different
1754        # interface is used by clearance views.
1755        self.certificate.study_mode = 'pg_ft'
1756        # Invariants are not being checked here?!
1757        self.certificate.end_level = 100
1758        self.browser.open(self.clearance_path)
1759        self.assertTrue('Employer' in self.browser.contents)
1760        self.browser.open(self.manage_clearance_path)
1761        self.assertTrue('Employer' in self.browser.contents)
1762        self.browser.open(self.edit_clearance_path)
1763        self.assertTrue('Employer' in self.browser.contents)
1764
1765    def test_activate_deactivate_buttons(self):
1766        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1767        self.browser.open(self.student_path)
1768        self.browser.getLink("Deactivate").click()
1769        self.assertTrue(
1770            'Student account has been deactivated.' in self.browser.contents)
1771        self.assertTrue(
1772            'Base Data (account deactivated)' in self.browser.contents)
1773        self.assertTrue(self.student.suspended)
1774        self.browser.getLink("Activate").click()
1775        self.assertTrue(
1776            'Student account has been activated.' in self.browser.contents)
1777        self.assertFalse(
1778            'Base Data (account deactivated)' in self.browser.contents)
1779        self.assertFalse(self.student.suspended)
1780        # History messages have been added ...
1781        self.browser.getLink("History").click()
1782        self.assertTrue(
1783            'Student account deactivated by Manager<br />' in self.browser.contents)
1784        self.assertTrue(
1785            'Student account activated by Manager<br />' in self.browser.contents)
1786        # ... and actions have been logged.
1787        logfile = os.path.join(
1788            self.app['datacenter'].storage, 'logs', 'students.log')
1789        logcontent = open(logfile).read()
1790        self.assertTrue('zope.mgr - students.browser.StudentDeactivatePage - '
1791                        'K1000000 - account deactivated' in logcontent)
1792        self.assertTrue('zope.mgr - students.browser.StudentActivatePage - '
1793                        'K1000000 - account activated' in logcontent)
1794
1795    def test_manage_student_transfer(self):
1796        # Add second certificate
1797        self.certificate2 = createObject('waeup.Certificate')
1798        self.certificate2.code = u'CERT2'
1799        self.certificate2.study_mode = 'ug_ft'
1800        self.certificate2.start_level = 999
1801        self.certificate2.end_level = 999
1802        self.app['faculties']['fac1']['dep1'].certificates.addCertificate(
1803            self.certificate2)
1804
1805        # Add study level to old study course
1806        studylevel = createObject(u'waeup.StudentStudyLevel')
1807        studylevel.level = 200
1808        self.student['studycourse'].addStudentStudyLevel(
1809            self.certificate, studylevel)
1810        studylevel = createObject(u'waeup.StudentStudyLevel')
1811        studylevel.level = 999
1812        self.student['studycourse'].addStudentStudyLevel(
1813            self.certificate, studylevel)
1814
1815        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1816        self.browser.open(self.student_path)
1817        self.browser.getLink("Transfer").click()
1818        self.browser.getControl(name="form.certificate").value = ['CERT2']
1819        self.browser.getControl(name="form.current_session").value = ['2011']
1820        self.browser.getControl(name="form.current_level").value = ['200']
1821        self.browser.getControl("Transfer").click()
1822        self.assertTrue(
1823            'Current level does not match certificate levels'
1824            in self.browser.contents)
1825        self.browser.getControl(name="form.current_level").value = ['999']
1826        self.browser.getControl("Transfer").click()
1827        self.assertTrue('Successfully transferred' in self.browser.contents)
1828        # The catalog has been updated
1829        cat = queryUtility(ICatalog, name='students_catalog')
1830        results = list(
1831            cat.searchResults(
1832            certcode=('CERT2', 'CERT2')))
1833        self.assertTrue(results[0] is self.student)
1834        results = list(
1835            cat.searchResults(
1836            current_session=(2011, 2011)))
1837        self.assertTrue(results[0] is self.student)
1838        # Add study level to new study course
1839        studylevel = createObject(u'waeup.StudentStudyLevel')
1840        studylevel.level = 999
1841        self.student['studycourse'].addStudentStudyLevel(
1842            self.certificate, studylevel)
1843
1844        # Edit and add pages are locked for old study courses
1845        self.browser.open(self.student_path + '/studycourse/manage')
1846        self.assertFalse('The requested form is locked' in self.browser.contents)
1847        self.browser.open(self.student_path + '/studycourse_1/manage')
1848        self.assertTrue('The requested form is locked' in self.browser.contents)
1849
1850        self.browser.open(self.student_path + '/studycourse/start_session')
1851        self.assertFalse('The requested form is locked' in self.browser.contents)
1852        self.browser.open(self.student_path + '/studycourse_1/start_session')
1853        self.assertTrue('The requested form is locked' in self.browser.contents)
1854
1855        IWorkflowState(self.student).setState('school fee paid')
1856        self.browser.open(self.student_path + '/studycourse/add')
1857        self.assertFalse('The requested form is locked' in self.browser.contents)
1858        self.browser.open(self.student_path + '/studycourse_1/add')
1859        self.assertTrue('The requested form is locked' in self.browser.contents)
1860
1861        self.browser.open(self.student_path + '/studycourse/999/manage')
1862        self.assertFalse('The requested form is locked' in self.browser.contents)
1863        self.browser.open(self.student_path + '/studycourse_1/999/manage')
1864        self.assertTrue('The requested form is locked' in self.browser.contents)
1865
1866        self.browser.open(self.student_path + '/studycourse/999/validate_courses')
1867        self.assertFalse('The requested form is locked' in self.browser.contents)
1868        self.browser.open(self.student_path + '/studycourse_1/999/validate_courses')
1869        self.assertTrue('The requested form is locked' in self.browser.contents)
1870
1871        self.browser.open(self.student_path + '/studycourse/999/reject_courses')
1872        self.assertFalse('The requested form is locked' in self.browser.contents)
1873        self.browser.open(self.student_path + '/studycourse_1/999/reject_courses')
1874        self.assertTrue('The requested form is locked' in self.browser.contents)
1875
1876        self.browser.open(self.student_path + '/studycourse/999/add')
1877        self.assertFalse('The requested form is locked' in self.browser.contents)
1878        self.browser.open(self.student_path + '/studycourse_1/999/add')
1879        self.assertTrue('The requested form is locked' in self.browser.contents)
1880
1881        self.browser.open(self.student_path + '/studycourse/999/edit')
1882        self.assertFalse('The requested form is locked' in self.browser.contents)
1883        self.browser.open(self.student_path + '/studycourse_1/999/edit')
1884        self.assertTrue('The requested form is locked' in self.browser.contents)
1885
1886        # Revert transfer
1887        self.browser.open(self.student_path + '/studycourse_1')
1888        self.browser.getLink("Reactivate").click()
1889        self.browser.getControl("Revert now").click()
1890        self.assertTrue('Previous transfer reverted' in self.browser.contents)
1891        results = list(
1892            cat.searchResults(
1893            certcode=('CERT1', 'CERT1')))
1894        self.assertTrue(results[0] is self.student)
1895        self.assertEqual([i for i in self.student.keys()],
1896            [u'accommodation', u'payments', u'studycourse'])
1897
1898    def test_login_as_student(self):
1899        # StudentImpersonators can login as student
1900        # Create clearance officer
1901        self.app['users'].addUser('mrofficer', 'mrofficersecret')
1902        self.app['users']['mrofficer'].email = 'mrofficer@foo.ng'
1903        self.app['users']['mrofficer'].title = 'Harry Actor'
1904        prmglobal = IPrincipalRoleManager(self.app)
1905        prmglobal.assignRoleToPrincipal('waeup.StudentImpersonator', 'mrofficer')
1906        prmglobal.assignRoleToPrincipal('waeup.StudentsManager', 'mrofficer')
1907        # Login as student impersonator
1908        self.browser.open(self.login_path)
1909        self.browser.getControl(name="form.login").value = 'mrofficer'
1910        self.browser.getControl(name="form.password").value = 'mrofficersecret'
1911        self.browser.getControl("Login").click()
1912        self.assertMatches('...You logged in...', self.browser.contents)
1913        self.browser.open(self.student_path)
1914        self.browser.getLink("Login as").click()
1915        self.browser.getControl("Set password now").click()
1916        temp_password = self.browser.getControl(name='form.password').value
1917        self.browser.getControl("Login now").click()
1918        self.assertMatches(
1919            '...You successfully logged in as...', self.browser.contents)
1920        # We are logged in as student and can see the 'My Data' tab
1921        self.assertMatches(
1922            '...<a href="#" class="dropdown-toggle">My Data</a>...',
1923            self.browser.contents)
1924        self.browser.getLink("Logout").click()
1925        # The student can't login with the original password ...
1926        self.browser.open(self.login_path)
1927        self.browser.getControl(name="form.login").value = self.student_id
1928        self.browser.getControl(name="form.password").value = 'spwd'
1929        self.browser.getControl("Login").click()
1930        self.assertMatches(
1931            '...Your account has been temporarily deactivated...',
1932            self.browser.contents)
1933        # ... but with the temporary password
1934        self.browser.open(self.login_path)
1935        self.browser.getControl(name="form.login").value = self.student_id
1936        self.browser.getControl(name="form.password").value = temp_password
1937        self.browser.getControl("Login").click()
1938        self.assertMatches('...You logged in...', self.browser.contents)
1939        # Creation of temp_password is properly logged
1940        logfile = os.path.join(
1941            self.app['datacenter'].storage, 'logs', 'students.log')
1942        logcontent = open(logfile).read()
1943        self.assertTrue(
1944            'mrofficer - students.browser.LoginAsStudentStep1 - K1000000 - '
1945            'temp_password generated: %s' % temp_password in logcontent)
1946
1947    def test_transcripts(self):
1948        studylevel = createObject(u'waeup.StudentStudyLevel')
1949        studylevel.level = 100
1950        studylevel.level_session = 2005
1951        self.student['studycourse'].entry_mode = 'ug_ft'
1952        self.student['studycourse'].addStudentStudyLevel(
1953            self.certificate, studylevel)
1954        studylevel2 = createObject(u'waeup.StudentStudyLevel')
1955        studylevel2.level = 110
1956        studylevel2.level_session = 2006
1957        self.student['studycourse'].addStudentStudyLevel(
1958            self.certificate, studylevel2)
1959        # Add second course (COURSE has been added automatically)
1960        courseticket = createObject('waeup.CourseTicket')
1961        courseticket.code = 'ANYCODE'
1962        courseticket.title = u'Any TITLE'
1963        courseticket.credits = 13
1964        courseticket.score = 66
1965        courseticket.semester = 1
1966        courseticket.dcode = u'ANYDCODE'
1967        courseticket.fcode = u'ANYFCODE'
1968        self.student['studycourse']['110']['COURSE2'] = courseticket
1969        self.student['studycourse']['100']['COURSE1'].score = 55
1970        self.assertEqual(self.student['studycourse']['100'].gpa_params_rectified[0], 3.0)
1971        self.assertEqual(self.student['studycourse']['110'].gpa_params_rectified[0], 4.0)
1972        # Get transcript data
1973        td = self.student['studycourse'].getTranscriptData()
1974        self.assertEqual(td[0][0]['level_key'], '100')
1975        self.assertEqual(td[0][0]['sgpa'], 3.0)
1976        self.assertEqual(td[0][0]['level'].level, 100)
1977        self.assertEqual(td[0][0]['level'].level_session, 2005)
1978        self.assertEqual(td[0][0]['tickets_1'][0].code, 'COURSE1')
1979        self.assertEqual(td[0][1]['level_key'], '110')
1980        self.assertEqual(td[0][1]['sgpa'], 4.0)
1981        self.assertEqual(td[0][1]['level'].level, 110)
1982        self.assertEqual(td[0][1]['level'].level_session, 2006)
1983        self.assertEqual(td[0][1]['tickets_1'][0].code, 'ANYCODE')
1984        self.assertEqual(td[1], 3.57)
1985        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1986        self.browser.open(self.student_path + '/studycourse/transcript')
1987        self.assertEqual(self.browser.headers['Status'], '200 Ok')
1988        self.assertTrue('Transcript' in self.browser.contents)
1989        # Officers can open the pdf transcript
1990        self.browser.open(self.student_path + '/studycourse/transcript.pdf')
1991        self.assertEqual(self.browser.headers['Status'], '200 Ok')
1992        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
1993        path = os.path.join(samples_dir(), 'transcript.pdf')
1994        open(path, 'wb').write(self.browser.contents)
1995        print "Sample PDF transcript.pdf written to %s" % path
1996
1997    def test_process_transcript_request(self):
1998        IWorkflowState(self.student).setState('transcript requested')
1999        notify(grok.ObjectModifiedEvent(self.student))
2000        self.student.transcript_comment = (
2001            u'On 07/08/2013 08:59:54 UTC K1000000 wrote:\n\nComment line 1 \n'
2002            'Comment line2\n\nDispatch Address:\nAddress line 1 \n'
2003            'Address line2\n\n')
2004        # Create transcript officer
2005        self.app['users'].addUser('mrtranscript', 'mrtranscriptsecret')
2006        self.app['users']['mrtranscript'].email = 'mrtranscript@foo.ng'
2007        self.app['users']['mrtranscript'].title = 'Ruth Gordon'
2008        prmglobal = IPrincipalRoleManager(self.app)
2009        prmglobal.assignRoleToPrincipal('waeup.TranscriptOfficer', 'mrtranscript')
2010        # Login as transcript officer
2011        self.browser.open(self.login_path)
2012        self.browser.getControl(name="form.login").value = 'mrtranscript'
2013        self.browser.getControl(name="form.password").value = 'mrtranscriptsecret'
2014        self.browser.getControl("Login").click()
2015        self.assertMatches('...You logged in...', self.browser.contents)
2016        # Officer can see his roles
2017        self.browser.getLink("My Roles").click()
2018        self.assertMatches(
2019            '...<div>Transcript Officer</div>...',
2020            self.browser.contents)
2021        # Officer can search for students in state 'transcripr requested'
2022        self.browser.open(self.container_path)
2023        self.browser.getControl(name="searchtype").value = ['transcript']
2024        self.browser.getControl("Search").click()
2025        self.assertTrue('Anna Tester' in self.browser.contents)
2026        self.browser.getLink("K1000000").click()
2027        self.browser.getLink("Manage transcript request").click()
2028        self.assertTrue(' UTC K1000000 wrote:<br><br>Comment line 1 <br>'
2029        'Comment line2<br><br>Dispatch Address:<br>Address line 1 <br>'
2030        'Address line2<br><br></p>' in self.browser.contents)
2031        self.browser.getControl(name="comment").value = (
2032            'Hello,\nYour transcript has been sent to the address provided.')
2033        self.browser.getControl("Save comment and mark as processed").click()
2034        self.assertTrue(
2035            'UTC mrtranscript wrote:\n\nHello,\nYour transcript has '
2036            'been sent to the address provided.\n\n'
2037            in self.student.transcript_comment)
2038        # The comment has been logged
2039        logfile = os.path.join(
2040            self.app['datacenter'].storage, 'logs', 'students.log')
2041        logcontent = open(logfile).read()
2042        self.assertTrue(
2043            'mrtranscript - students.browser.StudentTranscriptRequestProcessFormPage - '
2044            'K1000000 - comment: Hello,<br>'
2045            'Your transcript has been sent to the address provided'
2046            in logcontent)
2047
2048class StudentUITests(StudentsFullSetup):
2049    # Tests for Student class views and pages
2050
2051    def test_student_change_password(self):
2052        # Students can change the password
2053        self.student.personal_updated = datetime.utcnow()
2054        self.browser.open(self.login_path)
2055        self.browser.getControl(name="form.login").value = self.student_id
2056        self.browser.getControl(name="form.password").value = 'spwd'
2057        self.browser.getControl("Login").click()
2058        self.assertEqual(self.browser.url, self.student_path)
2059        self.assertTrue('You logged in' in self.browser.contents)
2060        # Change password
2061        self.browser.getLink("Change password").click()
2062        self.browser.getControl(name="change_password").value = 'pw'
2063        self.browser.getControl(
2064            name="change_password_repeat").value = 'pw'
2065        self.browser.getControl("Save").click()
2066        self.assertTrue('Password must have at least' in self.browser.contents)
2067        self.browser.getControl(name="change_password").value = 'new_password'
2068        self.browser.getControl(
2069            name="change_password_repeat").value = 'new_passssword'
2070        self.browser.getControl("Save").click()
2071        self.assertTrue('Passwords do not match' in self.browser.contents)
2072        self.browser.getControl(name="change_password").value = 'new_password'
2073        self.browser.getControl(
2074            name="change_password_repeat").value = 'new_password'
2075        self.browser.getControl("Save").click()
2076        self.assertTrue('Password changed' in self.browser.contents)
2077        # We are still logged in. Changing the password hasn't thrown us out.
2078        self.browser.getLink("Base Data").click()
2079        self.assertEqual(self.browser.url, self.student_path)
2080        # We can logout
2081        self.browser.getLink("Logout").click()
2082        self.assertTrue('You have been logged out' in self.browser.contents)
2083        self.assertEqual(self.browser.url, 'http://localhost/app')
2084        # We can login again with the new password
2085        self.browser.getLink("Login").click()
2086        self.browser.open(self.login_path)
2087        self.browser.getControl(name="form.login").value = self.student_id
2088        self.browser.getControl(name="form.password").value = 'new_password'
2089        self.browser.getControl("Login").click()
2090        self.assertEqual(self.browser.url, self.student_path)
2091        self.assertTrue('You logged in' in self.browser.contents)
2092        return
2093
2094    def test_setpassword(self):
2095        # Set password for first-time access
2096        student = Student()
2097        student.reg_number = u'123456'
2098        student.firstname = u'Klaus'
2099        student.lastname = u'Tester'
2100        self.app['students'].addStudent(student)
2101        setpassword_path = 'http://localhost/app/setpassword'
2102        student_path = 'http://localhost/app/students/%s' % student.student_id
2103        self.browser.open(setpassword_path)
2104        self.browser.getControl(name="ac_series").value = self.existing_pwdseries
2105        self.browser.getControl(name="ac_number").value = self.existing_pwdnumber
2106        self.browser.getControl(name="reg_number").value = '223456'
2107        self.browser.getControl("Set").click()
2108        self.assertMatches('...No student found...',
2109                           self.browser.contents)
2110        self.browser.getControl(name="reg_number").value = '123456'
2111        self.browser.getControl(name="ac_number").value = '999999'
2112        self.browser.getControl("Set").click()
2113        self.assertMatches('...Access code is invalid...',
2114                           self.browser.contents)
2115        self.browser.getControl(name="ac_number").value = self.existing_pwdnumber
2116        self.browser.getControl("Set").click()
2117        self.assertMatches('...Password has been set. Your Student Id is...',
2118                           self.browser.contents)
2119        self.browser.getControl("Set").click()
2120        self.assertMatches(
2121            '...Password has already been set. Your Student Id is...',
2122            self.browser.contents)
2123        existing_pwdpin = self.pwdpins[1]
2124        parts = existing_pwdpin.split('-')[1:]
2125        existing_pwdseries, existing_pwdnumber = parts
2126        self.browser.getControl(name="ac_series").value = existing_pwdseries
2127        self.browser.getControl(name="ac_number").value = existing_pwdnumber
2128        self.browser.getControl(name="reg_number").value = '123456'
2129        self.browser.getControl("Set").click()
2130        self.assertMatches(
2131            '...You are using the wrong Access Code...',
2132            self.browser.contents)
2133        # The student can login with the new credentials
2134        self.browser.open(self.login_path)
2135        self.browser.getControl(name="form.login").value = student.student_id
2136        self.browser.getControl(
2137            name="form.password").value = self.existing_pwdnumber
2138        self.browser.getControl("Login").click()
2139        self.assertEqual(self.browser.url, student_path)
2140        self.assertTrue('You logged in' in self.browser.contents)
2141        return
2142
2143    def test_student_login(self):
2144        # Student cant login if their password is not set
2145        self.student.password = None
2146        self.browser.open(self.login_path)
2147        self.browser.getControl(name="form.login").value = self.student_id
2148        self.browser.getControl(name="form.password").value = 'spwd'
2149        self.browser.getControl("Login").click()
2150        self.assertTrue(
2151            'You entered invalid credentials.' in self.browser.contents)
2152        # We set the password again
2153        IUserAccount(
2154            self.app['students'][self.student_id]).setPassword('spwd')
2155        # Students can't login if their account is suspended/deactivated
2156        self.student.suspended = True
2157        self.browser.open(self.login_path)
2158        self.browser.getControl(name="form.login").value = self.student_id
2159        self.browser.getControl(name="form.password").value = 'spwd'
2160        self.browser.getControl("Login").click()
2161        self.assertMatches(
2162            '...<div class="alert-message warning">'
2163            'Your account has been deactivated.</div>...', self.browser.contents)
2164        # If suspended_comment is set this message will be flashed instead
2165        self.student.suspended_comment = u'Aetsch baetsch!'
2166        self.browser.getControl(name="form.login").value = self.student_id
2167        self.browser.getControl(name="form.password").value = 'spwd'
2168        self.browser.getControl("Login").click()
2169        self.assertMatches(
2170            '...<div class="alert-message warning">Aetsch baetsch!</div>...',
2171            self.browser.contents)
2172        self.student.suspended = False
2173        # Students can't login if a temporary password has been set and
2174        # is not expired
2175        self.app['students'][self.student_id].setTempPassword(
2176            'anybody', 'temp_spwd')
2177        self.browser.open(self.login_path)
2178        self.browser.getControl(name="form.login").value = self.student_id
2179        self.browser.getControl(name="form.password").value = 'spwd'
2180        self.browser.getControl("Login").click()
2181        self.assertMatches(
2182            '...Your account has been temporarily deactivated...',
2183            self.browser.contents)
2184        # The student can login with the temporary password
2185        self.browser.open(self.login_path)
2186        self.browser.getControl(name="form.login").value = self.student_id
2187        self.browser.getControl(name="form.password").value = 'temp_spwd'
2188        self.browser.getControl("Login").click()
2189        self.assertMatches(
2190            '...You logged in...', self.browser.contents)
2191        # Student can view the base data
2192        self.browser.open(self.student_path)
2193        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2194        self.assertEqual(self.browser.url, self.student_path)
2195        # When the password expires ...
2196        delta = timedelta(minutes=11)
2197        self.app['students'][self.student_id].temp_password[
2198            'timestamp'] = datetime.utcnow() - delta
2199        self.app['students'][self.student_id]._p_changed = True
2200        # ... the student will be automatically logged out
2201        self.assertRaises(
2202            Unauthorized, self.browser.open, self.student_path)
2203        # Then the student can login with the original password
2204        self.browser.open(self.login_path)
2205        self.browser.getControl(name="form.login").value = self.student_id
2206        self.browser.getControl(name="form.password").value = 'spwd'
2207        self.browser.getControl("Login").click()
2208        self.assertMatches(
2209            '...You logged in...', self.browser.contents)
2210
2211    def test_student_clearance(self):
2212        # Student cant login if their password is not set
2213        IWorkflowInfo(self.student).fireTransition('admit')
2214        self.browser.open(self.login_path)
2215        self.browser.getControl(name="form.login").value = self.student_id
2216        self.browser.getControl(name="form.password").value = 'spwd'
2217        self.browser.getControl("Login").click()
2218        self.assertMatches(
2219            '...You logged in...', self.browser.contents)
2220        # Admitted student can upload a passport picture
2221        self.browser.open(self.student_path + '/change_portrait')
2222        ctrl = self.browser.getControl(name='passportuploadedit')
2223        file_obj = open(SAMPLE_IMAGE, 'rb')
2224        file_ctrl = ctrl.mech_control
2225        file_ctrl.add_file(file_obj, filename='my_photo.jpg')
2226        self.browser.getControl(
2227            name='upload_passportuploadedit').click()
2228        self.assertTrue(
2229            '<img align="middle" height="125px" src="passport.jpg" />'
2230            in self.browser.contents)
2231        # Students can open admission letter
2232        self.browser.getLink("Base Data").click()
2233        self.browser.getLink("Download admission letter").click()
2234        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2235        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2236        # Student can view the clearance data
2237        self.browser.open(self.student_path)
2238        self.browser.getLink("Clearance Data").click()
2239        # Student can't open clearance edit form before starting clearance
2240        self.browser.open(self.student_path + '/cedit')
2241        self.assertMatches('...The requested form is locked...',
2242                           self.browser.contents)
2243        self.browser.getLink("Clearance Data").click()
2244        self.browser.getLink("Start clearance").click()
2245        self.student.email = None
2246        # Uups, we forgot to fill the email fields
2247        self.browser.getControl("Start clearance").click()
2248        self.assertMatches('...Not all required fields filled...',
2249                           self.browser.contents)
2250        self.browser.open(self.student_path + '/edit_base')
2251        self.browser.getControl(name="form.email").value = 'aa@aa.ng'
2252        self.browser.getControl("Save").click()
2253        self.browser.open(self.student_path + '/start_clearance')
2254        self.browser.getControl(name="ac_series").value = '3'
2255        self.browser.getControl(name="ac_number").value = '4444444'
2256        self.browser.getControl("Start clearance now").click()
2257        self.assertMatches('...Activation code is invalid...',
2258                           self.browser.contents)
2259        self.browser.getControl(name="ac_series").value = self.existing_clrseries
2260        self.browser.getControl(name="ac_number").value = self.existing_clrnumber
2261        # Owner is Hans Wurst, AC can't be invalidated
2262        self.browser.getControl("Start clearance now").click()
2263        self.assertMatches('...You are not the owner of this access code...',
2264                           self.browser.contents)
2265        # Set the correct owner
2266        self.existing_clrac.owner = self.student_id
2267        # clr_code might be set (and thus returns None) due importing
2268        # an empty clr_code column.
2269        self.student.clr_code = None
2270        self.browser.getControl("Start clearance now").click()
2271        self.assertMatches('...Clearance process has been started...',
2272                           self.browser.contents)
2273        self.browser.getControl(name="form.date_of_birth").value = '09/10/1961'
2274        self.browser.getControl("Save", index=0).click()
2275        # Student can view the clearance data
2276        self.browser.getLink("Clearance Data").click()
2277        # and go back to the edit form
2278        self.browser.getLink("Edit").click()
2279        # Students can upload documents
2280        ctrl = self.browser.getControl(name='birthcertificateupload')
2281        file_obj = open(SAMPLE_IMAGE, 'rb')
2282        file_ctrl = ctrl.mech_control
2283        file_ctrl.add_file(file_obj, filename='my_birth_certificate.jpg')
2284        self.browser.getControl(
2285            name='upload_birthcertificateupload').click()
2286        self.assertTrue(
2287            '<a target="image" href="birth_certificate">Birth Certificate Scan</a>'
2288            in self.browser.contents)
2289        # Students can open clearance slip
2290        self.browser.getLink("View").click()
2291        self.browser.getLink("Download clearance slip").click()
2292        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2293        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2294        # Students can request clearance
2295        self.browser.open(self.edit_clearance_path)
2296        self.browser.getControl("Save and request clearance").click()
2297        self.browser.getControl(name="ac_series").value = self.existing_clrseries
2298        self.browser.getControl(name="ac_number").value = self.existing_clrnumber
2299        self.browser.getControl("Request clearance now").click()
2300        self.assertMatches('...Clearance has been requested...',
2301                           self.browser.contents)
2302        # Student can't reopen clearance form after requesting clearance
2303        self.browser.open(self.student_path + '/cedit')
2304        self.assertMatches('...The requested form is locked...',
2305                           self.browser.contents)
2306
2307    def test_student_course_registration(self):
2308        # Student cant login if their password is not set
2309        IWorkflowInfo(self.student).fireTransition('admit')
2310        self.browser.open(self.login_path)
2311        self.browser.getControl(name="form.login").value = self.student_id
2312        self.browser.getControl(name="form.password").value = 'spwd'
2313        self.browser.getControl("Login").click()
2314        # Student can't add study level if not in state 'school fee paid'
2315        self.browser.open(self.student_path + '/studycourse/add')
2316        self.assertMatches('...The requested form is locked...',
2317                           self.browser.contents)
2318        # ... and must be transferred first
2319        IWorkflowState(self.student).setState('school fee paid')
2320        # Now students can add the current study level
2321        self.browser.getLink("Study Course").click()
2322        self.browser.getLink("Add course list").click()
2323        self.assertMatches('...Add current level 100 (Year 1)...',
2324                           self.browser.contents)
2325        self.browser.getControl("Create course list now").click()
2326        # A level with one course ticket was created
2327        self.assertEqual(self.student['studycourse']['100'].number_of_tickets, 1)
2328        self.browser.getLink("100").click()
2329        self.browser.getLink("Edit course list").click()
2330        self.browser.getLink("here").click()
2331        self.browser.getControl(name="form.course").value = ['COURSE1']
2332        self.browser.getControl("Add course ticket").click()
2333        self.assertMatches('...The ticket exists...',
2334                           self.browser.contents)
2335        self.student['studycourse'].current_level = 200
2336        self.browser.getLink("Study Course").click()
2337        self.browser.getLink("Add course list").click()
2338        self.assertMatches('...Add current level 200 (Year 2)...',
2339                           self.browser.contents)
2340        self.browser.getControl("Create course list now").click()
2341        self.browser.getLink("200").click()
2342        self.browser.getLink("Edit course list").click()
2343        self.browser.getLink("here").click()
2344        self.browser.getControl(name="form.course").value = ['COURSE1']
2345        self.course.credits = 100
2346        self.browser.getControl("Add course ticket").click()
2347        self.assertMatches(
2348            '...Total credits exceed 50...', self.browser.contents)
2349        self.course.credits = 10
2350        self.browser.getControl("Add course ticket").click()
2351        self.assertMatches('...The ticket exists...',
2352                           self.browser.contents)
2353        # Indeed the ticket exists as carry-over course from level 100
2354        # since its score was 0
2355        self.assertTrue(
2356            self.student['studycourse']['200']['COURSE1'].carry_over is True)
2357        # Students can open the pdf course registration slip
2358        self.browser.open(self.student_path + '/studycourse/200')
2359        self.browser.getLink("Download course registration slip").click()
2360        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2361        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2362        # Students can remove course tickets
2363        self.browser.open(self.student_path + '/studycourse/200/edit')
2364        self.browser.getControl("Remove selected", index=0).click()
2365        self.assertTrue('No ticket selected' in self.browser.contents)
2366        # No ticket can be selected since the carry-over course is a core course
2367        self.assertRaises(
2368            LookupError, self.browser.getControl, name='val_id')
2369        self.student['studycourse']['200']['COURSE1'].mandatory = False
2370        self.browser.open(self.student_path + '/studycourse/200/edit')
2371        # Course list can't be registered if total_credits exceeds max_credits
2372        self.student['studycourse']['200']['COURSE1'].credits = 60
2373        self.browser.getControl("Register course list").click()
2374        self.assertTrue('Maximum credits of 50 exceeded' in self.browser.contents)
2375        # Student can now remove the ticket
2376        ctrl = self.browser.getControl(name='val_id')
2377        ctrl.getControl(value='COURSE1').selected = True
2378        self.browser.getControl("Remove selected", index=0).click()
2379        self.assertTrue('Successfully removed' in self.browser.contents)
2380        # Removing course tickets is properly logged
2381        logfile = os.path.join(
2382            self.app['datacenter'].storage, 'logs', 'students.log')
2383        logcontent = open(logfile).read()
2384        self.assertTrue('K1000000 - students.browser.StudyLevelEditFormPage '
2385        '- K1000000 - removed: COURSE1 at 200' in logcontent)
2386        # They can add the same ticket using the edit page directly.
2387        # We can do the same by adding the course on the manage page directly
2388        self.browser.getControl(name="course").value = 'COURSE1'
2389        self.browser.getControl("Add course ticket").click()
2390        # Adding course tickets is logged
2391        logfile = os.path.join(
2392            self.app['datacenter'].storage, 'logs', 'students.log')
2393        logcontent = open(logfile).read()
2394        self.assertTrue('K1000000 - students.browser.StudyLevelEditFormPage - '
2395            'K1000000 - added: COURSE1|200|2004' in logcontent)
2396        # Course list can be registered
2397        self.browser.getControl("Register course list").click()
2398        self.assertTrue('Course list has been registered' in self.browser.contents)
2399        self.assertEqual(self.student.state, 'courses registered')
2400        # Students can view the transcript
2401        #self.browser.open(self.studycourse_path)
2402        #self.browser.getLink("Transcript").click()
2403        #self.browser.getLink("Academic Transcript").click()
2404        #self.assertEqual(self.browser.headers['Status'], '200 Ok')
2405        #self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2406        return
2407
2408    def test_postgraduate_student_access(self):
2409        self.certificate.study_mode = 'pg_ft'
2410        self.certificate.start_level = 999
2411        self.certificate.end_level = 999
2412        self.student['studycourse'].current_level = 999
2413        IWorkflowState(self.student).setState('school fee paid')
2414        self.browser.open(self.login_path)
2415        self.browser.getControl(name="form.login").value = self.student_id
2416        self.browser.getControl(name="form.password").value = 'spwd'
2417        self.browser.getControl("Login").click()
2418        self.assertTrue(
2419            'You logged in.' in self.browser.contents)
2420        # Now students can add the current study level
2421        self.browser.getLink("Study Course").click()
2422        self.browser.getLink("Add course list").click()
2423        self.assertMatches('...Add current level Postgraduate Level...',
2424                           self.browser.contents)
2425        self.browser.getControl("Create course list now").click()
2426        # A level with one course ticket was created
2427        self.assertEqual(self.student['studycourse']['999'].number_of_tickets, 0)
2428        self.browser.getLink("999").click()
2429        self.browser.getLink("Edit course list").click()
2430        self.browser.getLink("here").click()
2431        self.browser.getControl(name="form.course").value = ['COURSE1']
2432        self.browser.getControl("Add course ticket").click()
2433        self.assertMatches('...Successfully added COURSE1...',
2434                           self.browser.contents)
2435        # Postgraduate students can't register course lists
2436        self.browser.getControl("Register course list").click()
2437        self.assertTrue("your course list can't bee registered"
2438            in self.browser.contents)
2439        self.assertEqual(self.student.state, 'school fee paid')
2440        return
2441
2442    def test_student_clearance_wo_clrcode(self):
2443        IWorkflowState(self.student).setState('clearance started')
2444        self.browser.open(self.login_path)
2445        self.browser.getControl(name="form.login").value = self.student_id
2446        self.browser.getControl(name="form.password").value = 'spwd'
2447        self.browser.getControl("Login").click()
2448        self.student.clearance_locked = False
2449        self.browser.open(self.edit_clearance_path)
2450        self.browser.getControl(name="form.date_of_birth").value = '09/10/1961'
2451        self.browser.getControl("Save and request clearance").click()
2452        self.assertMatches('...Clearance has been requested...',
2453                           self.browser.contents)
2454
2455    def test_student_clearance_payment(self):
2456        # Login
2457        self.browser.open(self.login_path)
2458        self.browser.getControl(name="form.login").value = self.student_id
2459        self.browser.getControl(name="form.password").value = 'spwd'
2460        self.browser.getControl("Login").click()
2461
2462        # Students can add online clearance payment tickets
2463        self.browser.open(self.payments_path + '/addop')
2464        self.browser.getControl(name="form.p_category").value = ['clearance']
2465        self.browser.getControl("Create ticket").click()
2466        self.assertMatches('...ticket created...',
2467                           self.browser.contents)
2468
2469        # Students can't approve the payment
2470        self.assertEqual(len(self.app['accesscodes']['CLR-0']),0)
2471        ctrl = self.browser.getControl(name='val_id')
2472        value = ctrl.options[0]
2473        self.browser.getLink(value).click()
2474        payment_url = self.browser.url
2475        self.assertRaises(
2476            Unauthorized, self.browser.open, payment_url + '/approve')
2477        # In the base package they can 'use' a fake approval view.
2478        # XXX: I tried to use
2479        # self.student['payments'][value].approveStudentPayment() instead.
2480        # But this function fails in
2481        # w.k.accesscodes.accesscode.create_accesscode.
2482        # grok.getSite returns None in tests.
2483        self.browser.open(payment_url + '/fake_approve')
2484        self.assertMatches('...Payment approved...',
2485                          self.browser.contents)
2486        expected = '''...
2487        <td>
2488          <span>Paid</span>
2489        </td>...'''
2490        expected = '''...
2491        <td>
2492          <span>Paid</span>
2493        </td>...'''
2494        self.assertMatches(expected,self.browser.contents)
2495        payment_id = self.student['payments'].keys()[0]
2496        payment = self.student['payments'][payment_id]
2497        self.assertEqual(payment.p_state, 'paid')
2498        self.assertEqual(payment.r_amount_approved, 3456.0)
2499        self.assertEqual(payment.r_code, 'AP')
2500        self.assertEqual(payment.r_desc, u'Payment approved by Anna Tester')
2501        # The new CLR-0 pin has been created
2502        self.assertEqual(len(self.app['accesscodes']['CLR-0']),1)
2503        pin = self.app['accesscodes']['CLR-0'].keys()[0]
2504        ac = self.app['accesscodes']['CLR-0'][pin]
2505        self.assertEqual(ac.owner, self.student_id)
2506        self.assertEqual(ac.cost, 3456.0)
2507
2508        # Students can open the pdf payment slip
2509        self.browser.open(payment_url + '/payment_slip.pdf')
2510        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2511        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2512
2513        # The new CLR-0 pin can be used for starting clearance
2514        # but they have to upload a passport picture first
2515        # which is only possible in state admitted
2516        self.browser.open(self.student_path + '/change_portrait')
2517        self.assertMatches('...form is locked...',
2518                          self.browser.contents)
2519        IWorkflowInfo(self.student).fireTransition('admit')
2520        self.browser.open(self.student_path + '/change_portrait')
2521        image = open(SAMPLE_IMAGE, 'rb')
2522        ctrl = self.browser.getControl(name='passportuploadedit')
2523        file_ctrl = ctrl.mech_control
2524        file_ctrl.add_file(image, filename='my_photo.jpg')
2525        self.browser.getControl(
2526            name='upload_passportuploadedit').click()
2527        self.browser.open(self.student_path + '/start_clearance')
2528        parts = pin.split('-')[1:]
2529        clrseries, clrnumber = parts
2530        self.browser.getControl(name="ac_series").value = clrseries
2531        self.browser.getControl(name="ac_number").value = clrnumber
2532        self.browser.getControl("Start clearance now").click()
2533        self.assertMatches('...Clearance process has been started...',
2534                           self.browser.contents)
2535
2536    def test_student_schoolfee_payment(self):
2537        configuration = createObject('waeup.SessionConfiguration')
2538        configuration.academic_session = 2005
2539        self.app['configuration'].addSessionConfiguration(configuration)
2540        # Login
2541        self.browser.open(self.login_path)
2542        self.browser.getControl(name="form.login").value = self.student_id
2543        self.browser.getControl(name="form.password").value = 'spwd'
2544        self.browser.getControl("Login").click()
2545
2546        # Students can add online school fee payment tickets.
2547        IWorkflowState(self.student).setState('returning')
2548        self.browser.open(self.payments_path)
2549        self.assertRaises(
2550            LookupError, self.browser.getControl, name='val_id')
2551        self.browser.getLink("Add current session payment ticket").click()
2552        self.browser.getControl(name="form.p_category").value = ['schoolfee']
2553        self.browser.getControl("Create ticket").click()
2554        self.assertMatches('...ticket created...',
2555                           self.browser.contents)
2556        ctrl = self.browser.getControl(name='val_id')
2557        value = ctrl.options[0]
2558        self.browser.getLink(value).click()
2559        self.assertMatches('...Amount Authorized...',
2560                           self.browser.contents)
2561        self.assertEqual(self.student['payments'][value].amount_auth, 20000.0)
2562        # Payment session and will be calculated as defined
2563        # in w.k.students.utils because we set changed the state
2564        # to returning
2565        self.assertEqual(self.student['payments'][value].p_session, 2005)
2566        self.assertEqual(self.student['payments'][value].p_level, 200)
2567
2568        # Student is the payer of the payment ticket.
2569        payer = IPayer(self.student['payments'][value])
2570        self.assertEqual(payer.display_fullname, 'Anna Tester')
2571        self.assertEqual(payer.id, self.student_id)
2572        self.assertEqual(payer.faculty, 'fac1')
2573        self.assertEqual(payer.department, 'dep1')
2574
2575        # We simulate the approval
2576        self.assertEqual(len(self.app['accesscodes']['SFE-0']),0)
2577        self.browser.open(self.browser.url + '/fake_approve')
2578        self.assertMatches('...Payment approved...',
2579                          self.browser.contents)
2580
2581        # The new SFE-0 pin can be used for starting new session
2582        self.browser.open(self.studycourse_path)
2583        self.browser.getLink('Start new session').click()
2584        pin = self.app['accesscodes']['SFE-0'].keys()[0]
2585        parts = pin.split('-')[1:]
2586        sfeseries, sfenumber = parts
2587        self.browser.getControl(name="ac_series").value = sfeseries
2588        self.browser.getControl(name="ac_number").value = sfenumber
2589        self.browser.getControl("Start now").click()
2590        self.assertMatches('...Session started...',
2591                           self.browser.contents)
2592        self.assertTrue(self.student.state == 'school fee paid')
2593        return
2594
2595    def test_student_bedallocation_payment(self):
2596        # Login
2597        self.browser.open(self.login_path)
2598        self.browser.getControl(name="form.login").value = self.student_id
2599        self.browser.getControl(name="form.password").value = 'spwd'
2600        self.browser.getControl("Login").click()
2601        self.browser.open(self.payments_path)
2602        self.browser.open(self.payments_path + '/addop')
2603        self.browser.getControl(name="form.p_category").value = ['bed_allocation']
2604        self.browser.getControl("Create ticket").click()
2605        self.assertMatches('...ticket created...',
2606                           self.browser.contents)
2607        # Students can remove only online payment tickets which have
2608        # not received a valid callback
2609        self.browser.open(self.payments_path)
2610        ctrl = self.browser.getControl(name='val_id')
2611        value = ctrl.options[0]
2612        ctrl.getControl(value=value).selected = True
2613        self.browser.getControl("Remove selected", index=0).click()
2614        self.assertTrue('Successfully removed' in self.browser.contents)
2615
2616    def test_student_maintenance_payment(self):
2617        # Login
2618        self.browser.open(self.login_path)
2619        self.browser.getControl(name="form.login").value = self.student_id
2620        self.browser.getControl(name="form.password").value = 'spwd'
2621        self.browser.getControl("Login").click()
2622        self.browser.open(self.payments_path)
2623        self.browser.open(self.payments_path + '/addop')
2624        self.browser.getControl(name="form.p_category").value = ['hostel_maintenance']
2625        self.browser.getControl("Create ticket").click()
2626        self.assertMatches('...You have not yet booked accommodation...',
2627                           self.browser.contents)
2628        # We continue this test in test_student_accommodation
2629
2630    def test_student_previous_payments(self):
2631        configuration = createObject('waeup.SessionConfiguration')
2632        configuration.academic_session = 2000
2633        configuration.clearance_fee = 3456.0
2634        configuration.booking_fee = 123.4
2635        self.app['configuration'].addSessionConfiguration(configuration)
2636        configuration2 = createObject('waeup.SessionConfiguration')
2637        configuration2.academic_session = 2003
2638        configuration2.clearance_fee = 3456.0
2639        configuration2.booking_fee = 123.4
2640        self.app['configuration'].addSessionConfiguration(configuration2)
2641        configuration3 = createObject('waeup.SessionConfiguration')
2642        configuration3.academic_session = 2005
2643        configuration3.clearance_fee = 3456.0
2644        configuration3.booking_fee = 123.4
2645        self.app['configuration'].addSessionConfiguration(configuration3)
2646        self.student['studycourse'].entry_session = 2002
2647
2648        # Login
2649        self.browser.open(self.login_path)
2650        self.browser.getControl(name="form.login").value = self.student_id
2651        self.browser.getControl(name="form.password").value = 'spwd'
2652        self.browser.getControl("Login").click()
2653
2654        # Students can add previous school fee payment tickets in any state.
2655        IWorkflowState(self.student).setState('courses registered')
2656        self.browser.open(self.payments_path)
2657        self.browser.getLink("Add previous session payment ticket").click()
2658
2659        # Previous session payment form is provided
2660        self.assertEqual(self.student.current_session, 2004)
2661        self.browser.getControl(name="form.p_category").value = ['schoolfee']
2662        self.browser.getControl(name="form.p_session").value = ['2000']
2663        self.browser.getControl(name="form.p_level").value = ['300']
2664        self.browser.getControl("Create ticket").click()
2665        self.assertMatches('...The previous session must not fall below...',
2666                           self.browser.contents)
2667        self.browser.getControl(name="form.p_category").value = ['schoolfee']
2668        self.browser.getControl(name="form.p_session").value = ['2005']
2669        self.browser.getControl(name="form.p_level").value = ['300']
2670        self.browser.getControl("Create ticket").click()
2671        self.assertMatches('...This is not a previous session...',
2672                           self.browser.contents)
2673        # Students can pay current session school fee.
2674        self.browser.getControl(name="form.p_category").value = ['schoolfee']
2675        self.browser.getControl(name="form.p_session").value = ['2004']
2676        self.browser.getControl(name="form.p_level").value = ['300']
2677        self.browser.getControl("Create ticket").click()
2678        self.assertMatches('...ticket created...',
2679                           self.browser.contents)
2680        ctrl = self.browser.getControl(name='val_id')
2681        value = ctrl.options[0]
2682        self.browser.getLink(value).click()
2683        self.assertMatches('...Amount Authorized...',
2684                           self.browser.contents)
2685        self.assertEqual(self.student['payments'][value].amount_auth, 20000.0)
2686
2687        # Payment session is properly set
2688        self.assertEqual(self.student['payments'][value].p_session, 2004)
2689        self.assertEqual(self.student['payments'][value].p_level, 300)
2690
2691        # We simulate the approval
2692        self.browser.open(self.browser.url + '/fake_approve')
2693        self.assertMatches('...Payment approved...',
2694                          self.browser.contents)
2695
2696        # No AC has been created
2697        self.assertEqual(len(self.app['accesscodes']['SFE-0'].keys()), 0)
2698        self.assertTrue(self.student['payments'][value].ac is None)
2699
2700        # Current payment flag is set False
2701        self.assertFalse(self.student['payments'][value].p_current)
2702
2703        # Button and form are not available for students who are in
2704        # states up to cleared
2705        self.student['studycourse'].entry_session = 2004
2706        IWorkflowState(self.student).setState('cleared')
2707        self.browser.open(self.payments_path)
2708        self.assertFalse(
2709            "Add previous session payment ticket" in self.browser.contents)
2710        self.browser.open(self.payments_path + '/addpp')
2711        self.assertTrue(
2712            "No previous payment to be made" in self.browser.contents)
2713        return
2714
2715    def test_postgraduate_student_payments(self):
2716        configuration = createObject('waeup.SessionConfiguration')
2717        configuration.academic_session = 2005
2718        self.app['configuration'].addSessionConfiguration(configuration)
2719        self.certificate.study_mode = 'pg_ft'
2720        self.certificate.start_level = 999
2721        self.certificate.end_level = 999
2722        self.student['studycourse'].current_level = 999
2723        # Login
2724        self.browser.open(self.login_path)
2725        self.browser.getControl(name="form.login").value = self.student_id
2726        self.browser.getControl(name="form.password").value = 'spwd'
2727        self.browser.getControl("Login").click()
2728        # Students can add online school fee payment tickets.
2729        IWorkflowState(self.student).setState('cleared')
2730        self.browser.open(self.payments_path)
2731        self.browser.getLink("Add current session payment ticket").click()
2732        self.browser.getControl(name="form.p_category").value = ['schoolfee']
2733        self.browser.getControl("Create ticket").click()
2734        self.assertMatches('...ticket created...',
2735                           self.browser.contents)
2736        ctrl = self.browser.getControl(name='val_id')
2737        value = ctrl.options[0]
2738        self.browser.getLink(value).click()
2739        self.assertMatches('...Amount Authorized...',
2740                           self.browser.contents)
2741        # Payment session and level are current ones.
2742        # Postgrads have to pay school_fee_1.
2743        self.assertEqual(self.student['payments'][value].amount_auth, 40000.0)
2744        self.assertEqual(self.student['payments'][value].p_session, 2004)
2745        self.assertEqual(self.student['payments'][value].p_level, 999)
2746
2747        # We simulate the approval
2748        self.assertEqual(len(self.app['accesscodes']['SFE-0']),0)
2749        self.browser.open(self.browser.url + '/fake_approve')
2750        self.assertMatches('...Payment approved...',
2751                          self.browser.contents)
2752
2753        # The new SFE-0 pin can be used for starting session
2754        self.browser.open(self.studycourse_path)
2755        self.browser.getLink('Start new session').click()
2756        pin = self.app['accesscodes']['SFE-0'].keys()[0]
2757        parts = pin.split('-')[1:]
2758        sfeseries, sfenumber = parts
2759        self.browser.getControl(name="ac_series").value = sfeseries
2760        self.browser.getControl(name="ac_number").value = sfenumber
2761        self.browser.getControl("Start now").click()
2762        self.assertMatches('...Session started...',
2763                           self.browser.contents)
2764        self.assertTrue(self.student.state == 'school fee paid')
2765
2766        # Postgrad students do not need to register courses the
2767        # can just pay for the next session.
2768        self.browser.open(self.payments_path)
2769        # Remove first payment to be sure that we access the right ticket
2770        del self.student['payments'][value]
2771        self.browser.getLink("Add current session payment ticket").click()
2772        self.browser.getControl(name="form.p_category").value = ['schoolfee']
2773        self.browser.getControl("Create ticket").click()
2774        ctrl = self.browser.getControl(name='val_id')
2775        value = ctrl.options[0]
2776        self.browser.getLink(value).click()
2777        # Payment session has increased by one, payment level remains the same.
2778        # Returning Postgraduates have to pay school_fee_2.
2779        self.assertEqual(self.student['payments'][value].amount_auth, 20000.0)
2780        self.assertEqual(self.student['payments'][value].p_session, 2005)
2781        self.assertEqual(self.student['payments'][value].p_level, 999)
2782
2783        # Student is still in old session
2784        self.assertEqual(self.student.current_session, 2004)
2785
2786        # We do not need to pay the ticket if any other
2787        # SFE pin is provided
2788        pin_container = self.app['accesscodes']
2789        pin_container.createBatch(
2790            datetime.utcnow(), 'some_userid', 'SFE', 9.99, 1)
2791        pin = pin_container['SFE-1'].values()[0].representation
2792        sfeseries, sfenumber = pin.split('-')[1:]
2793        # The new SFE-1 pin can be used for starting new session
2794        self.browser.open(self.studycourse_path)
2795        self.browser.getLink('Start new session').click()
2796        self.browser.getControl(name="ac_series").value = sfeseries
2797        self.browser.getControl(name="ac_number").value = sfenumber
2798        self.browser.getControl("Start now").click()
2799        self.assertMatches('...Session started...',
2800                           self.browser.contents)
2801        self.assertTrue(self.student.state == 'school fee paid')
2802        # Student is in new session
2803        self.assertEqual(self.student.current_session, 2005)
2804        self.assertEqual(self.student['studycourse'].current_level, 999)
2805        return
2806
2807    def test_student_accommodation(self):
2808        # Login
2809        self.browser.open(self.login_path)
2810        self.browser.getControl(name="form.login").value = self.student_id
2811        self.browser.getControl(name="form.password").value = 'spwd'
2812        self.browser.getControl("Login").click()
2813
2814        # Students can add online booking fee payment tickets and open the
2815        # callback view (see test_manage_payments)
2816        self.browser.getLink("Payments").click()
2817        self.browser.getLink("Add current session payment ticket").click()
2818        self.browser.getControl(name="form.p_category").value = ['bed_allocation']
2819        self.browser.getControl("Create ticket").click()
2820        ctrl = self.browser.getControl(name='val_id')
2821        value = ctrl.options[0]
2822        self.browser.getLink(value).click()
2823        self.browser.open(self.browser.url + '/fake_approve')
2824        # The new HOS-0 pin has been created
2825        self.assertEqual(len(self.app['accesscodes']['HOS-0']),1)
2826        pin = self.app['accesscodes']['HOS-0'].keys()[0]
2827        ac = self.app['accesscodes']['HOS-0'][pin]
2828        parts = pin.split('-')[1:]
2829        sfeseries, sfenumber = parts
2830
2831        # Students can use HOS code and book a bed space with it ...
2832        self.browser.open(self.acco_path)
2833        # ... but not if booking period has expired ...
2834        self.app['hostels'].enddate = datetime.now(pytz.utc)
2835        self.browser.getLink("Book accommodation").click()
2836        self.assertMatches('...Outside booking period: ...',
2837                           self.browser.contents)
2838        self.app['hostels'].enddate = datetime.now(pytz.utc) + timedelta(days=10)
2839        # ... or student is not the an allowed state ...
2840        self.browser.getLink("Book accommodation").click()
2841        self.assertMatches('...You are in the wrong...',
2842                           self.browser.contents)
2843        IWorkflowInfo(self.student).fireTransition('admit')
2844        self.browser.getLink("Book accommodation").click()
2845        self.assertMatches('...Activation Code:...',
2846                           self.browser.contents)
2847        # Student can't used faked ACs ...
2848        self.browser.getControl(name="ac_series").value = u'nonsense'
2849        self.browser.getControl(name="ac_number").value = sfenumber
2850        self.browser.getControl("Create bed ticket").click()
2851        self.assertMatches('...Activation code is invalid...',
2852                           self.browser.contents)
2853        # ... or ACs owned by somebody else.
2854        ac.owner = u'Anybody'
2855        self.browser.getControl(name="ac_series").value = sfeseries
2856        self.browser.getControl(name="ac_number").value = sfenumber
2857        self.browser.getControl("Create bed ticket").click()
2858        self.assertMatches('...You are not the owner of this access code...',
2859                           self.browser.contents)
2860        ac.owner = self.student_id
2861        self.browser.getControl(name="ac_series").value = sfeseries
2862        self.browser.getControl(name="ac_number").value = sfenumber
2863        self.browser.getControl("Create bed ticket").click()
2864        self.assertMatches('...Hall 1, Block A, Room 101, Bed A...',
2865                           self.browser.contents)
2866
2867        # Bed has been allocated
2868        bed = self.app['hostels']['hall-1']['hall-1_A_101_A']
2869        self.assertTrue(bed.owner == self.student_id)
2870
2871        # BedTicketAddPage is now blocked
2872        self.browser.getLink("Book accommodation").click()
2873        self.assertMatches('...You already booked a bed space...',
2874            self.browser.contents)
2875
2876        # The bed ticket displays the data correctly
2877        self.browser.open(self.acco_path + '/2004')
2878        self.assertMatches('...Hall 1, Block A, Room 101, Bed A...',
2879                           self.browser.contents)
2880        self.assertMatches('...2004/2005...', self.browser.contents)
2881        self.assertMatches('...regular_male_fr...', self.browser.contents)
2882        self.assertMatches('...%s...' % pin, self.browser.contents)
2883
2884        # Students can open the pdf slip
2885        self.browser.open(self.browser.url + '/bed_allocation_slip.pdf')
2886        self.assertEqual(self.browser.headers['Status'], '200 Ok')
2887        self.assertEqual(self.browser.headers['Content-Type'], 'application/pdf')
2888
2889        # Students can't relocate themselves
2890        self.assertFalse('Relocate' in self.browser.contents)
2891        relocate_path = self.acco_path + '/2004/relocate'
2892        self.assertRaises(
2893            Unauthorized, self.browser.open, relocate_path)
2894
2895        # Students can't the Remove button and check boxes
2896        self.browser.open(self.acco_path)
2897        self.assertFalse('Remove' in self.browser.contents)
2898        self.assertFalse('val_id' in self.browser.contents)
2899
2900        # Students can pay maintenance fee now
2901        self.browser.open(self.payments_path)
2902        self.browser.open(self.payments_path + '/addop')
2903        self.browser.getControl(name="form.p_category").value = ['hostel_maintenance']
2904        self.browser.getControl("Create ticket").click()
2905        self.assertMatches('...Payment ticket created...',
2906                           self.browser.contents)
2907        return
2908
2909    def test_change_password_request(self):
2910        self.browser.open('http://localhost/app/changepw')
2911        self.browser.getControl(name="form.identifier").value = '123'
2912        self.browser.getControl(name="form.email").value = 'aa@aa.ng'
2913        self.browser.getControl("Send login credentials").click()
2914        self.assertTrue('An email with' in self.browser.contents)
2915
2916    def test_student_expired_personal_data(self):
2917        # Login
2918        IWorkflowState(self.student).setState('school fee paid')
2919        delta = timedelta(days=180)
2920        self.student.personal_updated = datetime.utcnow() - delta
2921        self.browser.open(self.login_path)
2922        self.browser.getControl(name="form.login").value = self.student_id
2923        self.browser.getControl(name="form.password").value = 'spwd'
2924        self.browser.getControl("Login").click()
2925        self.assertEqual(self.browser.url, self.student_path)
2926        self.assertTrue(
2927            'You logged in' in self.browser.contents)
2928        # Students don't see personal_updated field in edit form
2929        self.browser.open(self.edit_personal_path)
2930        self.assertFalse('Updated' in self.browser.contents)
2931        self.browser.open(self.personal_path)
2932        self.assertTrue('Updated' in self.browser.contents)
2933        self.browser.getLink("Logout").click()
2934        delta = timedelta(days=181)
2935        self.student.personal_updated = datetime.utcnow() - delta
2936        self.browser.open(self.login_path)
2937        self.browser.getControl(name="form.login").value = self.student_id
2938        self.browser.getControl(name="form.password").value = 'spwd'
2939        self.browser.getControl("Login").click()
2940        self.assertEqual(self.browser.url, self.edit_personal_path)
2941        self.assertTrue(
2942            'Your personal data record is outdated.' in self.browser.contents)
2943
2944    def test_setReturningData(self):
2945        utils = getUtility(IStudentsUtils)
2946        self.student['studycourse'].current_level = 600
2947        utils.setReturningData(self.student)
2948        # The new level exceeds the certificates end_level.
2949        # In this case current_level remains unchanged and no error is raised.
2950        self.assertEqual(self.student['studycourse'].current_level, 600)
2951
2952    def test_request_transcript(self):
2953        IWorkflowState(self.student).setState('graduated')
2954        self.browser.open(self.login_path)
2955        self.browser.getControl(name="form.login").value = self.student_id
2956        self.browser.getControl(name="form.password").value = 'spwd'
2957        self.browser.getControl("Login").click()
2958        self.assertMatches(
2959            '...You logged in...', self.browser.contents)
2960        # Create payment ticket
2961        self.browser.open(self.payments_path)
2962        self.browser.open(self.payments_path + '/addop')
2963        self.browser.getControl(name="form.p_category").value = ['transcript']
2964        self.browser.getControl("Create ticket").click()
2965        ctrl = self.browser.getControl(name='val_id')
2966        value = ctrl.options[0]
2967        self.browser.getLink(value).click()
2968        self.assertMatches('...Amount Authorized...',
2969                           self.browser.contents)
2970        self.assertEqual(self.student['payments'][value].amount_auth, 4567.0)
2971        # Student is the payer of the payment ticket.
2972        payer = IPayer(self.student['payments'][value])
2973        self.assertEqual(payer.display_fullname, 'Anna Tester')
2974        self.assertEqual(payer.id, self.student_id)
2975        self.assertEqual(payer.faculty, 'fac1')
2976        self.assertEqual(payer.department, 'dep1')
2977        # We simulate the approval and fetch the pin
2978        self.assertEqual(len(self.app['accesscodes']['TSC-0']),0)
2979        self.browser.open(self.browser.url + '/fake_approve')
2980        self.assertMatches('...Payment approved...',
2981                          self.browser.contents)
2982        pin = self.app['accesscodes']['TSC-0'].keys()[0]
2983        parts = pin.split('-')[1:]
2984        tscseries, tscnumber = parts
2985        # Student can use the pin to send the transcript request
2986        self.browser.open(self.student_path)
2987        self.browser.getLink("Request transcript").click()
2988        self.browser.getControl(name="ac_series").value = tscseries
2989        self.browser.getControl(name="ac_number").value = tscnumber
2990        self.browser.getControl(name="comment").value = 'Comment line 1 \nComment line2'
2991        self.browser.getControl(name="address").value = 'Address line 1 \nAddress line2'
2992        self.browser.getControl("Submit").click()
2993        self.assertMatches('...Transcript processing has been started...',
2994                          self.browser.contents)
2995        self.assertEqual(self.student.state, 'transcript requested')
2996        self.assertMatches(
2997            '... UTC K1000000 wrote:\n\nComment line 1 \n'
2998            'Comment line2\n\nDispatch Address:\nAddress line 1 \n'
2999            'Address line2\n\n', self.student.transcript_comment)
3000        # The comment has been logged
3001        logfile = os.path.join(
3002            self.app['datacenter'].storage, 'logs', 'students.log')
3003        logcontent = open(logfile).read()
3004        self.assertTrue(
3005            'K1000000 - students.browser.StudentTranscriptRequestPage - '
3006            'K1000000 - comment: Comment line 1 <br>Comment line2\n'
3007            in logcontent)
3008
3009class StudentRequestPWTests(StudentsFullSetup):
3010    # Tests for student registration
3011
3012    layer = FunctionalLayer
3013
3014    def test_request_pw(self):
3015        # Student with wrong number can't be found.
3016        self.browser.open('http://localhost/app/requestpw')
3017        self.browser.getControl(name="form.firstname").value = 'Anna'
3018        self.browser.getControl(name="form.number").value = 'anynumber'
3019        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
3020        self.browser.getControl("Send login credentials").click()
3021        self.assertTrue('No student record found.'
3022            in self.browser.contents)
3023        # Anonymous is not informed that firstname verification failed.
3024        # It seems that the record doesn't exist.
3025        self.browser.open('http://localhost/app/requestpw')
3026        self.browser.getControl(name="form.firstname").value = 'Johnny'
3027        self.browser.getControl(name="form.number").value = '123'
3028        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
3029        self.browser.getControl("Send login credentials").click()
3030        self.assertTrue('No student record found.'
3031            in self.browser.contents)
3032        # Even with the correct firstname we can't register if a
3033        # password has been set and used.
3034        self.browser.getControl(name="form.firstname").value = 'Anna'
3035        self.browser.getControl(name="form.number").value = '123'
3036        self.browser.getControl("Send login credentials").click()
3037        self.assertTrue('Your password has already been set and used.'
3038            in self.browser.contents)
3039        self.browser.open('http://localhost/app/requestpw')
3040        self.app['students'][self.student_id].password = None
3041        # The firstname field, used for verification, is not case-sensitive.
3042        self.browser.getControl(name="form.firstname").value = 'aNNa'
3043        self.browser.getControl(name="form.number").value = '123'
3044        self.browser.getControl(name="form.email").value = 'new@yy.zz'
3045        self.browser.getControl("Send login credentials").click()
3046        # Yeah, we succeded ...
3047        self.assertTrue('Your password request was successful.'
3048            in self.browser.contents)
3049        # We can also use the matric_number instead.
3050        self.browser.open('http://localhost/app/requestpw')
3051        self.browser.getControl(name="form.firstname").value = 'aNNa'
3052        self.browser.getControl(name="form.number").value = '234'
3053        self.browser.getControl(name="form.email").value = 'new@yy.zz'
3054        self.browser.getControl("Send login credentials").click()
3055        self.assertTrue('Your password request was successful.'
3056            in self.browser.contents)
3057        # ... and  student can be found in the catalog via the email address
3058        cat = queryUtility(ICatalog, name='students_catalog')
3059        results = list(
3060            cat.searchResults(
3061            email=('new@yy.zz', 'new@yy.zz')))
3062        self.assertEqual(self.student,results[0])
3063        logfile = os.path.join(
3064            self.app['datacenter'].storage, 'logs', 'main.log')
3065        logcontent = open(logfile).read()
3066        self.assertTrue('zope.anybody - students.browser.StudentRequestPasswordPage - '
3067                        '234 (K1000000) - new@yy.zz' in logcontent)
3068        return
3069
3070    def test_student_locked_level_forms(self):
3071
3072        # Add two study levels, one current and one previous
3073        studylevel = createObject(u'waeup.StudentStudyLevel')
3074        studylevel.level = 100
3075        self.student['studycourse'].addStudentStudyLevel(
3076            self.certificate, studylevel)
3077        studylevel = createObject(u'waeup.StudentStudyLevel')
3078        studylevel.level = 200
3079        self.student['studycourse'].addStudentStudyLevel(
3080            self.certificate, studylevel)
3081        IWorkflowState(self.student).setState('school fee paid')
3082        self.student['studycourse'].current_level = 200
3083
3084        self.browser.open(self.login_path)
3085        self.browser.getControl(name="form.login").value = self.student_id
3086        self.browser.getControl(name="form.password").value = 'spwd'
3087        self.browser.getControl("Login").click()
3088
3089        self.browser.open(self.student_path + '/studycourse/200/edit')
3090        self.assertFalse('The requested form is locked' in self.browser.contents)
3091        self.browser.open(self.student_path + '/studycourse/100/edit')
3092        self.assertTrue('The requested form is locked' in self.browser.contents)
3093
3094        self.browser.open(self.student_path + '/studycourse/200/ctadd')
3095        self.assertFalse('The requested form is locked' in self.browser.contents)
3096        self.browser.open(self.student_path + '/studycourse/100/ctadd')
3097        self.assertTrue('The requested form is locked' in self.browser.contents)
3098
3099        IWorkflowState(self.student).setState('courses registered')
3100        self.browser.open(self.student_path + '/studycourse/200/edit')
3101        self.assertTrue('The requested form is locked' in self.browser.contents)
3102        self.browser.open(self.student_path + '/studycourse/200/ctadd')
3103        self.assertTrue('The requested form is locked' in self.browser.contents)
3104
3105
3106class PublicPagesTests(StudentsFullSetup):
3107    # Tests for simple webservices
3108
3109    layer = FunctionalLayer
3110
3111    def test_paymentrequest(self):
3112        payment = createObject('waeup.StudentOnlinePayment')
3113        payment.p_category = u'schoolfee'
3114        payment.p_session = self.student.current_session
3115        payment.p_item = u'My Certificate'
3116        payment.p_id = u'anyid'
3117        self.student['payments']['anykey'] = payment
3118        # Request information about unpaid payment ticket
3119        self.browser.open('http://localhost/app/paymentrequest?P_ID=anyid')
3120        self.assertEqual(self.browser.contents, '-1')
3121        # Request information about paid payment ticket
3122        payment.p_state = u'paid'
3123        notify(grok.ObjectModifiedEvent(payment))
3124        self.browser.open('http://localhost/app/paymentrequest?P_ID=anyid')
3125        self.assertEqual(self.browser.contents,
3126            'FULL_NAME=Anna Tester&FACULTY=fac1&DEPARTMENT=dep1'
3127            '&PAYMENT_ITEM=My Certificate&PAYMENT_CATEGORY=School Fee'
3128            '&ACADEMIC_SESSION=2004/2005&MATRIC_NUMBER=234&REG_NUMBER=123'
3129            '&FEE_AMOUNT=0.0')
3130        self.browser.open('http://localhost/app/paymentrequest?NONSENSE=nonsense')
3131        self.assertEqual(self.browser.contents, '-1')
3132        self.browser.open('http://localhost/app/paymentrequest?P_ID=nonsense')
3133        self.assertEqual(self.browser.contents, '-1')
3134
3135class StudentDataExportTests(StudentsFullSetup, FunctionalAsyncTestCase):
3136    # Tests for StudentsContainer class views and pages
3137
3138    layer = FunctionalLayer
3139
3140    def wait_for_export_job_completed(self):
3141        # helper function waiting until the current export job is completed
3142        manager = getUtility(IJobManager)
3143        job_id = self.app['datacenter'].running_exports[0][0]
3144        job = manager.get(job_id)
3145        wait_for_result(job)
3146        return job_id
3147
3148    def test_faculties_export(self):
3149        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
3150        facs_path = 'http://localhost/app/faculties'
3151        self.browser.open(facs_path)
3152        self.browser.getLink("Export student data").click()
3153        self.browser.getControl("Configure new export").click()
3154        self.browser.getControl(name="exporter").value = ['bursary']
3155        self.browser.getControl(name="session").value = ['2004']
3156        self.browser.getControl(name="level").value = ['100']
3157        self.browser.getControl(name="mode").value = ['ug_ft']
3158        self.browser.getControl("Create CSV file").click()
3159
3160        # When the job is finished and we reload the page...
3161        job_id = self.wait_for_export_job_completed()
3162        self.browser.open(facs_path + '/exports')
3163        # ... the csv file can be downloaded ...
3164        self.browser.getLink("Download").click()
3165        self.assertEqual(self.browser.headers['content-type'],
3166            'text/csv; charset=UTF-8')
3167        self.assertTrue(
3168            'filename="WAeUP.Kofa_bursary_%s.csv' % job_id in
3169            self.browser.headers['content-disposition'])
3170        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
3171        job_id = self.app['datacenter'].running_exports[0][0]
3172        # ... and discarded
3173        self.browser.open(facs_path + '/exports')
3174        self.browser.getControl("Discard").click()
3175        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
3176        # Creation, downloading and discarding is logged
3177        logfile = os.path.join(
3178            self.app['datacenter'].storage, 'logs', 'datacenter.log')
3179        logcontent = open(logfile).read()
3180        self.assertTrue(
3181            'zope.mgr - students.browser.FacultiesExportJobContainerJobConfig '
3182            '- exported: bursary (2004, 100, ug_ft, None, None), job_id=%s'
3183            % job_id in logcontent
3184            )
3185        self.assertTrue(
3186            'zope.mgr - students.browser.ExportJobContainerDownload '
3187            '- downloaded: WAeUP.Kofa_bursary_%s.csv, job_id=%s'
3188            % (job_id, job_id) in logcontent
3189            )
3190        self.assertTrue(
3191            'zope.mgr - students.browser.ExportJobContainerOverview '
3192            '- discarded: job_id=%s' % job_id in logcontent
3193            )
3194
3195    def test_department_export(self):
3196        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
3197        dep1_path = 'http://localhost/app/faculties/fac1/dep1'
3198        self.browser.open(dep1_path)
3199        self.browser.getLink("Export student data").click()
3200        self.browser.getControl("Configure new export").click()
3201        self.browser.getControl(name="exporter").value = ['students']
3202        self.browser.getControl(name="session").value = ['2004']
3203        self.browser.getControl(name="level").value = ['100']
3204        self.browser.getControl(name="mode").value = ['ug_ft']
3205        self.browser.getControl("Create CSV file").click()
3206
3207        # When the job is finished and we reload the page...
3208        job_id = self.wait_for_export_job_completed()
3209        self.browser.open(dep1_path + '/exports')
3210        # ... the csv file can be downloaded ...
3211        self.browser.getLink("Download").click()
3212        self.assertEqual(self.browser.headers['content-type'],
3213            'text/csv; charset=UTF-8')
3214        self.assertTrue(
3215            'filename="WAeUP.Kofa_students_%s.csv' % job_id in
3216            self.browser.headers['content-disposition'])
3217        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
3218        job_id = self.app['datacenter'].running_exports[0][0]
3219        # ... and discarded
3220        self.browser.open(dep1_path + '/exports')
3221        self.browser.getControl("Discard").click()
3222        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
3223        # Creation, downloading and discarding is logged
3224        logfile = os.path.join(
3225            self.app['datacenter'].storage, 'logs', 'datacenter.log')
3226        logcontent = open(logfile).read()
3227        self.assertTrue(
3228            'zope.mgr - students.browser.DepartmentExportJobContainerJobConfig '
3229            '- exported: students (2004, 100, ug_ft, dep1, None), job_id=%s'
3230            % job_id in logcontent
3231            )
3232        self.assertTrue(
3233            'zope.mgr - students.browser.ExportJobContainerDownload '
3234            '- downloaded: WAeUP.Kofa_students_%s.csv, job_id=%s'
3235            % (job_id, job_id) in logcontent
3236            )
3237        self.assertTrue(
3238            'zope.mgr - students.browser.ExportJobContainerOverview '
3239            '- discarded: job_id=%s' % job_id in logcontent
3240            )
3241
3242    def test_certificate_export(self):
3243        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
3244        cert1_path = 'http://localhost/app/faculties/fac1/dep1/certificates/CERT1'
3245        self.browser.open(cert1_path)
3246        self.browser.getLink("Export student data").click()
3247        self.browser.getControl("Configure new export").click()
3248        self.browser.getControl(name="exporter").value = ['students']
3249        self.browser.getControl(name="session").value = ['2004']
3250        self.browser.getControl(name="level").value = ['100']
3251        self.browser.getControl("Create CSV file").click()
3252
3253        # When the job is finished and we reload the page...
3254        job_id = self.wait_for_export_job_completed()
3255        self.browser.open(cert1_path + '/exports')
3256        # ... the csv file can be downloaded ...
3257        self.browser.getLink("Download").click()
3258        self.assertEqual(self.browser.headers['content-type'],
3259            'text/csv; charset=UTF-8')
3260        self.assertTrue(
3261            'filename="WAeUP.Kofa_students_%s.csv' % job_id in
3262            self.browser.headers['content-disposition'])
3263        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
3264        job_id = self.app['datacenter'].running_exports[0][0]
3265        # ... and discarded
3266        self.browser.open(cert1_path + '/exports')
3267        self.browser.getControl("Discard").click()
3268        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
3269        # Creation, downloading and discarding is logged
3270        logfile = os.path.join(
3271            self.app['datacenter'].storage, 'logs', 'datacenter.log')
3272        logcontent = open(logfile).read()
3273        self.assertTrue(
3274            'zope.mgr - students.browser.CertificateExportJobContainerJobConfig '
3275            '- exported: students (2004, 100, None, None, CERT1), job_id=%s'
3276            % job_id in logcontent
3277            )
3278        self.assertTrue(
3279            'zope.mgr - students.browser.ExportJobContainerDownload '
3280            '- downloaded: WAeUP.Kofa_students_%s.csv, job_id=%s'
3281            % (job_id, job_id) in logcontent
3282            )
3283        self.assertTrue(
3284            'zope.mgr - students.browser.ExportJobContainerOverview '
3285            '- discarded: job_id=%s' % job_id in logcontent
3286            )
3287
3288    def test_course_export_students(self):
3289        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
3290        course1_path = 'http://localhost/app/faculties/fac1/dep1/courses/COURSE1'
3291        self.browser.open(course1_path)
3292        self.browser.getLink("Export student data").click()
3293        self.browser.getControl("Configure new export").click()
3294        self.browser.getControl(name="exporter").value = ['students']
3295        self.browser.getControl(name="session").value = ['2004']
3296        self.browser.getControl(name="level").value = ['100']
3297        self.browser.getControl("Create CSV file").click()
3298
3299        # When the job is finished and we reload the page...
3300        job_id = self.wait_for_export_job_completed()
3301        self.browser.open(course1_path + '/exports')
3302        # ... the csv file can be downloaded ...
3303        self.browser.getLink("Download").click()
3304        self.assertEqual(self.browser.headers['content-type'],
3305            'text/csv; charset=UTF-8')
3306        self.assertTrue(
3307            'filename="WAeUP.Kofa_students_%s.csv' % job_id in
3308            self.browser.headers['content-disposition'])
3309        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
3310        job_id = self.app['datacenter'].running_exports[0][0]
3311        # ... and discarded
3312        self.browser.open(course1_path + '/exports')
3313        self.browser.getControl("Discard").click()
3314        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
3315        # Creation, downloading and discarding is logged
3316        logfile = os.path.join(
3317            self.app['datacenter'].storage, 'logs', 'datacenter.log')
3318        logcontent = open(logfile).read()
3319        self.assertTrue(
3320            'zope.mgr - students.browser.CourseExportJobContainerJobConfig '
3321            '- exported: students (2004, 100, COURSE1), job_id=%s'
3322            % job_id in logcontent
3323            )
3324        self.assertTrue(
3325            'zope.mgr - students.browser.ExportJobContainerDownload '
3326            '- downloaded: WAeUP.Kofa_students_%s.csv, job_id=%s'
3327            % (job_id, job_id) in logcontent
3328            )
3329        self.assertTrue(
3330            'zope.mgr - students.browser.ExportJobContainerOverview '
3331            '- discarded: job_id=%s' % job_id in logcontent
3332            )
3333
3334    def test_course_export_coursetickets(self):
3335        # We add study level 100 to the student's studycourse
3336        studylevel = StudentStudyLevel()
3337        studylevel.level = 100
3338        studylevel.level_session = 2004
3339        self.student['studycourse'].addStudentStudyLevel(
3340            self.certificate,studylevel)
3341        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
3342        course1_path = 'http://localhost/app/faculties/fac1/dep1/courses/COURSE1'
3343        self.browser.open(course1_path)
3344        self.browser.getLink("Export student data").click()
3345        self.browser.getControl("Configure new export").click()
3346        self.browser.getControl(name="exporter").value = ['coursetickets']
3347        self.browser.getControl(name="session").value = ['2004']
3348        self.browser.getControl(name="level").value = ['100']
3349        self.browser.getControl("Create CSV file").click()
3350        # When the job is finished and we reload the page...
3351        job_id = self.wait_for_export_job_completed()
3352        self.browser.open(course1_path + '/exports')
3353        # ... the csv file can be downloaded ...
3354        self.browser.getLink("Download").click()
3355        self.assertEqual(self.browser.headers['content-type'],
3356            'text/csv; charset=UTF-8')
3357        self.assertTrue(
3358            'filename="WAeUP.Kofa_coursetickets_%s.csv' % job_id in
3359            self.browser.headers['content-disposition'])
3360        # ... and contains the course ticket COURSE1
3361        self.assertEqual(self.browser.contents,
3362            'automatic,carry_over,code,credits,dcode,fcode,level,'
3363            'level_session,mandatory,passmark,score,semester,title,'
3364            'student_id,certcode\r\n1,0,COURSE1,10,dep1,fac1,100,2004,1,40,,1,'
3365            'Unnamed Course,K1000000,CERT1\r\n')
3366
3367        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
3368        job_id = self.app['datacenter'].running_exports[0][0]
3369        # Thew job can be discarded
3370        self.browser.open(course1_path + '/exports')
3371        self.browser.getControl("Discard").click()
3372        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
3373        # Creation, downloading and discarding is logged
3374        logfile = os.path.join(
3375            self.app['datacenter'].storage, 'logs', 'datacenter.log')
3376        logcontent = open(logfile).read()
3377        self.assertTrue(
3378            'zope.mgr - students.browser.CourseExportJobContainerJobConfig '
3379            '- exported: coursetickets (2004, 100, COURSE1), job_id=%s'
3380            % job_id in logcontent
3381            )
3382        self.assertTrue(
3383            'zope.mgr - students.browser.ExportJobContainerDownload '
3384            '- downloaded: WAeUP.Kofa_coursetickets_%s.csv, job_id=%s'
3385            % (job_id, job_id) in logcontent
3386            )
3387        self.assertTrue(
3388            'zope.mgr - students.browser.ExportJobContainerOverview '
3389            '- discarded: job_id=%s' % job_id in logcontent
3390            )
3391
3392    def test_export_departmet_officers(self):
3393        # Create department officer
3394        self.app['users'].addUser('mrdepartment', 'mrdepartmentsecret')
3395        self.app['users']['mrdepartment'].email = 'mrdepartment@foo.ng'
3396        self.app['users']['mrdepartment'].title = 'Carlo Pitter'
3397        # Assign local role
3398        department = self.app['faculties']['fac1']['dep1']
3399        prmlocal = IPrincipalRoleManager(department)
3400        prmlocal.assignRoleToPrincipal('waeup.local.DepartmentOfficer', 'mrdepartment')
3401        # Login as department officer
3402        self.browser.open(self.login_path)
3403        self.browser.getControl(name="form.login").value = 'mrdepartment'
3404        self.browser.getControl(name="form.password").value = 'mrdepartmentsecret'
3405        self.browser.getControl("Login").click()
3406        self.assertMatches('...You logged in...', self.browser.contents)
3407        self.browser.open("http://localhost/app/faculties/fac1/dep1")
3408        self.browser.getLink("Export student data").click()
3409        self.browser.getControl("Configure new export").click()
3410        # Only the paymentsoverview exporter is available for department officers
3411        self.assertFalse('<option value="students">' in self.browser.contents)
3412        self.assertTrue(
3413            '<option value="paymentsoverview">' in self.browser.contents)
3414        self.browser.getControl(name="exporter").value = ['paymentsoverview']
3415        self.browser.getControl(name="session").value = ['2004']
3416        self.browser.getControl(name="level").value = ['100']
3417        self.browser.getControl("Create CSV file").click()
3418        self.assertTrue('Export started' in self.browser.contents)
3419        # Thew job can be discarded
3420        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
3421        #job_id = self.app['datacenter'].running_exports[0][0]
3422        job_id = self.wait_for_export_job_completed()
3423        self.browser.open("http://localhost/app/faculties/fac1/dep1/exports")
3424        self.browser.getControl("Discard").click()
3425        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
3426
3427    def test_export_bursary_officers(self):
3428        # Create bursary officer
3429        self.app['users'].addUser('mrbursary', 'mrbursarysecret')
3430        self.app['users']['mrbursary'].email = 'mrbursary@foo.ng'
3431        self.app['users']['mrbursary'].title = 'Carlo Pitter'
3432        prmglobal = IPrincipalRoleManager(self.app)
3433        prmglobal.assignRoleToPrincipal('waeup.BursaryOfficer', 'mrbursary')
3434        # Login as bursary officer
3435        self.browser.open(self.login_path)
3436        self.browser.getControl(name="form.login").value = 'mrbursary'
3437        self.browser.getControl(name="form.password").value = 'mrbursarysecret'
3438        self.browser.getControl("Login").click()
3439        self.assertMatches('...You logged in...', self.browser.contents)
3440        self.browser.getLink("Academics").click()
3441        self.browser.getLink("Export student data").click()
3442        self.browser.getControl("Configure new export").click()
3443        # Only the bursary exporter is available for bursary officers
3444        # not only at facultiescontainer level ...
3445        self.assertFalse('<option value="students">' in self.browser.contents)
3446        self.assertTrue('<option value="bursary">' in self.browser.contents)
3447        self.browser.getControl(name="exporter").value = ['bursary']
3448        self.browser.getControl(name="session").value = ['2004']
3449        self.browser.getControl(name="level").value = ['100']
3450        self.browser.getControl("Create CSV file").click()
3451        self.assertTrue('Export started' in self.browser.contents)
3452        # ... but also at other levels
3453        self.browser.open('http://localhost/app/faculties/fac1/dep1')
3454        self.browser.getLink("Export student data").click()
3455        self.browser.getControl("Configure new export").click()
3456        self.assertFalse('<option value="students">' in self.browser.contents)
3457        self.assertTrue('<option value="bursary">' in self.browser.contents)
3458        # Thew job can be discarded
3459        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
3460        #job_id = self.app['datacenter'].running_exports[0][0]
3461        job_id = self.wait_for_export_job_completed()
3462        self.browser.open('http://localhost/app/faculties/exports')
3463        self.browser.getControl("Discard").click()
3464        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
Note: See TracBrowser for help on using the repository browser.