test-bloom-filter 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. #!/usr/bin/python
  2. # pylint: disable=W0402
  3. # W0402: We want the deprecated string module, for a use that isn't deprecated
  4. '''Unit tests for bloom_filter_mod'''
  5. import os
  6. import sys
  7. import math
  8. import time
  9. import random
  10. import bloom_filter_mod
  11. CHARACTERS = 'abcdefghijklmnopqrstuvwxyz1234567890'
  12. def my_range(maximum):
  13. '''A range function with consistent semantics on 2.x and 3.x'''
  14. value = 0
  15. while True:
  16. if value >= maximum:
  17. break
  18. yield value
  19. value += 1
  20. def test(description, values, trials, error_rate, probe_bitnoer=bloom_filter_mod.get_bitno_lin_comb, filename=None):
  21. # pylint: disable=R0913
  22. # R0913: We want a few arguments
  23. '''Some quick automatic tests for the bloom filter class'''
  24. if filename is not None:
  25. try:
  26. # start fresh
  27. os.unlink(filename)
  28. except OSError:
  29. pass
  30. all_good = True
  31. bloom_filter = bloom_filter_mod.Bloom_filter(
  32. ideal_num_elements_n=trials * 2,
  33. error_rate_p=error_rate,
  34. probe_bitnoer=probe_bitnoer,
  35. filename=filename,
  36. )
  37. #print(repr(bloom_filter))
  38. sys.stdout.write('\ndescription: %s num_bits_m: %s num_probes_k: %s\n' %
  39. (description, bloom_filter.num_bits_m, bloom_filter.num_probes_k))
  40. print('adding')
  41. for include in values.generator():
  42. bloom_filter.add(include)
  43. print('testing all known members')
  44. include_in_count = sum(include in bloom_filter for include in values.generator())
  45. if include_in_count == values.length():
  46. # Good
  47. pass
  48. else:
  49. sys.stderr.write('Include count bad: %s, %d\n' % (include_in_count, values.length()))
  50. all_good = False
  51. print('testing random non-members')
  52. false_positives = 0
  53. for trialno in my_range(trials):
  54. if trialno % 100000 == 0:
  55. sys.stderr.write('trialno countdown: %d\n' % (trials-trialno))
  56. #dummy = trialno
  57. while True:
  58. candidate = ''.join(random.sample(CHARACTERS, 5))
  59. # If we accidentally found a member, try again
  60. if values.within(candidate):
  61. continue
  62. if candidate in bloom_filter:
  63. #print 'We erroneously think %s is in the filter' % candidate
  64. false_positives += 1
  65. break
  66. actual_error_rate = float(false_positives) / trials
  67. if actual_error_rate > error_rate:
  68. sys.stderr.write('%s: Too many false positives: actual: %s, expected: %s\n' % (
  69. sys.argv[0],
  70. actual_error_rate,
  71. error_rate,
  72. ))
  73. all_good = False
  74. return all_good
  75. class States:
  76. '''Generate the USA's state names'''
  77. def __init__(self):
  78. pass
  79. states = '''Alabama Alaska Arizona Arkansas California Colorado Connecticut
  80. Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas
  81. Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota
  82. Mississippi Missouri Montana Nebraska Nevada NewHampshire NewJersey
  83. NewMexico NewYork NorthCarolina NorthDakota Ohio Oklahoma Oregon
  84. Pennsylvania RhodeIsland SouthCarolina SouthDakota Tennessee Texas Utah
  85. Vermont Virginia Washington WestVirginia Wisconsin Wyoming'''.split()
  86. @staticmethod
  87. def generator():
  88. '''Generate the states'''
  89. for state in States.states:
  90. yield state
  91. @staticmethod
  92. def within(value):
  93. '''Is the vaoue in our list of states?'''
  94. return value in States.states
  95. @staticmethod
  96. def length():
  97. '''What is the length of our contained values?'''
  98. return len(States.states)
  99. def random_string():
  100. '''Generate a random, 10 character string - for testing purposes'''
  101. list_ = []
  102. for chrno in range(10):
  103. dummy = chrno
  104. character = CHARACTERS[int(random.random() * len(CHARACTERS))]
  105. list_.append(character)
  106. return ''.join(list_)
  107. class Random_content:
  108. '''Generated a bunch of random strings in sorted order'''
  109. random_content = [ random_string() for dummy in range(1000) ]
  110. def __init__(self):
  111. pass
  112. @staticmethod
  113. def generator():
  114. '''Generate all values'''
  115. for item in Random_content.random_content:
  116. yield item
  117. @staticmethod
  118. def within(value):
  119. '''Test for membership'''
  120. return value in Random_content.random_content
  121. @staticmethod
  122. def length():
  123. '''How many members?'''
  124. return len(Random_content.random_content)
  125. class Evens:
  126. '''Generate a bunch of even numbers'''
  127. def __init__(self, maximum):
  128. self.maximum = maximum
  129. def generator(self):
  130. '''Generate all values'''
  131. for value in my_range(self.maximum):
  132. if value % 2 == 0:
  133. yield str(value)
  134. def within(self, value):
  135. '''Test for membership'''
  136. try:
  137. int_value = int(value)
  138. except ValueError:
  139. return False
  140. if int_value >= 0 and int_value < self.maximum and int_value % 2 == 0:
  141. return True
  142. else:
  143. return False
  144. def length(self):
  145. '''How many members?'''
  146. return int(math.ceil(self.maximum / 2.0))
  147. def and_test():
  148. '''Test the & operator'''
  149. all_good = True
  150. abc = bloom_filter_mod.Bloom_filter(ideal_num_elements_n=100, error_rate_p=0.01)
  151. for character in [ 'a', 'b', 'c' ]:
  152. abc += character
  153. bcd = bloom_filter_mod.Bloom_filter(ideal_num_elements_n=100, error_rate_p=0.01)
  154. for character in [ 'b', 'c', 'd' ]:
  155. bcd += character
  156. abc_and_bcd = abc
  157. abc_and_bcd &= bcd
  158. if 'a' in abc_and_bcd:
  159. sys.stderr.write('a in abc_and_bcd, but should not be')
  160. all_good = False
  161. if not 'b' in abc_and_bcd:
  162. sys.stderr.write('b not in abc_and_bcd, but should be')
  163. all_good = False
  164. if not 'c' in abc_and_bcd:
  165. sys.stderr.write('c not in abc_and_bcd, but should be')
  166. all_good = False
  167. if 'd' in abc_and_bcd:
  168. sys.stderr.write('d in abc_and_bcd, but should not be')
  169. all_good = False
  170. return all_good
  171. def or_test():
  172. '''Test the | operator'''
  173. all_good = True
  174. abc = bloom_filter_mod.Bloom_filter(ideal_num_elements_n=100, error_rate_p=0.01)
  175. for character in [ 'a', 'b', 'c' ]:
  176. abc += character
  177. bcd = bloom_filter_mod.Bloom_filter(ideal_num_elements_n=100, error_rate_p=0.01)
  178. for character in [ 'b', 'c', 'd' ]:
  179. bcd += character
  180. abc_and_bcd = abc
  181. abc_and_bcd |= bcd
  182. if not 'a' in abc_and_bcd:
  183. sys.stderr.write('a not in abc_and_bcd, but should be')
  184. all_good = False
  185. if not 'b' in abc_and_bcd:
  186. sys.stderr.write('b not in abc_and_bcd, but should be')
  187. all_good = False
  188. if not 'c' in abc_and_bcd:
  189. sys.stderr.write('c not in abc_and_bcd, but should be')
  190. all_good = False
  191. if not 'd' in abc_and_bcd:
  192. sys.stderr.write('d not in abc_and_bcd, but should be')
  193. all_good = False
  194. if 'e' in abc_and_bcd:
  195. sys.stderr.write('e in abc_and_bcd, but should be')
  196. all_good = False
  197. return all_good
  198. def main():
  199. '''Unit tests for Bloom_filter class'''
  200. all_good = True
  201. all_good &= test('states', States(), trials=100000, error_rate=0.01)
  202. all_good &= test('random', Random_content(), trials=10000, error_rate=0.1)
  203. all_good &= test('random', Random_content(), trials=10000, error_rate=0.1, probe_bitnoer=bloom_filter_mod.get_bitno_seed_rnd)
  204. filename = 'bloom-filter-rm-me'
  205. all_good &= test('random', Random_content(), trials=10000, error_rate=0.1, filename=filename)
  206. #for exponent in range(5):
  207. for exponent in range(10):
  208. elements = int(math.sqrt(10) ** exponent)
  209. for filename in [ None, 'bloom-filter-rm-me' ]:
  210. time0 = time.time()
  211. #if filename is None and elements > 1000000:
  212. # continue
  213. all_good &= test(
  214. 'evens %s %d' % ('array' if filename is None else 'file', elements),
  215. Evens(elements),
  216. trials=elements,
  217. error_rate=1e-12,
  218. filename=filename,
  219. )
  220. time1 = time.time()
  221. delta_t = time1 - time0
  222. if filename is None:
  223. file_ = open('array.txt', 'a')
  224. else:
  225. file_ = open('seek.txt', 'a')
  226. file_.write('%d %f\n' % (elements, delta_t))
  227. file_.close()
  228. all_good &= and_test()
  229. all_good &= or_test()
  230. if all_good:
  231. sys.stderr.write('%s: All tests passed\n' % sys.argv[0])
  232. sys.exit(0)
  233. else:
  234. sys.stderr.write('%s: One or more tests failed\n' % sys.argv[0])
  235. sys.exit(1)
  236. main()