source: main/waeup.kofa/trunk/src/waeup/kofa/applicants/tests/test_browser.py @ 13299

Last change on this file since 13299 was 13282, checked in by Henrik Bettermann, 9 years ago

Ignore trailing whitespaces when comparing lastname.

  • Property svn:keywords set to Id
File size: 72.6 KB
Line 
1## $Id: test_browser.py 13282 2015-10-06 04:25:35Z 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 applicant-related UI components.
20"""
21import os
22import pytz
23import shutil
24import tempfile
25import grok
26from datetime import datetime
27from StringIO import StringIO
28from datetime import datetime, date, timedelta
29from mechanize import LinkNotFoundError
30from zc.async.testing import wait_for_result
31from zope.securitypolicy.interfaces import IPrincipalRoleManager
32from zope.event import notify
33from zope.catalog.interfaces import ICatalog
34from zope.component import createObject, getUtility
35from zope.component.hooks import setSite, clearSite
36from zope.security.interfaces import Unauthorized
37from zope.testbrowser.testing import Browser
38from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState
39from waeup.kofa.testing import FunctionalLayer, FunctionalTestCase
40from waeup.kofa.app import University
41from waeup.kofa.payments.interfaces import IPayer
42from waeup.kofa.configuration import SessionConfiguration
43from waeup.kofa.applicants.container import ApplicantsContainer
44from waeup.kofa.applicants.applicant import Applicant
45from waeup.kofa.interfaces import (
46    IExtFileStore, IFileStoreNameChooser, IUserAccount, IJobManager)
47from waeup.kofa.university.faculty import Faculty
48from waeup.kofa.university.department import Department
49from waeup.kofa.tests.test_async import FunctionalAsyncTestCase
50
51PH_LEN = 15911  # Length of placeholder file
52
53session_1 = datetime.now().year - 2
54container_name_1 = u'app%s' % session_1
55session_2 = datetime.now().year - 1
56container_name_2 = u'app%s' % session_2
57
58SAMPLE_IMAGE = os.path.join(os.path.dirname(__file__), 'test_image.jpg')
59
60class ApplicantsFullSetup(FunctionalTestCase):
61    # A test case that only contains a setup and teardown
62    #
63    # Complete setup for applicants handlings is rather complex and
64    # requires lots of things created before we can start. This is a
65    # setup that does all this, creates a university, creates PINs,
66    # etc.  so that we do not have to bother with that in different
67    # test cases.
68
69    layer = FunctionalLayer
70
71    def setUp(self):
72        super(ApplicantsFullSetup, self).setUp()
73
74        # Setup a sample site for each test
75        app = University()
76        self.dc_root = tempfile.mkdtemp()
77        app['datacenter'].setStoragePath(self.dc_root)
78
79        # Prepopulate the ZODB...
80        self.getRootFolder()['app'] = app
81        # we add the site immediately after creation to the
82        # ZODB. Catalogs and other local utilities are not setup
83        # before that step.
84        self.app = self.getRootFolder()['app']
85        # Set site here. Some of the following setup code might need
86        # to access grok.getSite() and should get our new app then
87        setSite(app)
88
89        self.login_path = 'http://localhost/app/login'
90        self.root_path = 'http://localhost/app/applicants'
91        self.search_path = 'http://localhost/app/applicants/search'
92        self.manage_root_path = self.root_path + '/@@manage'
93        self.add_container_path = self.root_path + '/@@add'
94        self.container_path = 'http://localhost/app/applicants/%s' % container_name_1
95        self.manage_container_path = self.container_path + '/@@manage'
96
97        # Add an applicants container
98        applicantscontainer = ApplicantsContainer()
99        applicantscontainer.code = container_name_1
100        applicantscontainer.prefix = 'app'
101        applicantscontainer.year = session_1
102        applicantscontainer.title = u'This is the %s container' % container_name_1
103        applicantscontainer.application_category = 'basic'
104        applicantscontainer.mode = 'create'
105        applicantscontainer.strict_deadline = True
106        delta = timedelta(days=10)
107        applicantscontainer.startdate = datetime.now(pytz.utc) - delta
108        applicantscontainer.enddate = datetime.now(pytz.utc) + delta
109        self.app['applicants'][container_name_1] = applicantscontainer
110        self.applicantscontainer = self.app['applicants'][container_name_1]
111
112        # Populate university
113        certificate = createObject('waeup.Certificate')
114        certificate.code = 'CERT1'
115        certificate.application_category = 'basic'
116        certificate.start_level = 100
117        certificate.end_level = 500
118        certificate.study_mode = u'ug_ft'
119        self.certificate = certificate
120        self.app['faculties']['fac1'] = Faculty()
121        # The code has explicitely to be set, otherwise we don't
122        # find created students in their department
123        self.app['faculties']['fac1']['dep1'] = Department(code=u'dep1')
124        self.department = self.app['faculties']['fac1']['dep1']
125        self.app['faculties']['fac1']['dep1'].certificates.addCertificate(
126            certificate)
127
128        # Put the prepopulated site into test ZODB and prepare test
129        # browser
130        self.browser = Browser()
131        self.browser.handleErrors = False
132
133        # Create 5 access codes with prefix'FOO' and cost 9.99 each
134        pin_container = self.app['accesscodes']
135        pin_container.createBatch(
136            datetime.now(), 'some_userid', 'APP', 9.99, 5)
137        pins = pin_container[pin_container.keys()[0]].values()
138        self.pins = [x.representation for x in pins]
139        self.existing_pin = self.pins[0]
140        parts = self.existing_pin.split('-')[1:]
141        self.existing_series, self.existing_number = parts
142
143        # Add an applicant
144        self.applicant = createObject('waeup.Applicant')
145        # reg_number is the only field which has to be preset here
146        # because managers are allowed to edit this required field
147        self.applicant.firstname = u'Joan'
148        self.applicant.reg_number = u'1234'
149        self.applicant.course1 = certificate
150        app['applicants'][container_name_1].addApplicant(self.applicant)
151        IUserAccount(
152            self.app['applicants'][container_name_1][
153            self.applicant.application_number]).setPassword('apwd')
154        self.manage_path = 'http://localhost/app/applicants/%s/%s/%s' % (
155            container_name_1, self.applicant.application_number, 'manage')
156        self.edit_path = 'http://localhost/app/applicants/%s/%s/%s' % (
157            container_name_1, self.applicant.application_number, 'edit')
158        self.view_path = 'http://localhost/app/applicants/%s/%s' % (
159            container_name_1, self.applicant.application_number)
160
161    def login(self):
162        # Perform an applicant login. This creates an application record.
163        #
164        # This helper also sets `self.applicant`, which is the
165        # applicant object created.
166        self.browser.open(self.login_path)
167        self.browser.getControl(
168            name="form.login").value = self.applicant.applicant_id
169        self.browser.getControl(name="form.password").value = 'apwd'
170        self.browser.getControl("Login").click()
171
172    def fill_correct_values(self):
173        # Fill the edit form with suitable values
174        self.browser.getControl(name="form.firstname").value = 'John'
175        self.browser.getControl(name="form.middlename").value = 'Anthony'
176        self.browser.getControl(name="form.lastname").value = 'Tester'
177        self.browser.getControl(name="form.course1").value = ['CERT1']
178        self.browser.getControl(name="form.date_of_birth").value = '09/09/1988'
179        self.browser.getControl(name="form.sex").value = ['m']
180        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
181
182    def tearDown(self):
183        super(ApplicantsFullSetup, self).tearDown()
184        clearSite()
185        shutil.rmtree(self.dc_root)
186
187class ApplicantsRootUITests(ApplicantsFullSetup):
188    # Tests for ApplicantsRoot class
189
190    layer = FunctionalLayer
191
192    def test_anonymous_access(self):
193        # Anonymous users can access applicants root
194        self.browser.open(self.root_path)
195        self.assertEqual(self.browser.headers['Status'], '200 Ok')
196        self.assertFalse(
197            'Manage ' in self.browser.contents)
198        return
199
200    def test_anonymous_no_actions(self):
201        # Make sure anonymous users cannot access actions
202        self.browser.open(self.root_path)
203        self.assertRaises(
204            LookupError, self.browser.getControl, "Add local role")
205        # Manage screen neither linked nor accessible for anonymous
206        self.assertRaises(
207            LinkNotFoundError,
208            self.browser.getLink, 'Manage applicants section')
209        self.assertRaises(
210            Unauthorized, self.browser.open, self.manage_root_path)
211        # Add container screen not accessible for anonymous
212        self.assertRaises(
213            Unauthorized, self.browser.open, self.add_container_path)
214        return
215
216    def test_manage_access(self):
217        # Managers can access the manage pages of applicants root
218        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
219        self.browser.open(self.root_path)
220        self.assertTrue('Manage applicants section' in self.browser.contents)
221        # There is a manage link
222        link = self.browser.getLink('Manage applicants section')
223        link.click()
224        self.assertEqual(self.browser.headers['Status'], '200 Ok')
225        self.assertEqual(self.browser.url, self.manage_root_path)
226        return
227
228    def test_hide_container(self):
229        self.browser.open(self.root_path)
230        self.assertTrue(
231            '<a href="http://localhost/app/applicants/%s">'
232            'This is the %s container</a>' % (container_name_1, container_name_1)
233            in self.browser.contents)
234        self.app['applicants'][container_name_1].hidden = True
235        self.browser.open(self.root_path)
236        # Anonymous users can't see hidden containers
237        self.assertFalse(
238            '<a href="http://localhost/app/applicants/%s">'
239            'This is the %s container</a>' % (container_name_1, container_name_1)
240            in self.browser.contents)
241        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
242        self.browser.open(self.root_path)
243        self.assertTrue(
244            '<a href="http://localhost/app/applicants/%s">'
245            'This is the %s container</a>' % (container_name_1, container_name_1)
246            in self.browser.contents)
247        return
248
249    def test_search(self):
250        # Managers can access the manage pages of applicants root
251        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
252        self.browser.open(self.manage_path)
253        self.fill_correct_values()
254        self.browser.getControl("Save").click()
255        self.browser.open(self.root_path)
256        self.assertTrue('Manage applicants section' in self.browser.contents)
257        # There is a search link
258        link = self.browser.getLink('Find applicants')
259        link.click()
260        self.assertEqual(self.browser.headers['Status'], '200 Ok')
261        # We can find an applicant ...
262        # ... via his name
263        self.browser.getControl(name="searchtype").value = ['fullname']
264        self.browser.getControl(name="searchterm").value = 'John'
265        self.browser.getControl("Find applicant").click()
266        self.assertTrue('John Anthony Tester' in self.browser.contents)
267        self.browser.getControl(name="searchtype").value = ['fullname']
268        self.browser.getControl(name="searchterm").value = 'Tester'
269        self.browser.getControl("Find applicant").click()
270        self.assertTrue('John Anthony Tester' in self.browser.contents)
271        self.browser.open(self.search_path)
272        # ... and via his reg_number ...
273        self.browser.getControl(name="searchtype").value = ['reg_number']
274        self.browser.getControl(name="searchterm").value = '2345'
275        self.browser.getControl("Find applicant").click()
276        self.assertFalse('John Anthony Tester' in self.browser.contents)
277        self.browser.getControl(name="searchtype").value = ['reg_number']
278        self.browser.getControl(name="searchterm").value = '1234'
279        self.browser.getControl("Find applicant").click()
280        self.assertTrue('John Anthony Tester' in self.browser.contents)
281        # ... and not via his application_number ...
282        self.browser.getControl(name="searchtype").value = ['applicant_id']
283        self.browser.getControl(
284            name="searchterm").value = self.applicant.application_number
285        self.browser.getControl("Find applicant").click()
286        self.assertFalse('John Anthony Tester' in self.browser.contents)
287        # ... but ia his applicant_id ...
288        self.browser.getControl(name="searchtype").value = ['applicant_id']
289        self.browser.getControl(
290            name="searchterm").value = self.applicant.applicant_id
291        self.browser.getControl("Find applicant").click()
292        self.assertTrue('John Anthony Tester' in self.browser.contents)
293        # ... and via his email
294        self.browser.getControl(name="searchtype").value = ['email']
295        self.browser.getControl(name="searchterm").value = 'xx@yy.zz'
296        self.browser.getControl("Find applicant").click()
297        self.assertTrue('John Anthony Tester' in self.browser.contents)
298        return
299
300    def test_manage_actions_access(self):
301        # Managers can access the action on manage screen
302        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
303        self.browser.open(self.manage_root_path)
304        self.browser.getControl("Add local role").click()
305        self.assertTrue('No user selected' in self.browser.contents)
306        return
307
308    def test_local_roles_add_delete(self):
309        # Managers can assign and delete local roles of applicants root
310        myusers = self.app['users']
311        myusers.addUser('bob', 'bobssecret')
312        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
313        self.browser.open('http://localhost/app/faculties/fac1/dep1/manage')
314        self.browser.getControl(name="user").value = ['bob']
315        self.browser.getControl(name="local_role").value = [
316            'waeup.local.ApplicationsManager']
317        self.browser.getControl("Add local role").click()
318        self.assertTrue('<td>bob</td>' in self.browser.contents)
319        # Remove the role assigned
320        ctrl = self.browser.getControl(name='role_id')
321        ctrl.getControl(
322            value='bob|waeup.local.ApplicationsManager').selected = True
323        self.browser.getControl("Remove selected local roles").click()
324        self.assertTrue(
325            'Local role successfully removed: bob|waeup.local.ApplicationsManager'
326            in self.browser.contents)
327        self.assertFalse('<td>bob</td>' in self.browser.contents)
328        return
329
330    def test_add_delete_container(self):
331        # Managers can add and delete applicants containers
332        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
333        self.browser.open(self.manage_root_path)
334        self.browser.getControl("Add applicants container").click()
335        self.assertEqual(self.browser.headers['Status'], '200 Ok')
336        self.assertEqual(self.browser.url, self.add_container_path)
337        self.browser.getControl(name="form.prefix").value = ['app']
338        self.browser.getControl("Add applicants container").click()
339        self.assertTrue(
340            'There were errors' in self.browser.contents)
341        self.browser.getControl(name="form.prefix").value = ['app']
342        self.browser.getControl(name="form.year").value = [str(session_2)]
343        self.browser.getControl(name="form.mode").value = ['create']
344        self.browser.getControl(
345            name="form.application_category").value = ['basic']
346        self.browser.getControl("Add applicants container").click()
347        self.assertTrue('Added:' in self.browser.contents)
348        self.browser.getLink(container_name_1).click()
349        self.assertTrue('Manage applicants container'
350            in self.browser.contents)
351        self.browser.open(self.add_container_path)
352        self.browser.getControl("Cancel").click()
353        self.assertEqual(self.browser.url, self.manage_root_path)
354        self.browser.open(self.add_container_path)
355        self.browser.getControl(name="form.prefix").value = ['app']
356        self.browser.getControl(name="form.year").value = [str(session_2)]
357        self.browser.getControl(name="form.mode").value = ['create']
358        self.browser.getControl(
359            name="form.application_category").value = ['basic']
360        self.browser.getControl("Add applicants container").click()
361        self.assertTrue('exists already in the database'
362                        in self.browser.contents)
363        self.browser.open(self.manage_root_path)
364        ctrl = self.browser.getControl(name='val_id')
365        ctrl.getControl(value=container_name_2).selected = True
366        self.browser.getControl("Remove selected", index=0).click()
367        self.assertTrue('Successfully removed:' in self.browser.contents)
368        self.browser.open(self.add_container_path)
369        self.browser.getControl(name="form.prefix").value = ['app']
370        self.browser.getControl(name="form.year").value = [str(session_2)]
371        self.browser.getControl(name="form.mode").value = ['create']
372        #self.browser.getControl(name="form.ac_prefix").value = ['APP']
373        self.browser.getControl(
374            name="form.application_category").value = ['basic']
375        self.browser.getControl("Add applicants container").click()
376        del self.app['applicants'][container_name_2]
377        ctrl = self.browser.getControl(name='val_id')
378        ctrl.getControl(value=container_name_2).selected = True
379        self.browser.getControl("Remove selected", index=0).click()
380        self.assertMatches('...Could not delete...', self.browser.contents)
381        return
382
383class ApplicantsContainerUITests(ApplicantsFullSetup):
384    # Tests for ApplicantsContainer class views and pages
385
386    layer = FunctionalLayer
387
388    def test_anonymous_access(self):
389        # Anonymous users can access applicants containers
390        self.browser.open(self.container_path)
391        self.assertEqual(self.browser.headers['Status'], '200 Ok')
392        self.assertFalse(
393            'Manage ' in self.browser.contents)
394        return
395
396    def test_manage_access(self):
397        # Managers can access the manage pages of applicants
398        # containers and can perform actions
399        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
400        self.browser.open(self.manage_container_path)
401        self.assertEqual(self.browser.headers['Status'], '200 Ok')
402        self.assertEqual(self.browser.url, self.manage_container_path)
403        self.browser.getControl(name="form.application_fee").value = '200'
404        self.browser.getControl("Save").click()
405        self.assertTrue('Form has been saved' in self.browser.contents)
406        logfile = os.path.join(
407            self.app['datacenter'].storage, 'logs', 'applicants.log')
408        logcontent = open(logfile).read()
409        self.assertTrue(
410            'zope.mgr - applicants.browser.ApplicantsContainerManageFormPage - '
411            '%s - saved: application_fee\n' % container_name_1 in logcontent)
412        self.browser.getControl("Remove selected", index=0).click()
413        self.assertTrue('No applicant selected' in self.browser.contents)
414        self.browser.getControl("Add local role").click()
415        self.assertTrue('No user selected' in self.browser.contents)
416        self.browser.getControl("Cancel", index=0).click()
417        self.assertEqual(self.browser.url, self.container_path)
418        return
419
420    def test_statistics(self):
421        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
422        self.browser.open(self.container_path)
423        self.browser.getLink("Container statistics").click()
424        self.assertTrue('<td>initialized</td>' in self.browser.contents)
425        self.assertTrue('<td>1</td>' in self.browser.contents)
426        self.assertEqual(self.applicantscontainer.statistics[0],
427            {'not admitted': 0, 'started': 0, 'created': 0,
428            'admitted': 0, 'submitted': 0, 'initialized': 1, 'paid': 0})
429        #self.assertEqual(self.applicantscontainer.statistics[1],
430        #    {u'fac1': 0})
431        IWorkflowState(self.applicant).setState('submitted')
432        notify(grok.ObjectModifiedEvent(self.applicant))
433        self.assertEqual(self.applicantscontainer.statistics[0],
434            {'not admitted': 0, 'started': 0, 'created': 0,
435            'admitted': 0, 'submitted': 1, 'initialized': 0, 'paid': 0})
436        #self.assertEqual(self.applicantscontainer.statistics[1],
437        #    {u'fac1': 1})
438        return
439
440    def test_add_delete_applicants(self):
441        # Check the global role map first
442        role_manager = IPrincipalRoleManager(grok.getSite())
443        principals = role_manager.getPrincipalsForRole('waeup.Applicant')
444        self.assertEqual(len(principals), 1)
445        self.assertEqual(principals[0][0], self.applicant.applicant_id)
446        # Managers can add and delete applicants
447        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
448        self.add_applicant_path = self.container_path + '/addapplicant'
449        self.container_manage_path = self.container_path + '/@@manage'
450        self.browser.open(self.container_manage_path)
451        self.browser.getLink("Add applicant").click()
452        self.assertEqual(self.browser.headers['Status'], '200 Ok')
453        self.assertEqual(self.browser.url, self.add_applicant_path)
454        self.browser.getControl(name="form.firstname").value = 'Alois'
455        self.browser.getControl(name="form.middlename").value = 'Kofi'
456        self.browser.getControl(name="form.lastname").value = 'Bettermann'
457        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
458        self.browser.getControl("Create application record").click()
459        self.assertTrue('Application initialized' in self.browser.contents)
460        # The global role map has been extended
461        role_manager = IPrincipalRoleManager(grok.getSite())
462        principals = role_manager.getPrincipalsForRole('waeup.Applicant')
463        self.assertEqual(len(principals), 2)
464        self.browser.open(self.container_manage_path)
465        self.assertEqual(self.browser.headers['Status'], '200 Ok')
466        ctrl = self.browser.getControl(name='val_id')
467        value = ctrl.options[0]
468        ctrl.getControl(value=value).selected = True
469        self.browser.getControl("Remove selected", index=0).click()
470        self.assertTrue('Successfully removed:' in self.browser.contents)
471        # The global role map has been reduced
472        role_manager = IPrincipalRoleManager(grok.getSite())
473        principals = role_manager.getPrincipalsForRole('waeup.Applicant')
474        self.assertEqual(len(principals), 1)
475        self.browser.open(self.add_applicant_path)
476        self.browser.getControl(name="form.firstname").value = 'Albert'
477        self.browser.getControl(name="form.lastname").value = 'Einstein'
478        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
479        self.browser.getControl("Create application record").click()
480        self.assertTrue('Application initialized' in self.browser.contents)
481        return
482
483    def test_prefill_purge_container(self):
484        # Managers can pre-fill containers in create mode
485        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
486        self.prefill_path = self.container_path + '/prefill'
487        self.container_manage_path = self.container_path + '/@@manage'
488        self.browser.open(self.container_manage_path)
489        self.browser.getLink("Pre-fill").click()
490        self.assertEqual(self.browser.headers['Status'], '200 Ok')
491        self.assertEqual(self.browser.url, self.prefill_path)
492        self.browser.getControl(name="number").value = ['10']
493        self.browser.getControl("Pre-fill").click()
494        self.assertTrue('10 application records created.' in self.browser.contents)
495        self.browser.open(self.container_manage_path)
496        self.assertTrue('This container contains 10 unused pre-filled records.'
497            in self.browser.contents)
498        self.assertEqual(self.applicantscontainer.counts[0], 11)
499        self.assertEqual(self.applicantscontainer.counts[1], 1)
500        # In update mode we can't pre-fill the container
501        self.applicantscontainer.mode = 'update'
502        self.browser.open(self.container_manage_path)
503        self.browser.getLink("Pre-fill").click()
504        self.assertTrue('Container must be in create mode to be pre-filled.'
505            in self.browser.contents)
506        self.browser.open(self.manage_root_path)
507        # Number of total records is 11
508        self.assertTrue('<td>11</td>' in self.browser.contents)
509        # The statistics have not changed
510        self.browser.open(self.container_path)
511        self.browser.getLink("Container statistics").click()
512        self.assertTrue('<td>1</td>' in self.browser.contents)
513        self.assertEqual(self.applicantscontainer.statistics[0],
514            {'not admitted': 0, 'started': 0, 'created': 0,
515            'admitted': 0, 'submitted': 0, 'initialized': 1, 'paid': 0})
516        # Container can be purged
517        IWorkflowState(self.applicant).setState('submitted')
518        self.browser.open(self.container_manage_path)
519        self.browser.getLink("Purge").click()
520        self.browser.getControl("Remove").click()
521        self.assertTrue('10 application records purged' in self.browser.contents)
522        self.assertEqual(self.applicantscontainer.counts[0], 1)
523        self.assertEqual(self.applicantscontainer.counts[1], 1)
524        IWorkflowState(self.applicant).setState('initialized')
525        self.browser.open(self.container_manage_path)
526        self.browser.getLink("Purge").click()
527        self.browser.getControl("Remove").click()
528        self.assertTrue('1 application records purged' in self.browser.contents)
529        self.assertEqual(self.applicantscontainer.counts[0], 0)
530        self.assertEqual(self.applicantscontainer.counts[1], 0)
531        return
532
533class ApplicantUITests(ApplicantsFullSetup):
534    # Tests for uploading/browsing the passport image of appplicants
535
536    layer = FunctionalLayer
537
538    def test_manage_and_view_applicant(self):
539        # Managers can manage applicants
540        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
541        self.slip_path = self.view_path + '/application_slip.pdf'
542        self.browser.open(self.manage_path)
543        self.assertEqual(self.browser.headers['Status'], '200 Ok')
544        self.fill_correct_values()
545        # Fire transition
546        self.browser.getControl(name="transition").value = ['start']
547        self.browser.getControl("Save").click()
548        # Be sure that the empty phone field does not show wrong error message
549        self.assertFalse('Required input is missing' in self.browser.contents)
550        self.assertMatches('...Form has been saved...', self.browser.contents)
551        self.assertMatches('...Application started by Manager...',
552                           self.browser.contents)
553        self.browser.open(self.view_path)
554        self.assertEqual(self.browser.headers['Status'], '200 Ok')
555        # Change course_admitted
556        self.browser.open(self.manage_path)
557        self.browser.getControl(name="form.course_admitted").value = ['CERT1']
558        self.browser.getControl("Save").click()
559        self.assertMatches('...Form has been saved...', self.browser.contents)
560        # Change password
561        self.browser.getControl(name="password").value = 'secret'
562        self.browser.getControl(name="control_password").value = 'secre'
563        self.browser.getControl("Save").click()
564        self.assertMatches('...Passwords do not match...',
565                           self.browser.contents)
566        self.browser.getControl(name="password").value = 'secret'
567        self.browser.getControl(name="control_password").value = 'secret'
568        self.browser.getControl("Save").click()
569        self.assertMatches('...Form has been saved...', self.browser.contents)
570        # Pdf slip can't be opened and download button is not available
571        self.assertFalse('Download application slip' in self.browser.contents)
572        self.browser.open(self.slip_path)
573        self.assertTrue(
574            'Please pay and submit before trying to download the application slip.'
575            in self.browser.contents)
576        # If applicant is in correct state the pdf slip can be opened.
577        IWorkflowState(self.applicant).setState('submitted')
578        self.browser.open(self.manage_path)
579        self.browser.getLink("Download application slip").click()
580        self.assertEqual(self.browser.headers['Status'], '200 Ok')
581        self.assertEqual(self.browser.headers['Content-Type'],
582                         'application/pdf')
583        # Managers can view applicants even if certificate has been removed
584        del self.app['faculties']['fac1']['dep1'].certificates['CERT1']
585        self.browser.open(self.view_path)
586        self.assertEqual(self.browser.headers['Status'], '200 Ok')
587        self.browser.open(self.slip_path)
588        self.assertEqual(self.browser.headers['Status'], '200 Ok')
589        return
590
591    def test_passport_edit_view(self):
592        # We get a default image after login
593        self.browser.open(self.login_path)
594        self.login()
595        self.browser.open(self.browser.url + '/passport.jpg')
596        self.assertEqual(self.browser.headers['status'], '200 Ok')
597        self.assertEqual(self.browser.headers['content-type'], 'image/jpeg')
598        self.assertTrue('JFIF' in self.browser.contents)
599        self.assertEqual(
600            self.browser.headers['content-length'], str(PH_LEN))
601
602    def test_applicant_login(self):
603        self.applicant.suspended = True
604        self.login()
605        self.assertTrue(
606            'You entered invalid credentials.' in self.browser.contents)
607        self.applicant.suspended = False
608        self.browser.getControl("Login").click()
609        self.assertTrue(
610            'You logged in.' in self.browser.contents)
611
612    def test_applicant_access(self):
613        # Applicants can edit their record
614        self.browser.open(self.login_path)
615        self.login()
616        self.assertTrue(
617            'You logged in.' in self.browser.contents)
618        self.browser.open(self.edit_path)
619        self.assertTrue(self.browser.url != self.login_path)
620        self.assertEqual(self.browser.headers['Status'], '200 Ok')
621        self.fill_correct_values()
622        self.assertTrue(IUserAccount(self.applicant).checkPassword('apwd'))
623        self.browser.getControl("Save").click()
624        self.assertMatches('...Form has been saved...', self.browser.contents)
625        # Applicants don't see manage and search links ...
626        self.browser.open(self.root_path)
627        self.assertEqual(self.browser.headers['Status'], '200 Ok')
628        self.assertFalse('Search' in self.browser.contents)
629        self.assertFalse('Manage applicants section' in self.browser.contents)
630        # ... and can't access the manage page
631        self.assertRaises(
632            Unauthorized, self.browser.open, self.manage_path)
633        return
634
635    def test_message_for_created(self):
636        IWorkflowState(self.applicant).setState('created')
637        self.applicant.student_id = u'my id'
638        self.browser.open(self.login_path)
639        self.login()
640        self.assertTrue(
641            'You logged in.' in self.browser.contents)
642        self.assertTrue(
643            '<strong>Congratulations!</strong> You have been offered provisional'
644            ' admission into the %s/%s Academic Session of'
645            ' Sample University. Your student record has been created for you.'
646            % (session_1, session_1 + 1) in self.browser.contents)
647        self.assertTrue(
648            'Then enter your new student credentials: user name= my id,'
649            ' password = %s.' % self.applicant.application_number
650            in self.browser.contents)
651        return
652
653    def image_url(self, filename):
654        return self.edit_path.replace('edit', filename)
655
656    def test_after_login_default_browsable(self):
657        # After login we see the placeholder image in the edit view
658        self.login()
659        self.assertEqual(self.browser.url, self.view_path)
660        self.browser.open(self.edit_path)
661        # There is a correct <img> link included
662        self.assertTrue(
663              '<img src="passport.jpg" height="180px" />' in self.browser.contents)
664        # Browsing the link shows a real image
665        self.browser.open(self.image_url('passport.jpg'))
666        self.assertEqual(
667            self.browser.headers['content-type'], 'image/jpeg')
668        self.assertEqual(len(self.browser.contents), PH_LEN)
669
670    def test_after_submit_default_browsable(self):
671        # After submitting an applicant form the default image is
672        # still visible
673        self.login()
674        self.browser.open(self.edit_path)
675        self.browser.getControl("Save").click() # submit form
676        # There is a correct <img> link included
677        self.assertTrue(
678            '<img src="passport.jpg" height="180px" />' in self.browser.contents)
679        # Browsing the link shows a real image
680        self.browser.open(self.image_url('passport.jpg'))
681        self.assertEqual(
682            self.browser.headers['content-type'], 'image/jpeg')
683        self.assertEqual(len(self.browser.contents), PH_LEN)
684
685    def test_uploaded_image_respects_file_size_restriction(self):
686        # When we upload an image that is too big ( > 10 KB) we will
687        # get an error message
688        self.login()
689        self.browser.open(self.edit_path)
690        # Create a pseudo image file and select it to be uploaded in form
691        photo_content = 'A' * 1024 * 21  # A string of 21 KB size
692        pseudo_image = StringIO(photo_content)
693        ctrl = self.browser.getControl(name='form.passport')
694        file_ctrl = ctrl.mech_control
695        file_ctrl.add_file(pseudo_image, filename='myphoto.jpg')
696        self.browser.getControl("Save").click() # submit form
697        # There is a correct <img> link included
698        self.assertTrue(
699            '<img src="passport.jpg" height="180px" />' in self.browser.contents)
700        # We get a warning message
701        self.assertTrue(
702            'Uploaded image is too big' in self.browser.contents)
703        # Browsing the image gives us the default image, not the
704        # uploaded one.
705        self.browser.open(self.image_url('passport.jpg'))
706        self.assertEqual(
707            self.browser.headers['content-type'], 'image/jpeg')
708        self.assertEqual(len(self.browser.contents), PH_LEN)
709        # There is really no file stored for the applicant
710        img = getUtility(IExtFileStore).getFile(
711            IFileStoreNameChooser(self.applicant).chooseName())
712        self.assertTrue(img is None)
713
714    def test_uploaded_image_browsable_w_errors(self):
715        # We can upload a different image and browse it after submit,
716        # even if there are still errors in the form
717        self.login()
718        self.browser.open(self.edit_path)
719        # Create a pseudo image file and select it to be uploaded in form
720        photo_content = 'I pretend to be a graphics file'
721        pseudo_image = StringIO(photo_content)
722        ctrl = self.browser.getControl(name='form.passport')
723        file_ctrl = ctrl.mech_control
724        file_ctrl.add_file(pseudo_image, filename='myphoto.jpg')
725        self.browser.getControl("Save").click() # submit form
726        # There is a correct <img> link included
727        self.assertTrue(
728            '<img src="passport.jpg" height="180px" />' in self.browser.contents)
729        # Browsing the link shows a real image
730        self.browser.open(self.image_url('passport.jpg'))
731        self.assertEqual(
732            self.browser.headers['content-type'], 'image/jpeg')
733        self.assertEqual(self.browser.contents, photo_content)
734
735    def test_uploaded_image_stored_in_imagestorage_w_errors(self):
736        # After uploading a new passport pic the file is correctly
737        # stored in an imagestorage
738        self.login()
739        self.browser.open(self.edit_path)
740        # Create a pseudo image file and select it to be uploaded in form
741        pseudo_image = StringIO('I pretend to be a graphics file')
742        ctrl = self.browser.getControl(name='form.passport')
743        file_ctrl = ctrl.mech_control
744        file_ctrl.add_file(pseudo_image, filename='myphoto.jpg')
745        self.browser.getControl("Save").click() # submit form
746        storage = getUtility(IExtFileStore)
747        file_id = IFileStoreNameChooser(self.applicant).chooseName()
748        pseudo_image.seek(0) # reset our file data source
749        self.assertEqual(
750            storage.getFile(file_id).read(), pseudo_image.read())
751        return
752
753    def test_uploaded_image_browsable_wo_errors(self):
754        # We can upload a different image and browse it after submit,
755        # if there are no errors in form
756        self.login()
757        self.browser.open(self.edit_path)
758        self.fill_correct_values() # fill other fields with correct values
759        # Create a pseudo image file and select it to be uploaded in form
760        pseudo_image = StringIO('I pretend to be a graphics file')
761        ctrl = self.browser.getControl(name='form.passport')
762        file_ctrl = ctrl.mech_control
763        file_ctrl.add_file(pseudo_image, filename='myphoto.jpg')
764        self.browser.getControl("Save").click() # submit form
765        # There is a correct <img> link included
766        self.assertTrue(
767            '<img src="passport.jpg" height="180px" />' in self.browser.contents)
768        # Browsing the link shows a real image
769        self.browser.open(self.image_url('passport.jpg'))
770        self.assertEqual(
771            self.browser.headers['content-type'], 'image/jpeg')
772        self.assertEqual(len(self.browser.contents), 31)
773
774    def test_uploaded_image_stored_in_imagestorage_wo_errors(self):
775        # After uploading a new passport pic the file is correctly
776        # stored in an imagestorage if form contains no errors
777        self.login()
778        self.browser.open(self.edit_path)
779        self.fill_correct_values() # fill other fields with correct values
780        # Create a pseudo image file and select it to be uploaded in form
781        pseudo_image = StringIO('I pretend to be a graphics file')
782        ctrl = self.browser.getControl(name='form.passport')
783        file_ctrl = ctrl.mech_control
784        file_ctrl.add_file(pseudo_image, filename='myphoto.jpg')
785        self.browser.getControl("Save").click() # submit form
786        storage = getUtility(IExtFileStore)
787        file_id = IFileStoreNameChooser(self.applicant).chooseName()
788        # The stored image can be fetched
789        fd = storage.getFile(file_id)
790        file_len = len(fd.read())
791        self.assertEqual(file_len, 31)
792        # When an applicant is removed, also the image is gone.
793        del self.app['applicants'][container_name_1][self.applicant.application_number]
794        fd = storage.getFile(file_id)
795        self.assertTrue(fd is None)
796
797    def test_uploaded_images_equal(self):
798        # Make sure uploaded images do really differ if we eject a
799        # change notfication (and do not if we don't)
800        self.login()
801        self.browser.open(self.edit_path)
802        self.fill_correct_values() # fill other fields with correct values
803        self.browser.getControl("Save").click() # submit form
804        # Now go on as an officer
805        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
806        self.browser.open(self.manage_path)
807
808        # Create a pseudo image file and select it to be uploaded in form
809        pseudo_image = StringIO('I pretend to be a graphics file')
810        ctrl = self.browser.getControl(name='form.passport')
811        file_ctrl = ctrl.mech_control
812        file_ctrl.add_file(pseudo_image, filename='myphoto.jpg')
813        file_id = IFileStoreNameChooser(self.applicant).chooseName()
814        setSite(self.app)
815        passport0 = getUtility(IExtFileStore).getFile(file_id)
816        self.browser.getControl("Save").click() # submit form with changed pic
817        passport1 = getUtility(IExtFileStore).getFile(file_id).read()
818        self.browser.getControl("Save").click() # submit form w/o changes
819        passport2 = getUtility(IExtFileStore).getFile(file_id).read()
820        self.assertTrue(passport0 is None)
821        self.assertTrue(passport0 != passport1)
822        self.assertTrue(passport1 == passport2)
823        return
824
825    def test_upload_image_by_manager_with_logging(self):
826        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
827        self.browser.open(self.manage_path)
828        # Create a pseudo image file and select it to be uploaded in form
829        photo_content = 'A' * 1024 * 5  # A string of 5 KB size
830        pseudo_image = StringIO(photo_content)
831        ctrl = self.browser.getControl(name='form.passport')
832        file_ctrl = ctrl.mech_control
833        file_ctrl.add_file(pseudo_image, filename='myphoto.jpg')
834        self.browser.getControl("Save").click() # submit form
835        # Even though the form could not be saved ...
836        self.assertTrue(
837            'Required input is missing' in self.browser.contents)
838        # ... the file has been successfully uploaded
839        logfile = os.path.join(
840            self.app['datacenter'].storage, 'logs', 'applicants.log')
841        logcontent = open(logfile).read()
842        self.assertTrue(
843            'zope.mgr - applicants.browser.ApplicantManageFormPage - '
844            '%s - saved: passport'
845            % (self.applicant.applicant_id)
846            in logcontent)
847
848    def test_application_slip_with_non_jpg_image(self):
849        IWorkflowState(self.applicant).setState('submitted')
850        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
851        self.browser.open(self.manage_path)
852        # Create a pseudo image file and select it to be uploaded in form
853        photo_content = 'A' * 1024 * 5  # A string of 5 KB size
854        pseudo_image = StringIO(photo_content)
855        ctrl = self.browser.getControl(name='form.passport')
856        file_ctrl = ctrl.mech_control
857        file_ctrl.add_file(pseudo_image, filename='myphoto.jpg')
858        self.browser.getControl("Save").click() # submit form
859        self.browser.open(self.manage_path)
860        self.browser.getLink("Download application slip").click()
861        self.assertEqual(self.browser.headers['Status'], '200 Ok')
862        self.assertMatches(
863            '...Your image file is corrupted. Please replace...',
864            self.browser.contents)
865
866    def test_pay_portal_application_fee(self):
867        self.login()
868        self.browser.open(self.edit_path)
869        # Payment tickets can't be created before the form has been validated
870        self.browser.getControl("Add online payment ticket").click()
871        self.assertTrue('Required input is missing' in self.browser.contents)
872        self.fill_correct_values()
873        # We have to save the form otherwise the filled fields will be cleared
874        # after adding an online payment, because adding an online payment
875        # requires a filled form but does not save it
876        self.browser.getControl("Save").click()
877        self.browser.getControl("Add online payment ticket").click()
878        # Session object missing
879        self.assertTrue(
880            'Session configuration object is not available'
881            in self.browser.contents)
882        configuration = SessionConfiguration()
883        configuration.academic_session = session_1
884        configuration.application_fee = 200.0
885        self.app['configuration'].addSessionConfiguration(configuration)
886        self.browser.open(self.edit_path)
887        self.browser.getControl("Add online payment ticket").click()
888        self.assertMatches('...Payment ticket created...',
889                           self.browser.contents)
890        self.assertMatches('...Activation Code...',
891                           self.browser.contents)
892        # Payment ticket can be removed if they haven't received a
893        # valid callback
894        self.browser.open(self.edit_path)
895        ctrl = self.browser.getControl(name='val_id')
896        value = ctrl.options[0]
897        ctrl.getControl(value=value).selected = True
898        self.browser.getControl("Remove selected", index=0).click()
899        self.assertMatches('...Successfully removed...', self.browser.contents)
900        # We will try the callback request view
901        self.browser.getControl("Add online payment ticket").click()
902        self.browser.open(self.edit_path)
903        ctrl = self.browser.getControl(name='val_id')
904        value = ctrl.options[0]
905        self.browser.getLink(value).click()
906        self.assertMatches('...Amount Authorized...',
907                           self.browser.contents)
908        payment_url = self.browser.url
909        payment_id = self.applicant.keys()[0]
910        payment = self.applicant[payment_id]
911        self.assertEqual(payment.p_item,'This is the %s container' % container_name_1)
912        self.assertEqual(payment.p_session, session_1)
913        self.assertEqual(payment.p_category,'application')
914        self.assertEqual(payment.amount_auth,200.0)
915        # Applicant is payer of the payment ticket.
916        self.assertEqual(
917            IPayer(payment).display_fullname, 'John Anthony Tester')
918        self.assertEqual(
919            IPayer(payment).id, self.applicant.applicant_id)
920        self.assertEqual(IPayer(payment).faculty, 'N/A')
921        self.assertEqual(IPayer(payment).department, 'N/A')
922        # The pdf payment slip can't yet be opened
923        #self.browser.open(payment_url + '/payment_receipt.pdf')
924        #self.assertMatches('...Ticket not yet paid...',
925        #                   self.browser.contents)
926        # Approve payment
927        # Applicants can't approve payments
928        self.assertRaises(
929            Unauthorized, self.browser.open, payment_url + '/approve')
930        # We approve the payment by bypassing the view
931        payment.approve()
932        # Applicant is is not yet in state 'paid' because it was only
933        # the payment which we set to paid
934        self.browser.open(self.view_path)
935        self.assertMatches('...started...',
936                           self.browser.contents)
937        self.assertTrue(self.applicant.state == 'started')
938        # Let's logout and approve the payment as manager
939        self.browser.getLink("Logout").click()
940        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
941        # First we reset the payment
942        payment.r_amount_approved = 0.0
943        payment.r_code = u''
944        payment.p_state = 'unpaid'
945        payment.r_desc = u''
946        payment.payment_date = None
947        self.browser.open(payment_url)
948        self.browser.getLink("Approve payment").click()
949        self.assertEqual(payment.p_state, 'paid')
950        self.assertEqual(payment.r_amount_approved, 200.0)
951        self.assertEqual(payment.r_code, 'AP')
952        self.assertTrue(self.applicant.state == 'paid')
953        # Approval is logged in students.log ...
954        logfile = os.path.join(
955            self.app['datacenter'].storage, 'logs', 'applicants.log')
956        logcontent = open(logfile).read()
957        self.assertTrue(
958            'zope.mgr - applicants.browser.OnlinePaymentApprovePage - '
959            '%s - approved' % self.applicant.applicant_id
960            in logcontent)
961        # ... and in payments.log
962        logfile = os.path.join(
963            self.app['datacenter'].storage, 'logs', 'payments.log')
964        logcontent = open(logfile).read()
965        self.assertTrue(
966            '"zope.mgr",%s,%s,application,200.0,AP,,,,,,\n'
967            % (self.applicant.applicant_id, payment.p_id)
968            in logcontent)
969        # Payment slips can't be downloaded ...
970        payment_id = self.applicant.keys()[0]
971        self.browser.open(self.view_path + '/' + payment_id)
972        self.browser.getLink("Download payment slip").click()
973        self.assertTrue(
974            'Please submit the application form before trying to download payment slips.'
975            in self.browser.contents)
976        # ... unless form is submitted.
977        self.browser.open(self.view_path + '/edit')
978        image = open(SAMPLE_IMAGE, 'rb')
979        ctrl = self.browser.getControl(name='form.passport')
980        file_ctrl = ctrl.mech_control
981        file_ctrl.add_file(image, filename='myphoto.jpg')
982        self.browser.getControl(name="confirm_passport").value = True
983        self.browser.getControl("Finally Submit").click()
984        self.browser.open(self.view_path + '/' + payment_id)
985        self.browser.getLink("Download payment slip").click()
986        self.assertEqual(self.browser.headers['Content-Type'],
987                 'application/pdf')
988        return
989
990    def test_pay_container_application_fee(self):
991        self.login()
992        self.browser.open(self.edit_path)
993        self.fill_correct_values()
994        self.browser.getControl("Save").click()
995        configuration = SessionConfiguration()
996        configuration.academic_session = session_1
997        self.applicantscontainer.application_fee = 120.0
998        configuration.application_fee = 9999.9
999        self.app['configuration'].addSessionConfiguration(configuration)
1000        self.browser.open(self.edit_path)
1001        self.browser.getControl("Add online payment ticket").click()
1002        self.assertMatches('...Payment ticket created...',
1003                           self.browser.contents)
1004        self.assertMatches('...Payment ticket created...',
1005                           self.browser.contents)
1006        self.assertFalse(
1007            '<span>9999.9</span>' in self.browser.contents)
1008        self.assertTrue(
1009            '<span>120.0</span>' in self.browser.contents)
1010        self.assertTrue(
1011            '<span>Application Fee</span>' in self.browser.contents)
1012        return
1013
1014    def prepare_special_container(self):
1015        # Add special application container
1016        container_name = u'special%s' % session_1
1017        applicantscontainer = ApplicantsContainer()
1018        applicantscontainer.code = container_name
1019        applicantscontainer.prefix = 'special'
1020        applicantscontainer.year = session_1
1021        applicantscontainer.title = u'This is a special app container'
1022        applicantscontainer.application_category = 'no'
1023        applicantscontainer.mode = 'create'
1024        applicantscontainer.strict_deadline = True
1025        delta = timedelta(days=10)
1026        applicantscontainer.startdate = datetime.now(pytz.utc) - delta
1027        applicantscontainer.enddate = datetime.now(pytz.utc) + delta
1028        self.app['applicants'][container_name] = applicantscontainer
1029        # Add an applicant
1030        applicant = createObject('waeup.Applicant')
1031        # reg_number is the only field which has to be preset here
1032        # because managers are allowed to edit this required field
1033        applicant.reg_number = u'12345'
1034        self.special_applicant = applicant
1035        self.app['applicants'][container_name].addApplicant(applicant)
1036        IUserAccount(
1037            self.app['applicants'][container_name][
1038            applicant.application_number]).setPassword('apwd')
1039        # Add session configuration object
1040        self.configuration = SessionConfiguration()
1041        self.configuration.academic_session = session_1
1042        #self.configuration.transcript_fee = 200.0
1043        self.configuration.clearance_fee = 300.0
1044        self.app['configuration'].addSessionConfiguration(self.configuration)
1045
1046
1047    def test_pay_special_fee(self):
1048        self.prepare_special_container()
1049        # Login
1050        self.browser.open(self.login_path)
1051        self.browser.getControl(
1052            name="form.login").value = self.special_applicant.applicant_id
1053        self.browser.getControl(name="form.password").value = 'apwd'
1054        self.browser.getControl("Login").click()
1055        applicant_path = self.browser.url
1056        self.browser.getLink("Edit application record").click()
1057        self.browser.getControl(name="form.firstname").value = 'John'
1058        self.browser.getControl(name="form.middlename").value = 'Anthony'
1059        self.browser.getControl(name="form.lastname").value = 'Tester'
1060        self.browser.getControl(name="form.special_application").value = [
1061            'transcript']
1062        self.browser.getControl(name="form.date_of_birth").value = '09/09/1988'
1063        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
1064        self.configuration.transcript_fee = 0.0
1065        self.browser.getControl("Save").click()
1066        self.browser.getControl("Add online payment ticket").click()
1067        self.assertMatches('...Amount could not be determined...',
1068                           self.browser.contents)
1069        self.configuration.transcript_fee = 200.0
1070        self.browser.getLink("Edit application record").click()
1071        self.browser.getControl("Add online payment ticket").click()
1072        self.assertMatches('...Payment ticket created...',
1073                           self.browser.contents)
1074        self.assertTrue(
1075            '<span>Transcript Fee</span>' in self.browser.contents)
1076        self.assertTrue(
1077            'This is a special app container' in self.browser.contents)
1078        self.assertTrue(
1079            '<span>200.0</span>' in self.browser.contents)
1080        self.assertEqual(len(self.special_applicant.keys()), 1)
1081        # The applicant's workflow state is paid ...
1082        self.special_applicant.values()[0].approveApplicantPayment()
1083        self.assertEqual(self.special_applicant.state, 'paid')
1084        self.browser.open(applicant_path + '/edit')
1085        # ... but he can create further tickets.
1086        self.browser.getControl(name="form.special_application").value = [
1087            'clearance']
1088        self.browser.getControl("Save").click()
1089        self.browser.getControl("Add online payment ticket").click()
1090        self.assertMatches('...Payment ticket created...',
1091                           self.browser.contents)
1092        self.browser.open(applicant_path)
1093        self.assertTrue(
1094            '<td>Acceptance Fee</td>' in self.browser.contents)
1095        self.assertEqual(len(self.special_applicant.keys()), 2)
1096        # Second payment can also be approved wthout error message
1097        flashtype, msg, log = self.special_applicant.values()[1].approveApplicantPayment()
1098        self.assertEqual(flashtype, 'success')
1099        self.assertEqual(msg, 'Payment approved')
1100        # Payment slips can't be downloaded ...
1101        payment_id = self.special_applicant.keys()[0]
1102        self.browser.open(applicant_path + '/' + payment_id)
1103        self.browser.getLink("Download payment slip").click()
1104        self.assertTrue(
1105            'Please submit the application form before trying to download payment slips.'
1106            in self.browser.contents)
1107        # ... unless form is submitted.
1108        self.browser.open(applicant_path + '/edit')
1109        image = open(SAMPLE_IMAGE, 'rb')
1110        ctrl = self.browser.getControl(name='form.passport')
1111        file_ctrl = ctrl.mech_control
1112        file_ctrl.add_file(image, filename='myphoto.jpg')
1113        self.browser.getControl(name="confirm_passport").value = True
1114        self.browser.getControl("Finally Submit").click()
1115        self.browser.open(applicant_path + '/' + payment_id)
1116        self.browser.getLink("Download payment slip").click()
1117        self.assertEqual(self.browser.headers['Content-Type'],
1118                 'application/pdf')
1119        return
1120
1121    def test_final_submit(self):
1122        # Make sure that a correctly filled form with passport picture
1123        # can be submitted (only) after payment
1124        self.login()
1125        self.browser.getLink("Edit application record").click()
1126        self.assertFalse('Finally Submit' in self.browser.contents)
1127        IWorkflowInfo(self.applicant).fireTransition('pay')
1128        self.browser.open(self.edit_path)
1129        self.assertTrue('Finally Submit' in self.browser.contents)
1130        self.fill_correct_values() # fill other fields with correct values
1131        self.browser.getControl("Save").click()
1132        self.browser.getControl("Finally Submit").click()
1133        # We forgot to upload a passport picture
1134        self.assertTrue(
1135            'No passport picture uploaded' in self.browser.contents)
1136        # Use a real image file and select it to be uploaded in form
1137        image = open(SAMPLE_IMAGE, 'rb')
1138        ctrl = self.browser.getControl(name='form.passport')
1139        file_ctrl = ctrl.mech_control
1140        file_ctrl.add_file(image, filename='myphoto.jpg')
1141        self.browser.getControl("Finally Submit").click() # (finally) submit form
1142        # The picture has been uploaded but the form cannot be submitted
1143        # since the passport confirmation box was not ticked
1144        self.assertTrue(
1145            'Passport picture confirmation box not ticked'
1146            in self.browser.contents)
1147        self.browser.getControl(name="confirm_passport").value = True
1148        # If application period has expired and strict-deadline is set
1149        # applicants do notsee edit button and can't open
1150        # the edit form.
1151        self.applicantscontainer.enddate = datetime.now(pytz.utc)
1152        self.browser.open(self.view_path)
1153        self.assertFalse(
1154            'Edit application record' in self.browser.contents)
1155        self.browser.open(self.edit_path)
1156        self.assertTrue(
1157            'form is locked' in self.browser.contents)
1158        # We can either postpone the enddate ...
1159        self.applicantscontainer.enddate = datetime.now(
1160            pytz.utc) + timedelta(days=10)
1161        self.browser.open(self.edit_path)
1162        self.browser.getControl(name="confirm_passport").value = True
1163        self.browser.getControl("Finally Submit").click()
1164        self.assertTrue(
1165            'Application submitted' in self.browser.contents)
1166        # ... or allow submission after deadline.
1167        IWorkflowState(self.applicant).setState('paid')
1168        self.applicant.locked = False
1169        self.applicantscontainer.strict_deadline = False
1170        self.browser.open(self.edit_path)
1171        self.browser.getControl(name="confirm_passport").value = True
1172        self.browser.getControl("Finally Submit").click()
1173        self.assertTrue(
1174            'Application submitted' in self.browser.contents)
1175        self.browser.goBack(count=1)
1176        self.browser.getControl("Save").click()
1177        # The form is locked.
1178        self.assertTrue(self.applicant.locked)
1179        self.assertTrue(
1180            'The requested form is locked' in self.browser.contents)
1181        self.browser.goBack(count=1)
1182        self.browser.getControl("Finally Submit").click()
1183        self.assertTrue(
1184            'The requested form is locked' in self.browser.contents)
1185        return
1186
1187    def test_locking(self):
1188        # Make sure that locked forms can't be submitted
1189        self.login()
1190        self.browser.open(self.edit_path)
1191        self.fill_correct_values() # fill other fields with correct values
1192        # Create a pseudo image file and select it to be uploaded in form
1193        pseudo_image = StringIO('I pretend to be a graphics file')
1194        ctrl = self.browser.getControl(name='form.passport')
1195        file_ctrl = ctrl.mech_control
1196        file_ctrl.add_file(pseudo_image, filename='myphoto.jpg')
1197        self.browser.getControl("Save").click()
1198        # Now we lock the form
1199        self.applicant.locked = True
1200        self.browser.open(self.edit_path)
1201        self.assertEqual(self.browser.headers['Status'], '200 Ok')
1202        self.assertTrue(
1203            'The requested form is locked' in self.browser.contents)
1204        return
1205
1206    def test_certificate_removed(self):
1207        self.login()
1208        self.browser.open(self.edit_path)
1209        self.fill_correct_values()
1210        self.browser.getControl("Save").click()
1211        self.browser.open(self.view_path)
1212        self.assertTrue(
1213            'Unnamed Certificate' in self.browser.contents)
1214        self.browser.open(self.edit_path)
1215        self.assertTrue(
1216            '<option selected="selected" value="CERT1">' in self.browser.contents)
1217        # Now we remove the certificate
1218        del self.app['faculties']['fac1']['dep1'].certificates['CERT1']
1219        # The certificate is still shown in display mode
1220        self.browser.open(self.view_path)
1221        self.assertTrue(
1222            'Unnamed Certificate' in self.browser.contents)
1223        # The certificate is still selectable in edit mode so that it won't
1224        # be automatically replaced by another (arbitrary) certificate
1225        self.browser.open(self.edit_path)
1226        self.assertTrue(
1227            '<option selected="selected" value="CERT1">' in self.browser.contents)
1228        # Consequently, the certificate is still shown after saving the form
1229        self.browser.getControl("Save").click()
1230        self.browser.open(self.view_path)
1231        self.assertTrue(
1232            'Unnamed Certificate' in self.browser.contents)
1233        # Even if we add a new certificate the previous (removed)
1234        # certificate is shown
1235        certificate = createObject('waeup.Certificate')
1236        certificate.code = 'CERT2'
1237        certificate.title = 'New Certificate'
1238        certificate.application_category = 'basic'
1239        self.app['faculties']['fac1']['dep1'].certificates.addCertificate(
1240            certificate)
1241        self.browser.open(self.edit_path)
1242        self.assertTrue(
1243            '<option selected="selected" value="CERT1">'
1244            in self.browser.contents)
1245
1246class ApplicantRegisterTests(ApplicantsFullSetup):
1247    # Tests for applicant registration
1248
1249    layer = FunctionalLayer
1250
1251    def test_register_applicant_create(self):
1252        self.assertEqual(len(self.app['applicants'][container_name_1]), 1)
1253        # An applicant can register himself.
1254        self.browser.open(self.container_path)
1255        self.browser.getLink("Register for application").click()
1256        # Fill the edit form with suitable values
1257        self.browser.getControl(name="form.firstname").value = 'Anna'
1258        self.browser.getControl(name="form.lastname").value = 'Kurios'
1259        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
1260        self.browser.getControl(name="form.phone.country").value = ['+234']
1261        self.browser.getControl(name="form.phone.area").value = '555'
1262        self.browser.getControl(name="form.phone.ext").value = '6666666'
1263        self.browser.getControl("Send login credentials").click()
1264        self.assertEqual(self.browser.url,
1265            self.container_path + '/registration_complete?email=xx%40yy.zz')
1266        # A new applicant has been created
1267        self.assertEqual(len(self.app['applicants'][container_name_1]), 2)
1268        # The new applicant can be found in the catalog via the email address
1269        cat = getUtility(ICatalog, name='applicants_catalog')
1270        results = list(
1271            cat.searchResults(email=('xx@yy.zz', 'xx@yy.zz')))
1272        applicant = results[0]
1273        self.assertEqual(applicant.lastname,'Kurios')
1274        # The application_id has been copied to the reg_number
1275        self.assertEqual(applicant.applicant_id, applicant.reg_number)
1276        # The applicant can be found in the catalog via the reg_number
1277        results = list(
1278            cat.searchResults(
1279            reg_number=(applicant.reg_number, applicant.reg_number)))
1280        self.assertEqual(applicant,results[0])
1281        return
1282
1283    def test_register_applicant_take_unused_record(self):
1284        # Create an unused record
1285        uu_applicant = createObject('waeup.Applicant')
1286        self.app['applicants'][container_name_1].addApplicant(uu_applicant)
1287        self.assertEqual(uu_applicant.container_code, container_name_1 + '-')
1288        self.assertEqual(len(self.app['applicants'][container_name_1]), 2)
1289        self.browser.open(self.container_path)
1290        self.browser.getLink("Register for application").click()
1291        # Fill the edit form with suitable values
1292        self.browser.getControl(name="form.firstname").value = 'Anna'
1293        self.browser.getControl(name="form.lastname").value = 'Kurios'
1294        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
1295        self.browser.getControl(name="form.phone.country").value = ['+234']
1296        self.browser.getControl(name="form.phone.area").value = '555'
1297        self.browser.getControl(name="form.phone.ext").value = '6666666'
1298        self.browser.getControl("Send login credentials").click()
1299        # No applicant has been created ...
1300        self.assertEqual(len(self.app['applicants'][container_name_1]), 2)
1301        # ... and the existing, formerly unused record has been used instead
1302        self.assertEqual(uu_applicant.lastname, 'Kurios')
1303        self.assertEqual(uu_applicant.container_code, container_name_1 + '+')
1304        return
1305
1306    def test_register_applicant_update(self):
1307        # We change the application mode and check if applicants
1308        # can find and update imported records instead of creating new records.
1309        # First we check what happens if record does not exist.
1310        self.applicantscontainer.mode = 'update'
1311        self.browser.open(self.container_path + '/register')
1312        self.browser.getControl(name="form.lastname").value = 'Better'
1313        self.browser.getControl(name="form.reg_number").value = 'anynumber'
1314        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
1315        self.browser.getControl("Send login credentials").click()
1316        self.assertTrue('No application record found.'
1317            in self.browser.contents)
1318        # Even with the correct reg_number we can't register
1319        # because lastname attribute is not set.
1320        self.applicantscontainer.mode = 'update'
1321        self.browser.open(self.container_path + '/register')
1322        self.browser.getControl(name="form.lastname").value = 'Better'
1323        self.browser.getControl(name="form.reg_number").value = '1234'
1324        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
1325        self.browser.getControl("Send login credentials").click()
1326        self.assertTrue('An error occurred.' in self.browser.contents)
1327        # Let's set this attribute manually
1328        # and try to register with a wrong name.
1329        self.applicant.lastname = u'Better'
1330        self.browser.open(self.container_path + '/register')
1331        self.browser.getControl(name="form.lastname").value = 'Worse'
1332        self.browser.getControl(name="form.reg_number").value = '1234'
1333        self.browser.getControl(name="form.email").value = 'xx@yy.zz'
1334        self.browser.getControl("Send login credentials").click()
1335        # Anonymous is not informed that lastname verification failed.
1336        # It seems that the record doesn't exist.
1337        self.assertTrue('No application record found.'
1338            in self.browser.contents)
1339        # Even with the correct lastname we can't register if a
1340        # password has been set and used.
1341        IWorkflowState(self.applicant).setState('started')
1342        self.browser.getControl(name="form.lastname").value = 'Better'
1343        self.browser.getControl(name="form.reg_number").value = '1234'
1344        self.browser.getControl("Send login credentials").click()
1345        self.assertTrue('Your password has already been set and used.'
1346            in self.browser.contents)
1347        #IUserAccount(
1348        #    self.app['applicants'][container_name_1][
1349        #    self.applicant.application_number]).context.password = None
1350        # Even without unsetting the password we can re-register if state
1351        # is 'initialized'
1352        IWorkflowState(self.applicant).setState('initialized')
1353        self.browser.open(self.container_path + '/register')
1354        # The lastname field, used for verification, is not case-sensitive.
1355        self.browser.getControl(name="form.lastname").value = 'bEtter'
1356        self.browser.getControl(name="form.reg_number").value = '1234'
1357        self.browser.getControl(name="form.email").value = 'new@yy.zz'
1358        self.browser.getControl("Send login credentials").click()
1359        # Yeah, we succeded ...
1360        self.assertTrue('Your registration was successful.'
1361            in self.browser.contents)
1362        # ... and  applicant can be found in the catalog via the email address
1363        cat = getUtility(ICatalog, name='applicants_catalog')
1364        results = list(
1365            cat.searchResults(
1366            email=('new@yy.zz', 'new@yy.zz')))
1367        self.assertEqual(self.applicant,results[0])
1368        return
1369
1370    def test_change_password_request(self):
1371        self.browser.open('http://localhost/app/changepw')
1372        self.browser.getControl(name="form.identifier").value = '1234'
1373        self.browser.getControl(name="form.email").value = 'aa@aa.ng'
1374        self.browser.getControl("Send login credentials").click()
1375        self.assertTrue('No record found' in self.browser.contents)
1376        self.applicant.email = 'aa@aa.ng'
1377        # Update the catalog
1378        notify(grok.ObjectModifiedEvent(self.applicant))
1379        self.browser.open('http://localhost/app/changepw')
1380        self.browser.getControl(name="form.identifier").value = '1234'
1381        self.browser.getControl(name="form.email").value = 'aa@aa.ng'
1382        self.browser.getControl("Send login credentials").click()
1383        self.assertTrue(
1384            'An email with your user name and password has been sent'
1385            in self.browser.contents)
1386
1387    def test_check_status(self):
1388        self.applicant.lastname = u'Lion '
1389        self.browser.open('http://localhost/app/applicants/checkstatus')
1390        self.browser.getControl(name="applicant_id").value = 'nonsense'
1391        self.browser.getControl(name="lastname").value = 'Lion'
1392        self.browser.getControl("Submit").click()
1393        self.assertTrue('No application record found' in self.browser.contents)
1394        self.browser.getControl(name="applicant_id").value = self.applicant.applicant_id
1395        self.browser.getControl(name="lastname").value = 'nonsense'
1396        self.browser.getControl("Submit").click()
1397        self.assertTrue('No application record found' in self.browser.contents)
1398        self.browser.getControl(name="applicant_id").value = self.applicant.applicant_id
1399        self.browser.getControl(name="lastname").value = 'Lion'
1400        self.browser.getControl("Submit").click()
1401        self.assertTrue('Application status of' in self.browser.contents)
1402        self.assertTrue('You have not yet submitted your application' in self.browser.contents)
1403        IWorkflowState(self.applicant).setState('admitted')
1404        self.browser.open('http://localhost/app/applicants/checkstatus')
1405        self.browser.getControl(name="applicant_id").value = self.applicant.applicant_id
1406        # whitespaces are ignored
1407        self.browser.getControl(name="lastname").value = 'Lion'
1408        self.browser.getControl("Submit").click()
1409        self.assertTrue('Congratulations!' in self.browser.contents)
1410        self.assertFalse('Study Course' in self.browser.contents)
1411        self.applicant.course_admitted = self.certificate
1412        self.browser.open('http://localhost/app/applicants/checkstatus')
1413        self.browser.getControl(name="applicant_id").value = self.applicant.applicant_id
1414        self.browser.getControl(name="lastname").value = 'Lion'
1415        self.browser.getControl("Submit").click()
1416        self.assertTrue('Congratulations!' in self.browser.contents)
1417        self.assertTrue('Unnamed Certificate (CERT1)' in self.browser.contents)
1418        self.assertTrue('Department of Unnamed Department (dep1)' in self.browser.contents)
1419        self.assertTrue('Faculty of Unnamed Faculty (NA)' in self.browser.contents)
1420
1421class ApplicantsExportTests(ApplicantsFullSetup, FunctionalAsyncTestCase):
1422    # Tests for StudentsContainer class views and pages
1423
1424    layer = FunctionalLayer
1425
1426    def wait_for_export_job_completed(self):
1427        # helper function waiting until the current export job is completed
1428        manager = getUtility(IJobManager)
1429        job_id = self.app['datacenter'].running_exports[0][0]
1430        job = manager.get(job_id)
1431        wait_for_result(job)
1432        return job_id
1433
1434    def test_applicants_in_container_export(self):
1435        self.browser.addHeader('Authorization', 'Basic mgr:mgrpw')
1436        container_path = 'http://localhost/app/applicants/%s' % container_name_1
1437        self.browser.open(container_path)
1438        self.browser.getLink("Export applicants").click()
1439        self.browser.getControl("Start new export").click()
1440
1441        # When the job is finished and we reload the page...
1442        job_id = self.wait_for_export_job_completed()
1443        self.browser.open(container_path + '/exports')
1444        # ... the csv file can be downloaded ...
1445        self.browser.getLink("Download").click()
1446        self.assertEqual(self.browser.headers['content-type'],
1447            'text/csv; charset=UTF-8')
1448        self.assertTrue(
1449            'filename="WAeUP.Kofa_applicants_%s.csv' % job_id in
1450            self.browser.headers['content-disposition'])
1451        self.assertEqual(len(self.app['datacenter'].running_exports), 1)
1452        job_id = self.app['datacenter'].running_exports[0][0]
1453        # ... and discarded
1454        self.browser.open(container_path + '/exports')
1455        self.browser.getControl("Discard").click()
1456        self.assertEqual(len(self.app['datacenter'].running_exports), 0)
1457        # Creation, downloading and discarding is logged
1458        logfile = os.path.join(
1459            self.app['datacenter'].storage, 'logs', 'datacenter.log')
1460        logcontent = open(logfile).read()
1461        self.assertTrue(
1462            'zope.mgr - applicants.browser.ExportJobContainerJobStart - '
1463            'exported: applicants (%s), job_id=%s'
1464            % (container_name_1, job_id) in logcontent
1465            )
1466        self.assertTrue(
1467            'zope.mgr - applicants.browser.ExportJobContainerDownload '
1468            '- downloaded: WAeUP.Kofa_applicants_%s.csv, job_id=%s'
1469            % (job_id, job_id) in logcontent
1470            )
1471        self.assertTrue(
1472            'zope.mgr - applicants.browser.ExportJobContainerOverview '
1473            '- discarded: job_id=%s' % job_id in logcontent
1474            )
Note: See TracBrowser for help on using the repository browser.