test_kstore.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.1 (the License). You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License. You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10. import unittest
  11. from BTLR.platform import bttime
  12. from time import sleep
  13. from kstore import KStore
  14. if __name__ =="__main__":
  15. tests = unittest.defaultTestLoader.loadTestsFromNames(['test_kstore'])
  16. result = unittest.TextTestRunner().run(tests)
  17. class BasicTests(unittest.TestCase):
  18. def setUp(self):
  19. self.k = KStore()
  20. def testNoKeys(self):
  21. self.assertEqual(self.k.keys(), [])
  22. def testKey(self):
  23. self.k['foo'] = 'bar'
  24. self.assertEqual(self.k.keys(), ['foo'])
  25. def testKeys(self):
  26. self.k['foo'] = 'bar'
  27. self.k['wing'] = 'wang'
  28. l = self.k.keys()
  29. l.sort()
  30. self.assertEqual(l, ['foo', 'wing'])
  31. def testInsert(self):
  32. self.k['foo'] = 'bar'
  33. self.assertEqual(self.k['foo'], ['bar'])
  34. def testInsertTwo(self):
  35. self.k['foo'] = 'bar'
  36. self.k['foo'] = 'bing'
  37. l = self.k['foo']
  38. l.sort()
  39. self.assertEqual(l, ['bar', 'bing'])
  40. def testExpire(self):
  41. self.k['foo'] = 'bar'
  42. self.k.expire(bttime() - 1)
  43. l = self.k['foo']
  44. l.sort()
  45. self.assertEqual(l, ['bar'])
  46. self.k['foo'] = 'bing'
  47. t = bttime()
  48. self.k.expire(bttime() - 1)
  49. l = self.k['foo']
  50. l.sort()
  51. self.assertEqual(l, ['bar', 'bing'])
  52. self.k['foo'] = 'ding'
  53. self.k['foo'] = 'dang'
  54. l = self.k['foo']
  55. l.sort()
  56. self.assertEqual(l, ['bar', 'bing', 'dang', 'ding'])
  57. self.k.expire(t)
  58. l = self.k['foo']
  59. l.sort()
  60. self.assertEqual(l, ['dang', 'ding'])
  61. def testDup(self):
  62. self.k['foo'] = 'bar'
  63. self.k['foo'] = 'bar'
  64. self.assertEqual(self.k['foo'], ['bar'])
  65. def testSample(self):
  66. for i in xrange(2):
  67. self.k['foo'] = i
  68. l = self.k.sample('foo', 5)
  69. l.sort()
  70. self.assertEqual(l, [0, 1])
  71. for i in xrange(10):
  72. for i in xrange(10):
  73. self.k['bar'] = i
  74. l = self.k.sample('bar', 5)
  75. self.assertEqual(len(l), 5)
  76. for i in xrange(len(l)):
  77. self.assert_(l[i] not in l[i+1:])