source: main/waeup.cas/trunk/waeup/cas/tests/test_authenticators.py @ 10526

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

Call core_user_get_users first and bring order into tests.

File size: 15.4 KB
Line 
13# Tests for waeup.cas.authentictors
2import os
3import threading
4import unittest
5from paste.deploy import loadapp
6try:
7    from SimpleXMLRPCServer import SimpleXMLRPCServer  # Python 2.x
8except ImportError:
9    from xmlrpc.server import SimpleXMLRPCServer       # Python 3.x
10try:
11    import xmlrpclib                     # Python 2.x
12except ImportError:
13    import xmlrpc.client as xmlrpclib    # Python 3.x
14from waeup.cas.authenticators import (
15    get_all_authenticators, get_authenticator, filter_auth_opts,
16    Authenticator, DummyAuthenticator, KofaAuthenticator,
17    KofaMoodleAuthenticator
18    )
19from waeup.cas.server import CASServer
20
21
22class TestHelpers(unittest.TestCase):
23
24    def test_get_all_authenticators(self):
25        # we can get authenticators via entry points
26        auths = get_all_authenticators()
27        assert 'dummy' in auths
28        assert auths['dummy'] is DummyAuthenticator
29
30    def test_filter_auth_opts(self):
31        # we can filter auth opts
32        result = filter_auth_opts(
33            dict(auth='foo', auth_bar='baz', auth_baz='blah')
34            )
35        assert result == (
36            {'auth': 'foo'},
37            {'auth_bar': 'baz', 'auth_baz': 'blah'}
38            )
39
40    def test_get_authenticator(self):
41        # we can parse a paste.deploy config dict for auth
42        result = get_authenticator({})
43        assert result == {}
44        result = get_authenticator({'auth': 'dummy'})
45        assert isinstance(result['auth'], DummyAuthenticator)
46
47
48class AuthenticatorTests(unittest.TestCase):
49
50    def test_create(self):
51        # we can create Authenticator instances
52        auth = Authenticator()
53        assert isinstance(auth, Authenticator)
54
55
56class DummyAuthenticatorTests(unittest.TestCase):
57
58    def test_create(self):
59        # we can create DummyAuthenticator instances
60        auth = DummyAuthenticator()
61        assert isinstance(auth, DummyAuthenticator)
62
63    def test_check_credentials(self):
64        # we can succeed with 'bird'/'bebop'. Others will fail.
65        auth = DummyAuthenticator()
66        result1 = auth.check_credentials('bird', 'bebop')
67        assert result1 == (True, '')
68        result2 = auth.check_credentials('foo', 'bar')
69        assert result2 == (False, 'Invalid username or password.')
70
71
72BACKENDS1 = dict(
73    inst1=dict(
74        url='http://localhost:6666/app',
75        marker='^MA-',
76        )
77    )
78
79BACKENDS2 = dict(
80    inst1=dict(
81        url='http://localhost:6666/',
82        marker='^SCHOOL1-',
83        )
84    )
85
86BACKENDS3 = dict(
87    inst1=dict(
88        url='http://localhost:6666/',
89        marker='^SCHOOL1-',
90        moodle_url = 'http://localhost:7777/',
91        )
92    )
93
94class KofaAuthenticatorTests(unittest.TestCase):
95
96    def test_create(self):
97        # we can create KofaAuthenticator instances
98        auth = KofaAuthenticator()
99        assert isinstance(auth, KofaAuthenticator)
100
101    def test_options_defaults(self):
102        # all options have sensible defaults
103        auth = KofaAuthenticator()
104        assert auth.backends == {}
105
106    def test_options(self):
107        # we can pass options
108        auth = KofaAuthenticator(auth_backends=str(BACKENDS1))
109        assert auth.backends == BACKENDS1
110        auth = KofaAuthenticator(auth_backends='{"foo": {"url": "bar"}}')
111        assert auth.backends['foo']['marker'] == '.+'
112        self.assertRaises(
113            ValueError, KofaAuthenticator, auth_backends='not-a-py-expr')
114        self.assertRaises(
115            ValueError, KofaAuthenticator, auth_backends='"Not a dict"')
116        self.assertRaises(
117            ValueError, KofaAuthenticator,
118            auth_backends='{"foo": "not-a-dict"}')
119        self.assertRaises(
120            ValueError, KofaAuthenticator,
121            auth_backends='{"foo": {"no-url-key": "bar"}}')
122        self.assertRaises(
123            ValueError, KofaAuthenticator,
124            auth_backends='{"foo": {"url": "bar", "marker": "inv_re)"}}')
125
126    def test_paste_deploy_options(self):
127        # we can set CAS server-related options via paste.deploy config
128        paste_conf = os.path.join(
129            os.path.dirname(__file__), 'sample3.ini')
130        app = loadapp('config:%s' % paste_conf)
131        assert isinstance(app, CASServer)
132        assert app.db_connection_string == 'sqlite:///:memory:'
133        assert isinstance(app.auth, KofaAuthenticator)
134
135class KofaMoodleAuthenticatorTests(unittest.TestCase):
136
137    def test_paste_deploy_options(self):
138        # we can set CAS server-related options via paste.deploy config
139        paste_conf = os.path.join(
140            os.path.dirname(__file__), 'sample4.ini')
141        app = loadapp('config:%s' % paste_conf)
142        assert isinstance(app, CASServer)
143        assert app.db_connection_string == 'sqlite:///:memory:'
144        assert isinstance(app.auth, KofaAuthenticator)
145        assert app.auth.name == 'kofa_moodle1'
146        auth_backends = {
147          'kofa_moodle1':
148            {'url': 'http://xmlrpcuser1:xmlrpcuser1@localhost:8080/app1/',
149             'marker': '^K',
150             'moodle_url': 'http://localhost/moodle/webservice/xmlrpc/server.php?wstoken=de1e1cbacf91ec6290bb6f6339122e7d',
151            },
152          }
153        assert app.auth.backends == auth_backends
154
155
156class FakeKofaServer(SimpleXMLRPCServer):
157    # A fake Kofa server that provides only XMLRPC methods
158
159    allow_reuse_address = True
160
161    def __init__(self, *args, **kw):
162        kw.update(allow_none=True)
163        SimpleXMLRPCServer.__init__(self, *args, **kw)
164        self.register_function(
165            self._check_credentials, 'check_applicant_credentials')
166        self.register_function(
167            self._check_credentials, 'check_student_credentials')
168        self.register_function(
169            self._get_moodle_data, 'get_student_moodle_data')
170        self.register_function(
171            self._get_moodle_data, 'get_applicant_moodle_data')
172
173    def _check_credentials(self, username, password):
174        # fake waeup.kofa check_credentials method.
175        #
176        # This method is supposed to mimic the behaviour of an
177        # original waeup.kofa check_credentials method. It returns a
178        # positive result for the credentials `bird`/`bebop`.
179        if username == 'bird' and password == 'bebop':
180            return {'id': 'bird', 'email': 'bird@gods.net',
181                    'description': 'Mr. Charles Parker',
182                    'type': 'student'}
183        if username == 'pig' and password == 'pog':
184            return {'id': 'pig', 'email': 'pig@gods.net',
185                    'description': 'Mr. Ray Charles',
186                    'type': 'applicant'}
187        if username in (
188            'fault1', 'fault2',
189            'fault3', 'fault4', 'fault7') and password == 'biz':
190            return {'type': 'student'}
191        if username == 'fault5' and password == 'biz':
192            return {'type': 'applicant'}
193        if username == 'fault6' and password == 'biz':
194            return {'type': 'boss'}
195        return None
196
197    def _get_moodle_data(self, username):
198        # fake waeup.kofa get_student_moodle_data method.
199        if username == 'bird':
200            return dict(email='aa@aa.aa',
201                        firstname='Charles',
202                        lastname='Parker',
203                        )
204        if username == 'pig':
205            return dict(email='bb@bb.bb',
206                        firstname='Ray',
207                        lastname='Charles',
208                        )
209        if username in ('fault1', 'fault2', 'fault3',
210                        'fault4', 'fault5', 'fault7'):
211            return dict(email='ff@ff.ff',
212                        firstname='John',
213                        lastname='Fault',
214                        )
215
216class FakeMoodleServer(SimpleXMLRPCServer):
217    # A fake Moodle server that provides only XMLRPC methods
218
219    allow_reuse_address = True
220
221    def __init__(self, *args, **kw):
222        kw.update(allow_none=True)
223        SimpleXMLRPCServer.__init__(self, *args, **kw)
224        self.register_function(
225            self._core_user_create_users, 'core_user_create_users')
226        self.register_function(
227            self._core_user_get_users, 'core_user_get_users')
228        self.register_function(
229            self._core_user_update_users, 'core_user_update_users')
230
231    def _core_user_create_users(self, arg):
232        # fake Moodle core_user_create_users method.
233        if arg[0]['username'] == 'school1-fault1':
234            raise xmlrpclib.Fault('faultCode', 'core_user_create_users failed')
235        if arg[0]['username'] == 'school1-fault7':
236            raise xmlrpclib.Fault('faultCode', 'Email address already exists')
237        return [{'username': 'any name', 'id': 37}]
238
239    def _core_user_get_users(self, arg):
240        # fake Moodle core_user_get_users method.
241        if arg[0]['value'] == 'SCHOOL1-fault2':
242            raise xmlrpclib.Fault('faultCode', 'core_user_get_users failed')
243        if arg[0]['value'] == 'SCHOOL1-fault3':
244            return {'users':[{'id':'SCHOOL1-fault3'}]}
245        if arg[0]['value'] in ('SCHOOL1-fault4', 'SCHOOL1-fault5'):
246            return {'users':[{'id': 123}]}
247        return {'users': []}
248
249    def _core_user_update_users(self, arg):
250        # fake Moodle core_user_update_users method.
251        if arg[0]['id'] == 'SCHOOL1-fault3':
252            raise xmlrpclib.Fault('faultCode', 'core_user_update_users failed')
253        return None
254
255class KofaAuthenticatorsIntegrationTests(unittest.TestCase):
256    # A test case where a fake Kofa server and a fake Moodle server
257    # are started before tests (and shut down afterwards).
258
259    kofa_server = None
260    kofa_th = None
261    moodle_server = None
262    moodle_th = None
263
264    @classmethod
265    def setUpClass(cls):
266        # set up a fake kofa server
267        cls.kofa_server = FakeKofaServer(('localhost', 6666))
268        cls.kofa_th = threading.Thread(target=cls.kofa_server.serve_forever)
269        cls.kofa_th.daemon = True
270        cls.kofa_th.start()
271        # set up a fake moodle server
272        cls.moodle_server = FakeMoodleServer(('localhost', 7777))
273        cls.moodle_th = threading.Thread(target=cls.moodle_server.serve_forever)
274        cls.moodle_th.daemon = True
275        cls.moodle_th.start()
276
277    @classmethod
278    def tearDownClass(cls):
279        # tear down fake kofa server
280        cls.kofa_server.shutdown()
281        cls.kofa_server.server_close()
282        # tear down fake moodle server
283        cls.moodle_server.shutdown()
284        cls.moodle_server.server_close()
285
286    def test_fake_kofa_works(self):
287        # make sure the local fake kofa works
288        proxy = xmlrpclib.ServerProxy("http://localhost:6666", allow_none=True)
289        result = proxy.check_student_credentials('bird', 'bebop')
290        assert result == {
291            'description': 'Mr. Charles Parker',
292            'email': 'bird@gods.net',
293            'id': 'bird',
294            'type': 'student'}
295        result = proxy.check_applicant_credentials('pig', 'pog')
296        assert result == {
297            'description': 'Mr. Ray Charles',
298            'email': 'pig@gods.net',
299            'id': 'pig',
300            'type': 'applicant'}
301        result = proxy.get_student_moodle_data('pig')
302        assert result == {
303            'lastname': 'Charles',
304            'email': 'bb@bb.bb',
305            'firstname': 'Ray',
306            }
307        result = proxy.get_applicant_moodle_data('pig')
308        assert result == {
309            'lastname': 'Charles',
310            'email': 'bb@bb.bb',
311            'firstname': 'Ray',
312            }
313        return
314
315    def test_fake_moodle_works(self):
316        # make sure the local fake moodle works
317        proxy = xmlrpclib.ServerProxy("http://localhost:7777", allow_none=True)
318        # test core_user_create_users
319        result = proxy.core_user_create_users(
320            [{'username': 'any name'}])
321        assert result ==  [{'id': 37, 'username': 'any name'}]
322        self.assertRaises(
323            xmlrpclib.Fault, proxy.core_user_create_users,
324            [{'username': 'school1-fault1'}])
325        self.assertRaises(
326            xmlrpclib.Fault, proxy.core_user_create_users,
327            [{'username': 'school1-fault7'}])
328        # test core_user_get_users
329        self.assertRaises(
330            xmlrpclib.Fault, proxy.core_user_get_users,
331            [{'key': 'username', 'value': 'SCHOOL1-fault2'}])
332        # test core_user_update_users
333        result = proxy.core_user_update_users(
334            [{'id': 234}])
335        assert result == None
336        self.assertRaises(
337            xmlrpclib.Fault, proxy.core_user_update_users,
338            [{'id': 'SCHOOL1-fault3'}])
339        return
340
341    def test_check_credentials_KofaAuthenticator(self):
342        # we get real responses when querying Kofa instances
343        auth = KofaAuthenticator(auth_backends=str(BACKENDS2))
344        result1 = auth.check_credentials('SCHOOL1-bird', 'bebop')
345        assert result1 == (True, '')
346        result2 = auth.check_credentials('SCHOOL1-foo', 'bar')
347        assert result2 == (False, 'Invalid username or password.')
348        result3 = auth.check_credentials('SCHOOL2-bar', 'baz')
349        assert result3 == (False, 'Invalid username or password.')
350
351    def test_check_credentials_KofaMoodleAuthenticator(self):
352        # we get real responses when querying Kofa instances
353        auth = KofaMoodleAuthenticator(auth_backends=str(BACKENDS3))
354        result1s = auth.check_credentials('SCHOOL1-bird', 'bebop')
355        assert result1s == (True, '')
356        result1a  = auth.check_credentials('SCHOOL1-pig', 'pog')
357        assert result1a == (True, '')
358        # user does not exist
359        result2s = auth.check_credentials('SCHOOL1-foo', 'bar')
360        assert result2s == (False, 'Invalid username or password')
361        # school does not exist
362        result3s = auth.check_credentials('SCHOOL2-bar', 'baz')
363        assert result3s == (False, 'Invalid username or password')
364        # user is neither a student nor an applicant
365        result8 = auth.check_credentials('SCHOOL1-fault6', 'biz')
366        assert result8 == (False, 'User not eligible')
367        # user has an existing email address
368        result9 = auth.check_credentials('SCHOOL1-fault7', 'biz')
369        assert result9 == (False,
370                    'Another Moodle user is using the same email address.'
371                    ' Email addresses can\'t be used twice in Moodle.')
372
373        # exception is catched if core_user_create_users fails
374        result4s = auth.check_credentials('SCHOOL1-fault1', 'biz')
375        assert result4s == (False, 'core_user_create_users failed')
376        # exception is catched if core_user_get_users fails
377        result5s = auth.check_credentials('SCHOOL1-fault2', 'biz')
378        assert result5s == (False, 'core_user_get_users failed')
379        # exception is catched if core_user_update_users fails
380        result6s = auth.check_credentials('SCHOOL1-fault3', 'biz')
381        assert result6s == (False, 'core_user_update_users failed')
382
383        # no exception is raised if user exists
384        result7s = auth.check_credentials('SCHOOL1-fault4', 'biz')
385        assert result7s == (True, '')
386        result7a = auth.check_credentials('SCHOOL1-fault5', 'biz')
387        assert result7a == (True, '')
388
389        # if marker is an empty string, school markers are neither
390        # checked nor removed
391        BACKENDS3['inst1']['marker'] = ''
392        auth = KofaMoodleAuthenticator(auth_backends=str(BACKENDS3))
393        result10s = auth.check_credentials('bird', 'bebop')
394        assert result10s == (True, '')
395        result10a = auth.check_credentials('pig', 'pog')
396        assert result10a == (True, '')
397        result11s = auth.check_credentials('SCHOOL1-bird', 'bebop')
398        assert result11s == (False, 'Invalid username or password')
399        result11a = auth.check_credentials('SCHOOL1-pig', 'pog')
400        assert result11a == (False, 'Invalid username or password')
Note: See TracBrowser for help on using the repository browser.