test_threadedtempfile.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. import tempfile
  14. from test.support import threading_helper
  15. import unittest
  16. import io
  17. import threading
  18. from traceback import print_exc
  19. threading_helper.requires_working_threading(module=True)
  20. NUM_THREADS = 20
  21. FILES_PER_THREAD = 50
  22. startEvent = threading.Event()
  23. class TempFileGreedy(threading.Thread):
  24. error_count = 0
  25. ok_count = 0
  26. def run(self):
  27. self.errors = io.StringIO()
  28. startEvent.wait()
  29. for i in range(FILES_PER_THREAD):
  30. try:
  31. f = tempfile.TemporaryFile("w+b")
  32. f.close()
  33. except:
  34. self.error_count += 1
  35. print_exc(file=self.errors)
  36. else:
  37. self.ok_count += 1
  38. class ThreadedTempFileTest(unittest.TestCase):
  39. def test_main(self):
  40. threads = [TempFileGreedy() for i in range(NUM_THREADS)]
  41. with threading_helper.start_threads(threads, startEvent.set):
  42. pass
  43. ok = sum(t.ok_count for t in threads)
  44. errors = [str(t.name) + str(t.errors.getvalue())
  45. for t in threads if t.error_count]
  46. msg = "Errors: errors %d ok %d\n%s" % (len(errors), ok,
  47. '\n'.join(errors))
  48. self.assertEqual(errors, [], msg)
  49. self.assertEqual(ok, NUM_THREADS * FILES_PER_THREAD)
  50. if __name__ == "__main__":
  51. unittest.main()