PageRenderTime 43ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/SiRFLive/PythonStdLib/test/test_dummy_thread.py

https://bitbucket.org/x893/sirflive
Python | 181 lines | 124 code | 25 blank | 32 comment | 13 complexity | b5129c1bbfb0e0b2b4875e458aa4415d MD5 | raw file
  1. """Generic thread tests.
  2. Meant to be used by dummy_thread and thread. To allow for different modules
  3. to be used, test_main() can be called with the module to use as the thread
  4. implementation as its sole argument.
  5. """
  6. import dummy_thread as _thread
  7. import time
  8. import Queue
  9. import random
  10. import unittest
  11. from test import test_support
  12. DELAY = 0 # Set > 0 when testing a module other than dummy_thread, such as
  13. # the 'thread' module.
  14. class LockTests(unittest.TestCase):
  15. """Test lock objects."""
  16. def setUp(self):
  17. # Create a lock
  18. self.lock = _thread.allocate_lock()
  19. def test_initlock(self):
  20. #Make sure locks start locked
  21. self.failUnless(not self.lock.locked(),
  22. "Lock object is not initialized unlocked.")
  23. def test_release(self):
  24. # Test self.lock.release()
  25. self.lock.acquire()
  26. self.lock.release()
  27. self.failUnless(not self.lock.locked(),
  28. "Lock object did not release properly.")
  29. def test_improper_release(self):
  30. #Make sure release of an unlocked thread raises _thread.error
  31. self.failUnlessRaises(_thread.error, self.lock.release)
  32. def test_cond_acquire_success(self):
  33. #Make sure the conditional acquiring of the lock works.
  34. self.failUnless(self.lock.acquire(0),
  35. "Conditional acquiring of the lock failed.")
  36. def test_cond_acquire_fail(self):
  37. #Test acquiring locked lock returns False
  38. self.lock.acquire(0)
  39. self.failUnless(not self.lock.acquire(0),
  40. "Conditional acquiring of a locked lock incorrectly "
  41. "succeeded.")
  42. def test_uncond_acquire_success(self):
  43. #Make sure unconditional acquiring of a lock works.
  44. self.lock.acquire()
  45. self.failUnless(self.lock.locked(),
  46. "Uncondional locking failed.")
  47. def test_uncond_acquire_return_val(self):
  48. #Make sure that an unconditional locking returns True.
  49. self.failUnless(self.lock.acquire(1) is True,
  50. "Unconditional locking did not return True.")
  51. def test_uncond_acquire_blocking(self):
  52. #Make sure that unconditional acquiring of a locked lock blocks.
  53. def delay_unlock(to_unlock, delay):
  54. """Hold on to lock for a set amount of time before unlocking."""
  55. time.sleep(delay)
  56. to_unlock.release()
  57. self.lock.acquire()
  58. start_time = int(time.time())
  59. _thread.start_new_thread(delay_unlock,(self.lock, DELAY))
  60. if test_support.verbose:
  61. print
  62. print "*** Waiting for thread to release the lock "\
  63. "(approx. %s sec.) ***" % DELAY
  64. self.lock.acquire()
  65. end_time = int(time.time())
  66. if test_support.verbose:
  67. print "done"
  68. self.failUnless((end_time - start_time) >= DELAY,
  69. "Blocking by unconditional acquiring failed.")
  70. class MiscTests(unittest.TestCase):
  71. """Miscellaneous tests."""
  72. def test_exit(self):
  73. #Make sure _thread.exit() raises SystemExit
  74. self.failUnlessRaises(SystemExit, _thread.exit)
  75. def test_ident(self):
  76. #Test sanity of _thread.get_ident()
  77. self.failUnless(isinstance(_thread.get_ident(), int),
  78. "_thread.get_ident() returned a non-integer")
  79. self.failUnless(_thread.get_ident() != 0,
  80. "_thread.get_ident() returned 0")
  81. def test_LockType(self):
  82. #Make sure _thread.LockType is the same type as _thread.allocate_locke()
  83. self.failUnless(isinstance(_thread.allocate_lock(), _thread.LockType),
  84. "_thread.LockType is not an instance of what is "
  85. "returned by _thread.allocate_lock()")
  86. def test_interrupt_main(self):
  87. #Calling start_new_thread with a function that executes interrupt_main
  88. # should raise KeyboardInterrupt upon completion.
  89. def call_interrupt():
  90. _thread.interrupt_main()
  91. self.failUnlessRaises(KeyboardInterrupt, _thread.start_new_thread,
  92. call_interrupt, tuple())
  93. def test_interrupt_in_main(self):
  94. # Make sure that if interrupt_main is called in main threat that
  95. # KeyboardInterrupt is raised instantly.
  96. self.failUnlessRaises(KeyboardInterrupt, _thread.interrupt_main)
  97. class ThreadTests(unittest.TestCase):
  98. """Test thread creation."""
  99. def test_arg_passing(self):
  100. #Make sure that parameter passing works.
  101. def arg_tester(queue, arg1=False, arg2=False):
  102. """Use to test _thread.start_new_thread() passes args properly."""
  103. queue.put((arg1, arg2))
  104. testing_queue = Queue.Queue(1)
  105. _thread.start_new_thread(arg_tester, (testing_queue, True, True))
  106. result = testing_queue.get()
  107. self.failUnless(result[0] and result[1],
  108. "Argument passing for thread creation using tuple failed")
  109. _thread.start_new_thread(arg_tester, tuple(), {'queue':testing_queue,
  110. 'arg1':True, 'arg2':True})
  111. result = testing_queue.get()
  112. self.failUnless(result[0] and result[1],
  113. "Argument passing for thread creation using kwargs failed")
  114. _thread.start_new_thread(arg_tester, (testing_queue, True), {'arg2':True})
  115. result = testing_queue.get()
  116. self.failUnless(result[0] and result[1],
  117. "Argument passing for thread creation using both tuple"
  118. " and kwargs failed")
  119. def test_multi_creation(self):
  120. #Make sure multiple threads can be created.
  121. def queue_mark(queue, delay):
  122. """Wait for ``delay`` seconds and then put something into ``queue``"""
  123. time.sleep(delay)
  124. queue.put(_thread.get_ident())
  125. thread_count = 5
  126. testing_queue = Queue.Queue(thread_count)
  127. if test_support.verbose:
  128. print
  129. print "*** Testing multiple thread creation "\
  130. "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)
  131. for count in xrange(thread_count):
  132. if DELAY:
  133. local_delay = round(random.random(), 1)
  134. else:
  135. local_delay = 0
  136. _thread.start_new_thread(queue_mark,
  137. (testing_queue, local_delay))
  138. time.sleep(DELAY)
  139. if test_support.verbose:
  140. print 'done'
  141. self.failUnless(testing_queue.qsize() == thread_count,
  142. "Not all %s threads executed properly after %s sec." %
  143. (thread_count, DELAY))
  144. def test_main(imported_module=None):
  145. global _thread, DELAY
  146. if imported_module:
  147. _thread = imported_module
  148. DELAY = 2
  149. if test_support.verbose:
  150. print
  151. print "*** Using %s as _thread module ***" % _thread
  152. test_support.run_unittest(LockTests, MiscTests, ThreadTests)
  153. if __name__ == '__main__':
  154. test_main()