我正在学习Python中的线程,并且认为单元测试符合我的需要。
以这个multithreading.htm作为我的起点。但是,当我在函数中使用time.sleep()时,测试似乎从该代码块返回。
import unittest
import thread
import time
class Test(unittest.TestCase):
def test_threads(self):
thread.start_new_thread(self.print_time, ("Thread 1", 1))
def print_time(self, threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % (threadName, time.ctime(time.time()))
if __name__ == "__main__":
unittest.main()使用此代码将不会输出任何结果。摆脱time.sleep(延迟)输出:
Thread 1: Mon Aug 03 11:36:56 2015
Thread 1: Mon Aug 03 11:36:56 2015
Thread 1: Mon Aug 03 11:36:56 2015
Thread 1: Mon Aug 03 11:36:56 2015
Thread 1: Mon Aug 03 11:36:56 2015当我在Python中使用单元测试时,如何使用time.sleep()?
发布于 2015-08-03 17:09:53
您所看到的行为是因为您的脚本在线程有机会打印其输出之前就已经结束了。根据文档的说法,在“警告”下:
当主线程退出时,系统将定义其他线程是否存活。
所以很可能你的线程在它的第一次睡眠()中被杀死了。即使线程能够存活下来,我也怀疑您是否会在同一文档中看到ouput:
当主线程退出时。没有刷新标准的I/O文件。
如果没有您的time.sleep(delay),显然在脚本完成之前,print就已经准备好了。
解决这一问题的一种简单方法是让您的测试方法for ()完成子线程所需的时间,因此要将测试方法替换为
def test_threads(self):
Thread(target = self.print_time, args = ("Thread 1", 1)).start()
time.sleep(6)不过,通常情况下,您会将Threading模块用于这类工作。当您使用它以非守护进程模式(默认)启动线程时,调用线程只在它启动的所有线程完成之后才停止。
发布于 2015-08-03 12:15:32
嗯。我得到的和你一样。
你可以试着用threading.Thread()代替吗?
代码:
import unittest
from threading import Thread
import time
class Test(unittest.TestCase):
def test_threads(self):
Thread(target = self.print_time, args = ("Thread 1", 1)).start()
def print_time(self, threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % (threadName, time.ctime(time.time()))
if __name__ == "__main__":
unittest.main()输出:
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Thread 1: Mon Aug 03 13:07:46 2015
Thread 1: Mon Aug 03 13:07:47 2015
Thread 1: Mon Aug 03 13:07:48 2015
Thread 1: Mon Aug 03 13:07:49 2015
Thread 1: Mon Aug 03 13:07:50 2015不过,请注意,测试在线程完成之前完成。
https://stackoverflow.com/questions/31784081
复制相似问题