1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
5 Test cases for L{twisted.python.randbytes}.
10 from twisted.trial import unittest
11 from twisted.python import randbytes
15 class SecureRandomTestCaseBase(object):
17 Base class for secureRandom test cases.
20 def _check(self, source):
22 The given random bytes source should return the number of bytes
23 requested each time it is called and should probably not return the
24 same bytes on two consecutive calls (although this is a perfectly
25 legitimate occurrence and rejecting it may generate a spurious failure
26 -- maybe we'll get lucky and the heat death with come first).
28 for nbytes in range(17, 25):
30 self.assertEqual(len(s), nbytes)
32 self.assertEqual(len(s2), nbytes)
33 # This is crude but hey
34 self.assertNotEquals(s2, s)
38 class SecureRandomTestCase(SecureRandomTestCaseBase, unittest.TestCase):
40 Test secureRandom under normal conditions.
43 def test_normal(self):
45 L{randbytes.secureRandom} should return a string of the requested
46 length and make some effort to make its result otherwise unpredictable.
48 self._check(randbytes.secureRandom)
52 class ConditionalSecureRandomTestCase(SecureRandomTestCaseBase,
55 Test random sources one by one, then remove it to.
60 Create a L{randbytes.RandomFactory} to use in the tests.
62 self.factory = randbytes.RandomFactory()
65 def errorFactory(self, nbytes):
67 A factory raising an error when a source is not available.
69 raise randbytes.SourceNotAvailable()
72 def test_osUrandom(self):
74 L{RandomFactory._osUrandom} should work as a random source whenever
75 L{os.urandom} is available.
77 self._check(self.factory._osUrandom)
80 def test_withoutAnything(self):
82 Remove all secure sources and assert it raises a failure. Then try the
85 self.factory._osUrandom = self.errorFactory
86 self.assertRaises(randbytes.SecureRandomNotAvailable,
87 self.factory.secureRandom, 18)
89 return self.factory.secureRandom(18, fallback=True)
92 "urandom unavailable - "
93 "proceeding with non-cryptographically secure random source",
96 self.assertEqual(len(s), 18)
100 class RandomTestCaseBase(SecureRandomTestCaseBase, unittest.TestCase):
102 'Normal' random test cases.
105 def test_normal(self):
109 self._check(randbytes.insecureRandom)
112 def test_withoutGetrandbits(self):
114 Test C{insecureRandom} without C{random.getrandbits}.
116 factory = randbytes.RandomFactory()
117 factory.getrandbits = None
118 self._check(factory.insecureRandom)