test_threadedtempfile.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. Create and delete FILES_PER_THREAD temp files (via tempfile.TemporaryFile)
  3. in each of NUM_THREADS threads, recording the number of successes and
  4. failures. A failure is a bug in tempfile, and may be due to:
  5. + Trying to create more than one tempfile with the same name.
  6. + Trying to delete a tempfile that doesn't still exist.
  7. + Something we've never seen before.
  8. By default, NUM_THREADS == 20 and FILES_PER_THREAD == 50. This is enough to
  9. create about 150 failures per run under Win98SE in 2.0, and runs pretty
  10. quickly. Guido reports needing to boost FILES_PER_THREAD to 500 before
  11. provoking a 2.0 failure under Linux.
  12. """
  13. NUM_THREADS = 20
  14. FILES_PER_THREAD = 50
  15. import tempfile
  16. from test.test_support import start_threads, run_unittest, import_module
  17. threading = import_module('threading')
  18. import unittest
  19. import StringIO
  20. from traceback import print_exc
  21. startEvent = threading.Event()
  22. class TempFileGreedy(threading.Thread):
  23. error_count = 0
  24. ok_count = 0
  25. def run(self):
  26. self.errors = StringIO.StringIO()
  27. startEvent.wait()
  28. for i in range(FILES_PER_THREAD):
  29. try:
  30. f = tempfile.TemporaryFile("w+b")
  31. f.close()
  32. except:
  33. self.error_count += 1
  34. print_exc(file=self.errors)
  35. else:
  36. self.ok_count += 1
  37. class ThreadedTempFileTest(unittest.TestCase):
  38. def test_main(self):
  39. threads = [TempFileGreedy() for i in range(NUM_THREADS)]
  40. with start_threads(threads, startEvent.set):
  41. pass
  42. ok = sum(t.ok_count for t in threads)
  43. errors = [str(t.getName()) + str(t.errors.getvalue())
  44. for t in threads if t.error_count]
  45. msg = "Errors: errors %d ok %d\n%s" % (len(errors), ok,
  46. '\n'.join(errors))
  47. self.assertEqual(errors, [], msg)
  48. self.assertEqual(ok, NUM_THREADS * FILES_PER_THREAD)
  49. def test_main():
  50. run_unittest(ThreadedTempFileTest)
  51. if __name__ == "__main__":
  52. test_main()