/Lib/test/test_dummy_thread.py

http://unladen-swallow.googlecode.com/ · Python · 182 lines · 125 code · 25 blank · 32 comment · 13 complexity · 9aa3a29a477ad4923a5312d0de961a7f 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. self.failUnless(self.lock.acquire() is True)
  52. def test_uncond_acquire_blocking(self):
  53. #Make sure that unconditional acquiring of a locked lock blocks.
  54. def delay_unlock(to_unlock, delay):
  55. """Hold on to lock for a set amount of time before unlocking."""
  56. time.sleep(delay)
  57. to_unlock.release()
  58. self.lock.acquire()
  59. start_time = int(time.time())
  60. _thread.start_new_thread(delay_unlock,(self.lock, DELAY))
  61. if test_support.verbose:
  62. print
  63. print "*** Waiting for thread to release the lock "\
  64. "(approx. %s sec.) ***" % DELAY
  65. self.lock.acquire()
  66. end_time = int(time.time())
  67. if test_support.verbose:
  68. print "done"
  69. self.failUnless((end_time - start_time) >= DELAY,
  70. "Blocking by unconditional acquiring failed.")
  71. class MiscTests(unittest.TestCase):
  72. """Miscellaneous tests."""
  73. def test_exit(self):
  74. #Make sure _thread.exit() raises SystemExit
  75. self.failUnlessRaises(SystemExit, _thread.exit)
  76. def test_ident(self):
  77. #Test sanity of _thread.get_ident()
  78. self.failUnless(isinstance(_thread.get_ident(), int),
  79. "_thread.get_ident() returned a non-integer")
  80. self.failUnless(_thread.get_ident() != 0,
  81. "_thread.get_ident() returned 0")
  82. def test_LockType(self):
  83. #Make sure _thread.LockType is the same type as _thread.allocate_locke()
  84. self.failUnless(isinstance(_thread.allocate_lock(), _thread.LockType),
  85. "_thread.LockType is not an instance of what is "
  86. "returned by _thread.allocate_lock()")
  87. def test_interrupt_main(self):
  88. #Calling start_new_thread with a function that executes interrupt_main
  89. # should raise KeyboardInterrupt upon completion.
  90. def call_interrupt():
  91. _thread.interrupt_main()
  92. self.failUnlessRaises(KeyboardInterrupt, _thread.start_new_thread,
  93. call_interrupt, tuple())
  94. def test_interrupt_in_main(self):
  95. # Make sure that if interrupt_main is called in main threat that
  96. # KeyboardInterrupt is raised instantly.
  97. self.failUnlessRaises(KeyboardInterrupt, _thread.interrupt_main)
  98. class ThreadTests(unittest.TestCase):
  99. """Test thread creation."""
  100. def test_arg_passing(self):
  101. #Make sure that parameter passing works.
  102. def arg_tester(queue, arg1=False, arg2=False):
  103. """Use to test _thread.start_new_thread() passes args properly."""
  104. queue.put((arg1, arg2))
  105. testing_queue = Queue.Queue(1)
  106. _thread.start_new_thread(arg_tester, (testing_queue, True, True))
  107. result = testing_queue.get()
  108. self.failUnless(result[0] and result[1],
  109. "Argument passing for thread creation using tuple failed")
  110. _thread.start_new_thread(arg_tester, tuple(), {'queue':testing_queue,
  111. 'arg1':True, 'arg2':True})
  112. result = testing_queue.get()
  113. self.failUnless(result[0] and result[1],
  114. "Argument passing for thread creation using kwargs failed")
  115. _thread.start_new_thread(arg_tester, (testing_queue, True), {'arg2':True})
  116. result = testing_queue.get()
  117. self.failUnless(result[0] and result[1],
  118. "Argument passing for thread creation using both tuple"
  119. " and kwargs failed")
  120. def test_multi_creation(self):
  121. #Make sure multiple threads can be created.
  122. def queue_mark(queue, delay):
  123. """Wait for ``delay`` seconds and then put something into ``queue``"""
  124. time.sleep(delay)
  125. queue.put(_thread.get_ident())
  126. thread_count = 5
  127. testing_queue = Queue.Queue(thread_count)
  128. if test_support.verbose:
  129. print
  130. print "*** Testing multiple thread creation "\
  131. "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)
  132. for count in xrange(thread_count):
  133. if DELAY:
  134. local_delay = round(random.random(), 1)
  135. else:
  136. local_delay = 0
  137. _thread.start_new_thread(queue_mark,
  138. (testing_queue, local_delay))
  139. time.sleep(DELAY)
  140. if test_support.verbose:
  141. print 'done'
  142. self.failUnless(testing_queue.qsize() == thread_count,
  143. "Not all %s threads executed properly after %s sec." %
  144. (thread_count, DELAY))
  145. def test_main(imported_module=None):
  146. global _thread, DELAY
  147. if imported_module:
  148. _thread = imported_module
  149. DELAY = 2
  150. if test_support.verbose:
  151. print
  152. print "*** Using %s as _thread module ***" % _thread
  153. test_support.run_unittest(LockTests, MiscTests, ThreadTests)
  154. if __name__ == '__main__':
  155. test_main()