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

Last change on this file since 11614 was 11601, checked in by Henrik Bettermann, 10 years ago

Fix tests.

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