• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python -S
2#
3# Copyright 2014 Google Inc. All rights reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18fastrand_test.py: Tests for _fastrand extension module.
19"""
20import unittest
21
22import _fastrand  # module under test
23
24
25BIT_WIDTHS = [8, 16, 32, 64]
26
27
28class FastRandTest(unittest.TestCase):
29
30  def testRandbits64(self):
31    for n in BIT_WIDTHS:
32      #print '== %d' % n
33      for p1 in [0.1, 0.5, 0.9]:
34        #print '-- %f' % p1
35        for i in xrange(5):
36          r = _fastrand.randbits(p1, n)
37          # Rough sanity check
38          self.assertLess(r, 2 ** n)
39
40          # Visual check
41          #b = bin(r)
42          #print b
43          #print b.count('1')
44
45
46  def testRandbits64_EdgeCases(self):
47    for n in BIT_WIDTHS:
48      r = _fastrand.randbits(0.0, n)
49      self.assertEqual(0, r)
50
51    for n in BIT_WIDTHS:
52      r = _fastrand.randbits(1.0, n)
53      self.assertEqual(2 ** n - 1, r)
54
55  def testRandbitsError(self):
56    r = _fastrand.randbits(-1, 64)
57    # TODO: Should probably raise exceptions
58    self.assertEqual(None, r)
59
60    r = _fastrand.randbits(0.0, 65)
61    self.assertEqual(None, r)
62
63
64if __name__ == '__main__':
65  unittest.main()
66