Here are the examples of the python api twisted.test.proto_helpers.StringTransport taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
131 Examples
3
Example 1
Project: mythbox Source File: test_tls.py
def test_makeConnection(self):
"""
When L{TLSMemoryBIOProtocol} is connected to a transport, it connects
the protocol it wraps to a transport.
"""
clientProtocol = Protocol()
clientFactory = ClientFactory()
clientFactory.protocol = lambda: clientProtocol
contextFactory = ClientContextFactory()
wrapperFactory = TLSMemoryBIOFactory(
contextFactory, True, clientFactory)
sslProtocol = wrapperFactory.buildProtocol(None)
transport = StringTransport()
sslProtocol.makeConnection(transport)
self.assertNotIdentical(clientProtocol.transport, None)
self.assertNotIdentical(clientProtocol.transport, transport)
3
Example 2
Project: mythbox Source File: test_protocols.py
def test_lineTooLong(self):
"""
Test sending a line too long: it should close the connection.
"""
t = proto_helpers.StringTransport()
a = LineOnlyTester()
a.makeConnection(t)
res = a.dataReceived('x'*200)
self.assertIsInstance(res, error.ConnectionLost)
3
Example 3
def makeProto(self, *a, **kw):
protoClass = kw.pop('_protoClass', client.SOCKS5Client)
fac = FakeSOCKS5ClientFactory(*a, **kw)
fac.protocol = protoClass
proto = fac.buildProtocol(None)
transport = proto_helpers.StringTransport()
transport.abortConnection = lambda: None
proto.makeConnection(transport)
return fac, proto
3
Example 4
Project: mythbox Source File: test_telnet.py
def test_requestNegotiationEscapesIAC(self):
"""
If the payload for a subnegotiation includes I{IAC}, it is escaped by
L{telnet.Telnet.requestNegotiation} with another I{IAC}.
See RFC 855.
"""
transport = proto_helpers.StringTransport()
self.protocol.makeConnection(transport)
self.protocol.requestNegotiation('\x01', '\xff')
self.assertEqual(
transport.value(),
'\xff\xfa\x01\xff\xff\xff\xf0')
3
Example 5
Project: txmsgpackrpc Source File: test_protocol.py
def setUp(self):
factory = EchoServerFactory(True)
self.proto = factory.buildProtocol(("127.0.0.1", 0))
self.transport = proto_helpers.StringTransport()
self.proto.makeConnection(self.transport)
self.packer = msgpack.Packer(encoding="utf-8")
3
Example 6
Project: twitty-twister Source File: test_streaming.py
def setUp(self):
self.objects = []
self.transport = proto_helpers.StringTransport()
self.clock = task.Clock()
self.protocol = TestableTwitterStream(self.clock, self.objects.append)
self.protocol.makeConnection(self.transport)
3
Example 7
def test_discard(self):
"""
Test wire.Discard protocol.
"""
t = proto_helpers.StringTransport()
a = wire.Discard()
a.makeConnection(t)
a.dataReceived("hello")
a.dataReceived("world")
a.dataReceived("how")
a.dataReceived("are")
a.dataReceived("you")
self.assertEqual(t.value(), "")
3
Example 8
Project: imaginary Source File: test_wiring.py
def test_connectionMadePrompt(self):
"""
L{CharacterSelectionTextServer} prompts the player upon connection,
giving them the option to create a character.
"""
testWorld = buildWorld(self)
transport = StringTransport()
terminal = ServerProtocol(lambda: testWorld.proto)
terminal.makeConnection(transport)
self.assertIn("0) Create", transport.io.getvalue())
3
Example 9
Project: mythbox Source File: test_protocols.py
def test_noUnicode(self):
"""
Test that L{proto_helpers.StringTransport} doesn't accept unicode data.
"""
s = proto_helpers.StringTransport()
self.assertRaises(TypeError, s.write, u'foo')
3
Example 10
Project: txmongo Source File: test_cancel.py
def test_protocol_connectionReady(self):
proto = MongoProtocol()
d1 = proto.connectionReady()
d2 = proto.connectionReady()
d1.cancel()
with AssertCallbackNotCalled(d1):
proto.makeConnection(proto_helpers.StringTransport())
self.assertTrue(d2.called)
self.failureResultOf(d1, defer.CancelledError)
3
Example 11
def setUp(self):
self.underlyingTransport = StringTransport()
self.pt = insults.ServerProtocol()
self.p = recvline.HistoricRecvLine()
self.pt.protocolFactory = lambda: self.p
self.pt.factory = self
self.pt.makeConnection(self.underlyingTransport)
3
Example 12
Project: mythbox Source File: test_default.py
def test_signDataWithAgent(self):
"""
When connected to an agent, L{SSHUserAuthClient} can use it to
request signatures of particular data with a particular L{Key}.
"""
client = SSHUserAuthClient("user", ConchOptions(), None)
agent = SSHAgentClient()
transport = StringTransport()
agent.makeConnection(transport)
client.keyAgent = agent
cleartext = "Sign here"
client.signData(self.rsaPublic, cleartext)
self.assertEquals(
transport.value(),
"\x00\x00\x00\x8b\r\x00\x00\x00u" + self.rsaPublic.blob() +
"\x00\x00\x00\t" + cleartext +
"\x00\x00\x00\x00")
3
Example 13
Project: crossbar Source File: test_unisocket.py
def test_invalid_status_line(self):
"""
Not speaking RawSocket but also not speaking a type of HTTP will cause
the connection to be dropped.
"""
t = StringTransport()
f = UniSocketServerFactory()
p = f.buildProtocol(None)
p.makeConnection(t)
t.protocol = p
self.assertTrue(t.connected)
p.dataReceived(b'this is not HTTP\r\n\r\n')
self.assertFalse(t.connected)
3
Example 14
Project: mythbox Source File: test_protocol.py
def test_cancelConnectUNIXTimeout(self):
"""
L{ClientCreator.connectUNIX} inserts a very short delayed call between
the time the connection is established and the time the L{Deferred}
returned from one of its connect methods actually fires. If the
L{Deferred} is cancelled in this interval, the established connection is
closed, the timeout is cancelled, and the L{Deferred} fails with
L{CancelledError}.
"""
def connect(reactor, cc):
d = cc.connectUNIX('/foo/bar')
address, factory, timeout, bindAddress = reactor.unixClients.pop()
protocol = factory.buildProtocol(None)
transport = StringTransport()
protocol.makeConnection(transport)
return d
return self._cancelConnectTimeoutTest(connect)
3
Example 15
Project: imaginary Source File: test_player.py
def setUp(self):
self.store = store.Store()
self.bob = objects.Thing(store=self.store, name=u"bob")
self.room = objects.Thing(store=self.store, name=u"a place")
roomContainer = Container.createFor(self.room, capacity=1000)
self.bob.moveTo(roomContainer)
self.actor = objects.Actor.createFor(self.bob)
self.player = player.Player(self.bob)
self.player.useColors = False
from twisted.test.proto_helpers import StringTransport
self.transport = StringTransport()
class Protocol:
write = self.transport.write
self.player.setProtocol(Protocol())
3
Example 16
def testSuccess(self):
p = TestIdentServer()
p.makeConnection(StringTransport())
L = []
p.sendLine = L.append
p.resultValue = ('SYS', 'USER')
p.lineReceived('123, 456')
self.assertEquals(L[0], '123, 456 : USERID : SYS : USER')
3
Example 17
Project: txjason Source File: test_netstring.py
def setUp(self):
self.factory = JSONRPCServerFactory()
self.factory.addHandler(TestHandler(), 'foo')
self.proto = self.factory.buildProtocol(('127.0.0.1', 0))
self.tr = proto_helpers.StringTransport()
self.proto.makeConnection(self.tr)
self.client = client.JSONRPCClient()
3
Example 18
def test_who(self):
"""
Test wire.Who protocol.
"""
t = proto_helpers.StringTransport()
a = wire.Who()
a.makeConnection(t)
self.assertEquals(t.value(), "root\r\n")
3
Example 19
def test_sendInitialized(self):
"""
Test send when the stream has been initialized.
The data should be sent directly over the XML stream.
"""
factory = xmlstream.XmlStreamFactory(xmlstream.Authenticator())
sm = subprotocols.StreamManager(factory)
xs = factory.buildProtocol(None)
xs.transport = proto_helpers.StringTransport()
xs.connectionMade()
xs.dataReceived(b"<stream:stream xmlns='jabber:client' "
b"xmlns:stream='http://etherx.jabber.org/streams' "
b"from='example.com' id='12345'>")
xs.dispatch(xs, "//event/stream/authd")
sm.send("<presence/>")
self.assertEquals(b"<presence/>", xs.transport.value())
3
Example 20
def test_buffer(self):
"""
Test that when strings are received in chunks of different lengths,
they are still parsed correctly.
"""
for packet_size in range(1, 10):
t = proto_helpers.StringTransport()
a = TestNetstring()
a.MAX_LENGTH = 699
a.makeConnection(t)
for s in self.strings:
a.sendString(s)
out = t.value()
for i in range(len(out)/packet_size + 1):
s = out[i*packet_size:(i+1)*packet_size]
if s:
a.dataReceived(s)
self.assertEquals(a.received, self.strings)
3
Example 21
def makeProto(self, *a, **kw):
fac = self.factory(*a, **kw)
proto = fac.buildProtocol(None)
transport = proto_helpers.StringTransport()
transport.abortConnection = lambda: self.aborted.append(True)
proto.makeConnection(transport)
return fac, proto
3
Example 22
def connect(self, fac):
self.factory = fac
if self.deferred:
return self.deferred
if self.failure:
return defer.fail(self.failure)
self.proto = fac.buildProtocol(None)
transport = proto_helpers.StringTransport()
self.aborted = []
transport.abortConnection = lambda: self.aborted.append(True)
self.tlsStarts = []
transport.startTLS = lambda ctx: self.tlsStarts.append(ctx)
self.proto.makeConnection(transport)
self.transport = transport
return defer.succeed(self.proto)
3
Example 23
def test_sendNotInitialized(self):
"""
Test send when the stream is connected but not yet initialized.
The data should be cached until the XML stream has been initialized.
"""
factory = xmlstream.XmlStreamFactory(xmlstream.Authenticator())
sm = subprotocols.StreamManager(factory)
xs = factory.buildProtocol(None)
xs.transport = proto_helpers.StringTransport()
xs.connectionMade()
xs.dataReceived(b"<stream:stream xmlns='jabber:client' "
b"xmlns:stream='http://etherx.jabber.org/streams' "
b"from='example.com' id='12345'>")
sm.send("<presence/>")
self.assertEquals(b"", xs.transport.value())
self.assertEquals("<presence/>", sm._packetQueue[0])
3
Example 24
def setUp(self):
"""
Create a L{cftp.StdioClient} hooked up to dummy transport and a fake
user database.
"""
class Connection:
pass
conn = Connection()
conn.transport = StringTransport()
conn.transport.localClosed = False
self.client = cftp.StdioClient(conn)
self.database = self.client._pwd = UserDatabase()
# Intentionally bypassing makeConnection - that triggers some code
# which uses features not provided by our dumb Connection fake.
self.client.transport = StringTransport()
3
Example 25
def test_consumer(self):
# a local producer sends data to a consuming Transit object
c = transit.Connection(None, None, None, "description")
c.transport = proto_helpers.StringTransport()
records = []
c.send_record = records.append
producer = proto_helpers.StringTransport()
c.registerProducer(producer, True)
self.assertIs(c.transport.producer, producer)
c.write(b"r1.")
self.assertEqual(records, [b"r1."])
c.unregisterProducer()
self.assertEqual(c.transport.producer, None)
3
Example 26
Project: mythbox Source File: test_manhole.py
def test_interruptResetsInterpreterBuffer(self):
"""
L{manhole.Manhole.handle_INT} should cause the interpreter input buffer
to be reset.
"""
transport = StringTransport()
terminal = insults.ServerProtocol(manhole.Manhole)
terminal.makeConnection(transport)
protocol = terminal.terminalProtocol
interpreter = protocol.interpreter
interpreter.buffer.extend(["1", "2"])
protocol.handle_INT()
self.assertFalse(interpreter.buffer)
3
Example 27
def setUp(self):
self.transport = StringTransport()
self.proto = Mock()
self.parser = ClientProtocol(lambda: self.proto)
self.parser.factory = self
self.parser.makeConnection(self.transport)
result = self.assertCall(occurrences(self.proto).pop(0), "makeConnection", (self.parser,))
self.failIf(occurrences(result))
3
Example 28
Project: crossbar Source File: test_unisocket.py
def test_web_with_no_factory(self):
"""
Trying to speak HTTP without a factory will drop the connection.
"""
t = StringTransport()
f = UniSocketServerFactory()
p = f.buildProtocol(None)
p.makeConnection(t)
t.protocol = p
self.assertTrue(t.connected)
p.dataReceived(b'GET /foo HTTP/1.1\r\n\r\n')
self.assertFalse(t.connected)
3
Example 29
Project: mythbox Source File: test_telnet.py
def test_requestNegotiation(self):
"""
L{telnet.Telnet.requestNegotiation} formats the feature byte and the
payload bytes into the subnegotiation format and sends them.
See RFC 855.
"""
transport = proto_helpers.StringTransport()
self.protocol.makeConnection(transport)
self.protocol.requestNegotiation('\x01', '\x02\x03')
self.assertEqual(
transport.value(),
# IAC SB feature bytes IAC SE
'\xff\xfa\x01\x02\x03\xff\xf0')
3
Example 30
Project: scrapy Source File: test_webclient.py
def _test(self, factory, testvalue):
transport = StringTransport()
protocol = client.ScrapyHTTPPageGetter()
protocol.factory = factory
protocol.makeConnection(transport)
self.assertEqual(
set(transport.value().splitlines()),
set(testvalue.splitlines()))
return testvalue
3
Example 31
Project: mythbox Source File: test_protocol.py
def test_cancelConnectTCPTimeout(self):
"""
L{ClientCreator.connectTCP} inserts a very short delayed call between
the time the connection is established and the time the L{Deferred}
returned from one of its connect methods actually fires. If the
L{Deferred} is cancelled in this interval, the established connection is
closed, the timeout is cancelled, and the L{Deferred} fails with
L{CancelledError}.
"""
def connect(reactor, cc):
d = cc.connectTCP('example.com', 1234)
host, port, factory, timeout, bindAddress = reactor.tcpClients.pop()
protocol = factory.buildProtocol(None)
transport = StringTransport()
protocol.makeConnection(transport)
return d
return self._cancelConnectTimeoutTest(connect)
3
Example 32
Project: crossbar Source File: test_unisocket.py
def test_websocket_with_no_map(self):
"""
A web request that matches no WebSocket
"""
t = StringTransport()
websocket_map = {u"x": None, u"y": None}
f = UniSocketServerFactory(websocket_factory_map=websocket_map)
p = f.buildProtocol(None)
p.makeConnection(t)
t.protocol = p
self.assertTrue(t.connected)
p.dataReceived(b'GET /ws HTTP/1.1\r\nConnection: close\r\n\r\n')
self.assertFalse(t.connected)
self.assertEqual(t.value(), b"")
3
Example 33
Project: mythbox Source File: test_protocol.py
def test_cancelConnectSSLTimeout(self):
"""
L{ClientCreator.connectSSL} inserts a very short delayed call between
the time the connection is established and the time the L{Deferred}
returned from one of its connect methods actually fires. If the
L{Deferred} is cancelled in this interval, the established connection is
closed, the timeout is cancelled, and the L{Deferred} fails with
L{CancelledError}.
"""
def connect(reactor, cc):
d = cc.connectSSL('example.com', 1234, object())
host, port, factory, contextFactory, timeout, bindADdress = reactor.sslClients.pop()
protocol = factory.buildProtocol(None)
transport = StringTransport()
protocol.makeConnection(transport)
return d
return self._cancelConnectTimeoutTest(connect)
3
Example 34
def setUp(self):
factory = xmlstream.XmlStreamFactory(xmlstream.Authenticator())
self.clock = task.Clock()
self.streamManager = subprotocols.StreamManager(factory, self.clock)
self.xmlstream = factory.buildProtocol(None)
self.transport = proto_helpers.StringTransport()
self.xmlstream.transport = self.transport
self.request = IQGetStanza()
3
Example 35
def setUp(self):
"""
Create and connect a L{finger.Finger} instance.
"""
self.transport = StringTransport()
self.protocol = finger.Finger()
self.protocol.makeConnection(self.transport)
3
Example 36
Project: txjason Source File: test_netstring.py
def connect(self, fac):
if self.deferred:
return self.deferred
if self.fail:
return defer.fail(FakeError())
self.proto = fac.buildProtocol(None)
self.transport = proto_helpers.StringTransport()
self.transport.abortConnection = self.transport.loseConnection = (
lambda: self.disconnect(FakeDisconnectedError()))
self.proto.makeConnection(self.transport)
self.connected = True
return defer.succeed(self.proto)
3
Example 37
def test_QOTD(self):
"""
Test wire.QOTD protocol.
"""
t = proto_helpers.StringTransport()
a = wire.QOTD()
a.makeConnection(t)
self.assertEquals(t.value(),
"An apple a day keeps the doctor away.\r\n")
3
Example 38
Project: imaginary Source File: test_runner.py
def test_consoleTextServer(self):
"""
L{ConsoleTextServer.connectionMade} sets the protocol of its player to
itself.
"""
leader, follower = makeTerminal(self)
store = Store()
world = ImaginaryWorld(store=store)
actor = world.create(u"player")
setTerminalSize(leader, 234, 567)
player = Player(actor)
textServer = ConsoleTextServer(player, follower)
terminalProtocol = ServerProtocol(lambda: textServer)
self.assertIdentical(player.proto, None)
terminalProtocol.makeConnection(StringTransport())
self.assertIdentical(player.proto, textServer)
self.assertEqual(textServer.width, 567)
self.assertEqual(textServer.height, 234)
3
Example 39
Project: mythbox Source File: test_protocols.py
def test_echo(self):
"""
Test wire.Echo protocol: send some data and check it send it back.
"""
t = proto_helpers.StringTransport()
a = wire.Echo()
a.makeConnection(t)
a.dataReceived("hello")
a.dataReceived("world")
a.dataReceived("how")
a.dataReceived("are")
a.dataReceived("you")
self.assertEquals(t.value(), "helloworldhowareyou")
3
Example 40
Project: carbon Source File: test_client.py
def setUp(self):
carbon_client.settings = TestSettings() # reset to defaults
factory = CarbonPickleClientFactory(('127.0.0.1', 2003, 'a'))
self.protocol = factory.buildProtocol(('127.0.0.1', 2003))
self.transport = StringTransport()
self.protocol.makeConnection(self.transport)
3
Example 41
def test_buffer(self):
"""
Test buffering over line protocol: data received should match buffer.
"""
t = proto_helpers.StringTransport()
a = LineOnlyTester()
a.makeConnection(t)
for c in self.buffer:
a.dataReceived(c)
self.assertEquals(a.received, self.buffer.split('\n')[:-1])
3
Example 42
def setUp(self):
self.output = []
class MyService(object):
pass
self.service = MyService()
self.service.defaultDomain = self.receiving
self.service.domains = [self.receiving, 'pubsub.'+self.receiving]
self.service.secret = self.secret
self.authenticator = server.XMPPServerListenAuthenticator(self.service)
self.xmlstream = xmlstream.XmlStream(self.authenticator)
self.xmlstream.send = self.output.append
self.xmlstream.transport = StringTransport()
3
Example 43
def getProtocol(self):
"""
Return a new instance of C{self.protocol} connected to a new instance
of L{proto_helpers.StringTransport}.
"""
t = proto_helpers.StringTransport()
a = self.protocol()
a.makeConnection(t)
return a
3
Example 44
def makeProto(self, *a, **kw):
protoClass = kw.pop('_protoClass', client.SOCKS4Client)
fac = FakeSOCKS4ClientFactory(*a, **kw)
fac.protocol = protoClass
proto = fac.buildProtocol(None)
transport = proto_helpers.StringTransport()
transport.abortConnection = lambda: None
proto.makeConnection(transport)
return fac, proto
3
Example 45
Project: txmongo Source File: test_cancel.py
def test_protocol_query(self):
tr = proto_helpers.StringTransport()
proto = MongoProtocol()
proto.makeConnection(tr)
d = proto.send_QUERY(Query(query={'x': 42}))
d.cancel()
with AssertCallbackNotCalled(d):
reply = Reply(response_to=1, docuements=[{'x': 42}])
reply_bin = struct.pack("<iiiiqii", 1, *reply[2:8]) + b''.join(reply.docuements)
reply_bin = struct.pack('<i', len(reply_bin) + 4) + reply_bin
proto.dataReceived(reply_bin)
self.failureResultOf(d, defer.CancelledError)
3
Example 46
Project: airpnp Source File: test_airplayservice.py
def setUp(self):
self.apserver = IAirPlayServerMock()
service = AirPlayService(self.apserver, "test")
service.deviceid = "01:00:17:44:60:d2"
self.apserver.features = 0x77
self.proto = http.HTTPChannel()
self.proto.requestFactory = server.Request
self.proto.site = server.Site(service.create_site())
self.proto.makeConnection(StringTransport())
3
Example 47
Project: wokkel Source File: test_server.py
def setUp(self):
self.service = FakeService()
self.factory = server.XMPPS2SServerFactory(self.service)
self.xmlstream = self.factory.buildProtocol(None)
self.transport = StringTransport()
self.xmlstream.thisEntity = jid.JID('example.org')
self.xmlstream.otherEntity = jid.JID('example.com')
3
Example 48
Project: pyrollbar Source File: test_twisted.py
def setUp(self):
rollbar.init(TOKEN, 'twisted-test')
factory = SquareFactory()
self.proto = factory.buildProtocol(('127.0.0.1', 0))
self.tr = proto_helpers.StringTransport()
self.proto.makeConnection(self.tr)
3
Example 49
Project: crossbar Source File: test_unisocket.py
def test_rawsocket_with_no_factory(self):
"""
Trying to speak RawSocket with no RawSocket factory configured will
drop the connection.
"""
t = StringTransport()
f = UniSocketServerFactory()
p = f.buildProtocol(None)
p.makeConnection(t)
t.protocol = p
self.assertTrue(t.connected)
p.dataReceived(b'\x7F0000000')
self.assertFalse(t.connected)
3
Example 50
def test_nextLine(self):
"""
L{ServerProtocol.nextLine} writes C{"\r\n"} to its transport.
"""
# Why doesn't it write ESC E? Because ESC E is poorly supported. For
# example, gnome-terminal (many different versions) fails to scroll if
# it receives ESC E and the cursor is already on the last row.
protocol = ServerProtocol()
transport = StringTransport()
protocol.makeConnection(transport)
protocol.nextLine()
self.assertEqual(transport.value(), "\r\n")