Debian Codegraph @

tests/unit/test_client.py

raw symbols SCIP
1 try:
2 import unittest2 as unittest
3 except ImportError:
4 import unittest # noqa
5
6 from puresasl import SASLError
7 from puresasl.client import SASLClient
8 from puresasl.mechanisms import AnonymousMechanism, PlainMechanism, mechanisms, DigestMD5Mechanism
9
10
11 class SASLClientTest(unittest.TestCase):
12
13 def test_init(self):
14 # defaults
15 SASLClient('localhost')
16
17 # with mechanism
18 sasl_client = SASLClient('localhost', mechanism=AnonymousMechanism.name)
19 self.assertIsInstance(sasl_client._chosen_mech, AnonymousMechanism)
20 self.assertIs(sasl_client._chosen_mech.sasl, sasl_client)
21
22 # invalid mech
23 self.assertRaises(SASLError, SASLClient, 'localhost', mechanism='WRONG')
24
25 def test_chosen_mechanism(self):
26 client = SASLClient('localhost', mechanism=PlainMechanism.name, username='user', password='pass')
27 self.assertTrue(client.process())
28 self.assertTrue(client.complete)
29 msg = 'msg'
30 self.assertEqual(client.wrap(msg), msg)
31 self.assertEqual(client.unwrap(msg), msg)
32 client.dispose()
33
34 def test_unchosen_mechanism(self):
35 client = SASLClient('localhost')
36 self.assertRaises(SASLError, client.process)
37 self.assertRaises(SASLError, client.wrap, 'msg')
38 self.assertRaises(SASLError, client.unwrap, 'msg')
39 with self.assertRaises(SASLError):
40 client.complete
41 self.assertRaises(SASLError, client.dispose)
42
43 def test_choose_mechanism(self):
44 client = SASLClient('localhost', service='something')
45 choices = ['invalid']
46 self.assertRaises(SASLError, client.choose_mechanism, choices)
47
48 choices = [m for m in mechanisms.values() if m is not DigestMD5Mechanism]
49 mech_names = set(m.name for m in choices)
50 client.choose_mechanism(mech_names)
51 self.assertIsInstance(client._chosen_mech, max(choices, key=lambda m: m.score))
52
53 anon_names = set(m.name for m in choices if m.allows_anonymous)
54 client.choose_mechanism(anon_names)
55 self.assertIn(client.mechanism, anon_names)
56 self.assertRaises(SASLError, client.choose_mechanism, anon_names, allow_anonymous=False)
57
58 plain_names = set(m.name for m in choices if m.uses_plaintext)
59 client.choose_mechanism(plain_names)
60 self.assertIn(client.mechanism, plain_names)
61 self.assertRaises(SASLError, client.choose_mechanism, plain_names, allow_plaintext=False)
62
63 not_active_names = set(m.name for m in choices if not m.active_safe)
64 client.choose_mechanism(not_active_names)
65 self.assertIn(client.mechanism, not_active_names)
66 self.assertRaises(SASLError, client.choose_mechanism, not_active_names, allow_active=False)
67
68 not_dict_names = set(m.name for m in choices if not m.dictionary_safe)
69 client.choose_mechanism(not_dict_names)
70 self.assertIn(client.mechanism, not_dict_names)
71 self.assertRaises(SASLError, client.choose_mechanism, not_dict_names, allow_dictionary=False)