source: main/waeup.sirp/trunk/src/waeup/sirp/applicants/tests/test_authentication.py @ 5817

Last change on this file since 5817 was 5817, checked in by uli, 14 years ago

Remove JAMB-related tests and unused imports.

File size: 10.0 KB
Line 
1##
2## test_authentication.py
3## Login : <uli@pu.smp.net>
4## Started on  Fri Aug 20 08:18:58 2010 Uli Fouquet
5## $Id$
6##
7## Copyright (C) 2010 Uli Fouquet
8## This program is free software; you can redistribute it and/or modify
9## it under the terms of the GNU General Public License as published by
10## the Free Software Foundation; either version 2 of the License, or
11## (at your option) any later version.
12##
13## This program is distributed in the hope that it will be useful,
14## but WITHOUT ANY WARRANTY; without even the implied warranty of
15## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16## GNU General Public License for more details.
17##
18## You should have received a copy of the GNU General Public License
19## along with this program; if not, write to the Free Software
20## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21##
22import grok
23import unittest
24from zope.component import provideAdapter
25from zope.component.hooks import setSite, clearSite
26from zope.interface import verify
27from zope.pluggableauth.interfaces import  IAuthenticatedPrincipalFactory
28from zope.publisher.browser import TestRequest
29from zope.publisher.interfaces import IRequest
30from zope.session.interfaces import ISession
31from zope.site import LocalSiteManager
32from zope.testing import cleanup
33from waeup.sirp.applicants.authentication import (
34    ApplicantsAuthenticatorPlugin, WAeUPApplicantCredentialsPlugin,
35    ApplicantCredentials, AuthenticatedApplicantPrincipalFactory,
36    ApplicantPrincipalInfo, ApplicantPrincipal)
37
38class FakeBatch(dict):
39    def getAccessCode(self, id):
40        return self.get(id)
41
42class FakeAccessCode(object):
43    def __init__(self, repr, inv_date=None):
44        self.invalidation_date = inv_date
45        self.representation = repr
46
47class FakeInvAccessCode(object):
48    invalidation_date = True
49
50class FakeApplication(object):
51    def __init__(self, ac=None):
52        self.access_code = ac
53
54class FakeSite(grok.Application, grok.Container):
55    def __init__(self):
56        super(FakeSite, self).__init__()
57        self['applicants'] = {
58            'APP': {
59                'APP-12345': FakeApplication('APP-12345'),
60                'APP-54321': FakeApplication('APP-54321'),
61                'APP-22222': FakeApplication('APP-OTHER'),
62                'APP-44444': FakeApplication(),
63                'APP-55555': FakeApplication('APP-OTHER'),
64                },
65            'JAMB': {
66                'JAMB1': FakeApplication(),
67                'JAMB2': FakeApplication('APP-12345'),
68                'JAMB3': FakeApplication('APP-54321'),
69                'JAMB4': FakeApplication('APP-44444'),
70                },
71            }
72        self['accesscodes'] = {
73            'APP': FakeBatch({
74                    'APP-12345': FakeAccessCode('APP-12345'),
75                    'APP-54321': FakeAccessCode('APP-54321', True),
76                    'APP-11111': FakeAccessCode('APP-11111'),
77                    'APP-22222': FakeAccessCode('APP-22222'),
78                    'APP-33333': FakeAccessCode('APP-33333', True),
79                    'APP-44444': FakeAccessCode('APP-44444', True),
80                    'APP-55555': FakeAccessCode('APP-55555', True),
81                    })
82            }
83
84class AuthenticatorPluginTest(unittest.TestCase):
85
86    def setUp(self):
87        self.app = FakeSite()
88        self.app.setSiteManager(LocalSiteManager(self.app))
89        self.plugin = ApplicantsAuthenticatorPlugin()
90        setSite(self.app)
91        return
92
93    def tearDown(self):
94        clearSite()
95        return
96
97    def test_invalid_credentials(self):
98        result = self.plugin.authenticateCredentials('not-a-dict')
99        assert result is None
100
101        result = self.plugin.authenticateCredentials(
102            dict(accesscode=None, foo='blah'))
103        assert result is None
104
105        result = self.plugin.authenticateCredentials(
106            dict(accesscode='Nonsense',))
107        assert result is None
108
109        # Possible cases, where formal correct authentication
110        # data is not valid:
111        result = self.plugin.authenticateCredentials(
112            dict(accesscode='APP-22222'))
113        assert result is None
114
115        result = self.plugin.authenticateCredentials(
116            dict(accesscode='APP-33333'))
117        assert result is None
118
119        result = self.plugin.authenticateCredentials(
120            dict(accesscode='APP-44444'))
121        assert result is None
122       
123        result = self.plugin.authenticateCredentials(
124            dict(accesscode='APP-55555'))
125        assert result is None
126        return
127
128    def test_valid_credentials(self):
129        """The six different cases where we allow login.
130
131        All other combinations should be forbidden.
132        """
133        result = self.plugin.authenticateCredentials(
134            dict(accesscode='APP-11111'))
135        assert result is not None
136
137        result = self.plugin.authenticateCredentials(
138            dict(accesscode='APP-12345'))
139        assert result is not None
140
141        result = self.plugin.authenticateCredentials(
142            dict(accesscode='APP-54321'))
143        assert result is not None
144
145        # check the `principalInfo` method of authenticator
146        # plugin. This is only here to satisfy the coverage report.
147        assert self.plugin.principalInfo('not-an-id') is None
148        return
149
150session_data = {
151    'zope.pluggableauth.browserplugins': {}
152    }
153
154class FakeSession(dict):
155    def __init__(self, request):
156        pass
157
158    def get(self, key, default=None):
159        return self.__getitem__(key, default)
160   
161    def __getitem__(self, key, default=None):
162        return session_data.get(key, default)
163
164    def __setitem__(self, key, value):
165        session_data[key] = value
166        return
167
168class CredentialsPluginTest(unittest.TestCase):
169
170    def setUp(self):
171        self.request = TestRequest()
172        provideAdapter(FakeSession, (IRequest,), ISession)
173        self.plugin = WAeUPApplicantCredentialsPlugin()
174        self.full_request = TestRequest()
175        session_data['zope.pluggableauth.browserplugins'] = {}
176        return
177
178    def tearDown(self):
179        cleanup.tearDown()
180        return
181
182    def filled_request(self, form_dict):
183        request = TestRequest()
184        for key, value in form_dict.items():
185            request.form[key] = value
186        return request
187
188    def test_extractCredentials_invalid(self):
189        result = self.plugin.extractCredentials('not-a-request')
190        assert result is None
191        return
192
193    def test_extractCredentials_empty(self):
194        result = self.plugin.extractCredentials(self.request)
195        assert result is None
196        return
197
198    def test_extractCredentials_full_set(self):
199        request = self.filled_request({
200                'form.prefix': 'APP',
201                'form.ac_series': '1',
202                'form.ac_number': '1234567890',
203                #'form.jamb_reg_no': 'JAMB_NUMBER',
204                })
205        result = self.plugin.extractCredentials(request)
206        self.assertEqual(result, {'accesscode': 'APP-1-1234567890'})
207        return
208
209    def test_extractCredentials_accesscode_only(self):
210        request = self.filled_request({
211                'form.prefix': 'APP',
212                'form.ac_series': '1',
213                'form.ac_number': '1234567890',
214                })
215        result = self.plugin.extractCredentials(request)
216        self.assertEqual(result, {'accesscode': 'APP-1-1234567890'})
217        return
218
219    def test_extractCredentials_from_empty_session(self):
220        session_data['zope.pluggableauth.browserplugins']['credentials'] = None
221        result = self.plugin.extractCredentials(self.request)
222        assert result is None
223        return
224
225    def test_extractCredentials_from_nonempty_session(self):
226        credentials = ApplicantCredentials('APP-1-12345')
227        session_data['zope.pluggableauth.browserplugins'][
228            'credentials'] = credentials
229        result = self.plugin.extractCredentials(self.request)
230        self.assertEqual(result, {'accesscode': 'APP-1-12345'})
231        return
232
233
234class ApplicantCredentialsTest(unittest.TestCase):
235
236    def setUp(self):
237        self.credentials = ApplicantCredentials('SOME_ACCESSCODE')
238        return
239
240    def tearDown(self):
241        return
242
243    def test_methods(self):
244        self.assertEqual(self.credentials.getAccessCode(), 'SOME_ACCESSCODE')
245        assert self.credentials.getLogin() is None
246        assert self.credentials.getPassword() is None
247        return
248
249class FakePluggableAuth(object):
250    prefix = 'foo'
251
252class PrincipalFactoryTest(unittest.TestCase):
253
254    def setUp(self):
255        self.info = ApplicantPrincipalInfo('APP-1-1234567890')
256        return
257
258    def tearDown(self):
259        pass
260
261    def test_principalFactory_interface(self):
262        verify.verifyClass(IAuthenticatedPrincipalFactory,
263                           AuthenticatedApplicantPrincipalFactory
264                           )
265        return
266
267    def test_principalFactory_create(self):
268        factory = AuthenticatedApplicantPrincipalFactory(self.info, None)
269
270        assert factory.info is self.info
271        assert factory.request is None
272        return
273
274    def test_principalFactory_call_w_prefix(self):
275        factory = AuthenticatedApplicantPrincipalFactory(self.info, None)
276        principal = factory(FakePluggableAuth())
277
278        assert isinstance(principal, ApplicantPrincipal)
279        self.assertEqual(principal.__repr__(),
280                         "ApplicantPrincipal('foo.APP-1-1234567890')")
281        self.assertEqual(principal.id, 'foo.APP-1-1234567890')
282        return
283
284    def test_principalFactory_call_wo_prefix(self):
285        factory = AuthenticatedApplicantPrincipalFactory(self.info, None)
286        fake_auth = FakePluggableAuth()
287        fake_auth.prefix = None
288        principal = factory(fake_auth)
289        self.assertEqual(principal.id, 'APP-1-1234567890')
290        return
291       
292def test_suite():
293    suite = unittest.TestSuite()
294    for testcase in [
295        AuthenticatorPluginTest, CredentialsPluginTest,
296        ApplicantCredentialsTest, PrincipalFactoryTest,
297        ]:
298        suite.addTest(unittest.TestLoader().loadTestsFromTestCase(
299                testcase
300                )
301        )
302    return suite
Note: See TracBrowser for help on using the repository browser.