blob: fe63c9e91437bac33f7f2f45b3948ea3a853f049 [file] [log] [blame]
Tim Peters9fadfb02001-01-13 03:04:02 +00001"""
2Create and delete FILES_PER_THREAD temp files (via tempfile.TemporaryFile)
3in each of NUM_THREADS threads, recording the number of successes and
4failures. A failure is a bug in tempfile, and may be due to:
5
6+ Trying to create more than one tempfile with the same name.
7+ Trying to delete a tempfile that doesn't still exist.
8+ Something we've never seen before.
9
10By default, NUM_THREADS == 20 and FILES_PER_THREAD == 50. This is enough to
11create about 150 failures per run under Win98SE in 2.0, and runs pretty
12quickly. Guido reports needing to boost FILES_PER_THREAD to 500 before
Guido van Rossumd8faa362007-04-27 19:54:29 +000013provoking a 2.0 failure under Linux.
Tim Peters9fadfb02001-01-13 03:04:02 +000014"""
15
Guido van Rossumd8faa362007-04-27 19:54:29 +000016import tempfile
17
Hai Shie80697d2020-05-28 06:10:27 +080018from test.support import threading_helper
Guido van Rossumd8faa362007-04-27 19:54:29 +000019import unittest
Guido van Rossum34d19282007-08-09 01:03:29 +000020import io
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020021import threading
Tim Peters9fadfb02001-01-13 03:04:02 +000022from traceback import print_exc
23
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020024
25NUM_THREADS = 20
26FILES_PER_THREAD = 50
27
28
Tim Peters9fadfb02001-01-13 03:04:02 +000029startEvent = threading.Event()
30
Victor Stinner8f4ef3b2019-07-01 18:28:25 +020031
Tim Peters9fadfb02001-01-13 03:04:02 +000032class TempFileGreedy(threading.Thread):
33 error_count = 0
34 ok_count = 0
35
36 def run(self):
Guido van Rossum34d19282007-08-09 01:03:29 +000037 self.errors = io.StringIO()
Tim Peters9fadfb02001-01-13 03:04:02 +000038 startEvent.wait()
39 for i in range(FILES_PER_THREAD):
40 try:
41 f = tempfile.TemporaryFile("w+b")
42 f.close()
43 except:
44 self.error_count += 1
45 print_exc(file=self.errors)
46 else:
47 self.ok_count += 1
48
Guido van Rossumd8faa362007-04-27 19:54:29 +000049
50class ThreadedTempFileTest(unittest.TestCase):
51 def test_main(self):
Serhiy Storchaka263dcd22015-04-01 13:01:14 +030052 threads = [TempFileGreedy() for i in range(NUM_THREADS)]
Hai Shie80697d2020-05-28 06:10:27 +080053 with threading_helper.start_threads(threads, startEvent.set):
Serhiy Storchaka263dcd22015-04-01 13:01:14 +030054 pass
55 ok = sum(t.ok_count for t in threads)
56 errors = [str(t.name) + str(t.errors.getvalue())
57 for t in threads if t.error_count]
Guido van Rossumd8faa362007-04-27 19:54:29 +000058
59 msg = "Errors: errors %d ok %d\n%s" % (len(errors), ok,
60 '\n'.join(errors))
Ezio Melottib3aedd42010-11-20 19:04:17 +000061 self.assertEqual(errors, [], msg)
62 self.assertEqual(ok, NUM_THREADS * FILES_PER_THREAD)
Guido van Rossumd8faa362007-04-27 19:54:29 +000063
Tim Peters9fadfb02001-01-13 03:04:02 +000064if __name__ == "__main__":
Serhiy Storchaka263dcd22015-04-01 13:01:14 +030065 unittest.main()