在我的代码中,我task.LoopingCall()
习惯每秒运行一些延迟函数。我想确保该函数为一定数量的事物返回正确的值。所以,我想我可以使用 atask.clock()
并调用advance()
它的方法。但是,我没有得到正确数量的预期响应。
知道我做错了什么吗?
这是一个测试代码来说明我的意思。首先是服务器:
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
from twisted.internet import task
import time
class Chat(LineReceiver):
def __init__(self):
self.echo = None
def connectionMade(self):
self.echo = task.LoopingCall(self.echo_print)
self.echo.start(1)
def connectionLost(self, reason='whatever'):
if self.echo is not None and self.echo.running:
self.echo.stop()
def lineReceived(self, line):
if line == 'stop':
self.echo.stop()
def echo_print (self):
self.sendLine("Echo")
class ChatFactory(Factory):
def __init__(self):
pass
def buildProtocol(self, addr):
return Chat()
if __name__ == "__main__":
reactor.listenTCP(8123, ChatFactory())
reactor.run()
现在是测试用例:
from twisted.internet import task, base
from twisted.trial import unittest
from twisted.test import proto_helpers
from chat import ChatFactory
class TestChat (unittest.TestCase):
def setUp (self):
self.factory = ChatFactory()
self.clock = task.Clock()
self.proto = self.factory.buildProtocol(('127.0.0.1', 0))
self.tr = proto_helpers.StringTransport()
self.proto.callLater = self.clock.callLater
self.proto.makeConnection(self.tr)
def tearDown (self):
if self.proto:
self.proto.connectionLost()
def test_echo (self):
self.proto.dataReceived('ook\n')
seconds_elapsed = 5
self.clock.advance(seconds_elapsed)
expected = 'Echo\r\n' * seconds_elapsed
self.assertEqual(self.tr.value(), expected)
当我对此运行 py.test 时,我得到:
E FailTest: not equal:
E a = 'Echo\r\n'
E b = 'Echo\r\nEcho\r\nEcho\r\nEcho\r\nEcho\r\n'
请注意,添加import time; time.sleep(5)
确实使测试通过。所以,我怀疑问题是task.clock
没有正确使用。