使用线程和测试进行网络Ping
我正在尝试用线程来对两个不同的网络进行ping测试。我能够得到我想要的响应,但我想把它转换成一个测试。我下面有我尝试过的代码,但测试运行器说没有测试被执行。代码如下:
#!/home/workspace/downloads/Python-2.6.4/python
from threading import Thread
import subprocess, unittest
from Queue import Queue
class TestPing(unittest.TestCase):
num_threads = 4
queue = Queue()
ips = ["10.51.54.100", "10.51.54.122"]
#wraps system ping command
def RunTest(i, q):
"""Pings subnet"""
while True:
ip = q.get()
print "Thread %s: Pinging %s" % (i, ip)
ret = subprocess.call("ping -c 1 %s" % ip,
shell=True,
stdout=open('/dev/null', 'w'),
stderr=subprocess.STDOUT)
if ret == 0:
print "%s: is alive" % ip
assert True
else:
print "%s: did not respond" % ip
assert False
q.task_done()
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=pinger, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Place work in queue
for ip in ips:
queue.put(ip)
#Wait until worker threads are done to exit
queue.join()
class PingTestSuite(unittest.TestSuite):
def makePingTestSuite():
suite = unittest.TestSuite()
suite.addTest(TestPingMove("TestPing"))
return suite
def suite():
return unittest.makeSuite(TestPing)
if __name__ == '__main__':
unittest.main()
我希望测试能够判断网络是否有响应,如果没有响应就返回假,并且对这两个网络各进行一次测试。有没有人知道我哪里出错了?
1 个回答
3
当你创建一个继承自 unittest.TestCase
的类时,所有以 test
开头的方法会自动被执行。否则,这段代码就不会被当作测试来运行。(所以 RunTest
这个方法不会被执行)。
如果你把 RunTest
改成(虽然名字不太好听的) test_RunTest
:
class TestPing(unittest.TestCase):
def test_RunTest(self):
add code here
那么这段代码就会被执行。另外,unittest
期望 test_RunTest
的第一个也是唯一的参数是 self
。
如果你想测试 func(args)
是否会抛出错误,可以使用 self.assertRaises
,像这样:
self.assertRaises(AssertionError, func, args)
或者,如果 func
返回的是 True
或 False
,你可以用 self.assertTrue
或 self.assertFalse
来检查返回的值是否正确。
此外,当你写单元测试时,最好把所有的函数和类放在一个模块里,然后在单元测试脚本中导入这个模块,再测试这些函数是否返回你预期的结果或者是否抛出错误。我可能理解错了,但看起来你现在把这两部分混在一起了。