2020import signal
2121import textwrap
2222
23+ from unittest import mock
2324from test import lock_tests
2425from test import support
2526
@@ -86,6 +87,33 @@ def tearDown(self):
8687
8788class ThreadTests (BaseTestCase ):
8889
90+ @cpython_only
91+ def test_name (self ):
92+ def func (): pass
93+
94+ thread = threading .Thread (name = "myname1" )
95+ self .assertEqual (thread .name , "myname1" )
96+
97+ # Convert int name to str
98+ thread = threading .Thread (name = 123 )
99+ self .assertEqual (thread .name , "123" )
100+
101+ # target name is ignored if name is specified
102+ thread = threading .Thread (target = func , name = "myname2" )
103+ self .assertEqual (thread .name , "myname2" )
104+
105+ with mock .patch .object (threading , '_counter' , return_value = 2 ):
106+ thread = threading .Thread (name = "" )
107+ self .assertEqual (thread .name , "Thread-2" )
108+
109+ with mock .patch .object (threading , '_counter' , return_value = 3 ):
110+ thread = threading .Thread ()
111+ self .assertEqual (thread .name , "Thread-3" )
112+
113+ with mock .patch .object (threading , '_counter' , return_value = 5 ):
114+ thread = threading .Thread (target = func )
115+ self .assertEqual (thread .name , "Thread-5 (func)" )
116+
89117 # Create a bunch of threads, let each do some work, wait until all are
90118 # done.
91119 def test_various_ops (self ):
@@ -531,7 +559,7 @@ def test_main_thread_after_fork_from_nonmain_thread(self):
531559 import os, threading, sys
532560 from test import support
533561
534- def f ():
562+ def func ():
535563 pid = os.fork()
536564 if pid == 0:
537565 main = threading.main_thread()
@@ -544,14 +572,14 @@ def f():
544572 else:
545573 support.wait_process(pid, exitcode=0)
546574
547- th = threading.Thread(target=f )
575+ th = threading.Thread(target=func )
548576 th.start()
549577 th.join()
550578 """
551579 _ , out , err = assert_python_ok ("-c" , code )
552580 data = out .decode ().replace ('\r ' , '' )
553581 self .assertEqual (err , b"" )
554- self .assertEqual (data , "Thread-1\n True\n True\n " )
582+ self .assertEqual (data , "Thread-1 (func) \n True\n True\n " )
555583
556584 def test_main_thread_during_shutdown (self ):
557585 # bpo-31516: current_thread() should still point to the main thread
0 commit comments