本文整理汇总了Python中twisted.test.proto_helpers.StringTransport.value方法的典型用法代码示例。如果您正苦于以下问题:Python StringTransport.value方法的具体用法?Python StringTransport.value怎么用?Python StringTransport.value使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.test.proto_helpers.StringTransport
的用法示例。
在下文中一共展示了StringTransport.value方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: FingerTestCase
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
class FingerTestCase(unittest.TestCase):
"""
Tests for L{finger.Finger}.
"""
def setUp(self):
"""
Create and connect a L{finger.Finger} instance.
"""
self.transport = StringTransport()
self.protocol = finger.Finger()
self.protocol.makeConnection(self.transport)
def test_simple(self):
"""
When L{finger.Finger} receives a CR LF terminated line, it responds
with the default user status message - that no such user exists.
"""
self.protocol.dataReceived("moshez\r\n")
self.assertEqual(
self.transport.value(),
"Login: moshez\nNo such user\n")
def test_simpleW(self):
"""
The behavior for a query which begins with C{"/w"} is the same as the
behavior for one which does not. The user is reported as not existing.
"""
self.protocol.dataReceived("/w moshez\r\n")
self.assertEqual(
self.transport.value(),
"Login: moshez\nNo such user\n")
def test_forwarding(self):
"""
When L{finger.Finger} receives a request for a remote user, it responds
with a message rejecting the request.
"""
self.protocol.dataReceived("[email protected]\r\n")
self.assertEqual(
self.transport.value(),
"Finger forwarding service denied\n")
def test_list(self):
"""
When L{finger.Finger} receives a blank line, it responds with a message
rejecting the request for all online users.
"""
self.protocol.dataReceived("\r\n")
self.assertEqual(
self.transport.value(),
"Finger online list denied\n")
示例2: PlayerTest
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
class PlayerTest(unittest.TestCase):
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())
def testSend(self):
self.player.send("Hi\n")
self.assertEquals(self.transport.value(), "Hi\n")
self.player.send(("Hi", "\n"))
self.assertEquals(self.transport.value(), "Hi\nHi\n")
self.player.send(["Hi", "\n"])
self.assertEquals(self.transport.value(), "Hi\nHi\nHi\n")
self.player.send(i for i in ("Hi", "\n"))
self.assertEquals(self.transport.value(), "Hi\nHi\nHi\nHi\n")
def testDisconnect(self):
self.player.proto.terminal = None
self.player.disconnect()
self.assertIdentical(self.actor.getIntelligence(), None)
def test_ambiguity(self):
"""
When the player refers to something ambiguously, the error message
should enumerate the objects in question.
"""
for color in [u'red', u'green', u'blue']:
it = objects.Thing(store=self.store, name=u'%s thing' % (color,))
it.moveTo(self.room)
self.player.parse("take thing")
self.assertEquals(self.transport.value(),
"> take thing\n"
"Could you be more specific? When you said 'thing', "
"did you mean: a red thing, a green thing, "
"or a blue thing?\r\n")
示例3: test_client_requires_trailing_slashes
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def test_client_requires_trailing_slashes(self):
"""
If a connection is made to a client but the client rejects it due to
requiring a trailing slash. We need to retry the request with a
trailing slash. Workaround for Synapse <= v0.99.3, explained in #3622.
"""
d = self.cl.get_json("testserv:8008", "foo/bar", try_trailing_slash_on_400=True)
# Send the request
self.pump()
# there should have been a call to connectTCP
clients = self.reactor.tcpClients
self.assertEqual(len(clients), 1)
(_host, _port, factory, _timeout, _bindAddress) = clients[0]
# complete the connection and wire it up to a fake transport
client = factory.buildProtocol(None)
conn = StringTransport()
client.makeConnection(conn)
# that should have made it send the request to the connection
self.assertRegex(conn.value(), b"^GET /foo/bar")
# Clear the original request data before sending a response
conn.clear()
# Send the HTTP response
client.dataReceived(
b"HTTP/1.1 400 Bad Request\r\n"
b"Content-Type: application/json\r\n"
b"Content-Length: 59\r\n"
b"\r\n"
b'{"errcode":"M_UNRECOGNIZED","error":"Unrecognized request"}'
)
# We should get another request with a trailing slash
self.assertRegex(conn.value(), b"^GET /foo/bar/")
# Send a happy response this time
client.dataReceived(
b"HTTP/1.1 200 OK\r\n"
b"Content-Type: application/json\r\n"
b"Content-Length: 2\r\n"
b"\r\n"
b'{}'
)
# We should get a successful response
r = self.successResultOf(d)
self.assertEqual(r, {})
示例4: WebSocketClientStandaloneTestCase
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
class WebSocketClientStandaloneTestCase(unittest.TestCase):
"""
Tests for L{WebSocketClient}, not requiring a server.
"""
def setUp(self):
client = TestClientWithExtraHeaders("ws://foo/bar")
self.transport = StringTransport()
client.makeConnection(self.transport)
def test_HandshakeHeaders(self):
data = self.transport.value().split("\r\n")
req = data.pop(0)
self.assertEqual(req, "GET /bar HTTP/1.1")
self.assertIn("Host: foo:80", data)
self.assertIn("Connection: Upgrade", data)
self.assertIn("Origin: http://foo", data)
self.assertIn("Sec-WebSocket-Version: 13", data)
self.assertIn("Baz: bam", data)
self.assertEqual(data[-1], "")
self.assertEqual(len(data), 9)
key = [l for l in data if l.startswith("Sec-WebSocket-Key")]
self.assertEqual(len(key), 1)
## Just test the length of the key
self.assertEqual(len(key[0].split(":")[1].lstrip()), 24)
示例5: _versionTest
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def _versionTest(self, serverVersionResponse):
"""
Test L{NotificationClient} version negotiation.
"""
self.client.factory.userHandle = "foo"
transport = StringTransport()
self.client.makeConnection(transport)
self.assertEquals(
transport.value(), "VER 1 MSNP8 CVR0\r\n")
transport.clear()
self.client.dataReceived(serverVersionResponse)
self.assertEquals(
transport.value(),
"CVR 2 0x0409 win 4.10 i386 MSNMSGR 5.0.0544 MSMSGS foo\r\n")
示例6: test03_make_echo_with_collector
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def test03_make_echo_with_collector(self):
"""
Test with correct handler used in the package.
- Get the request from server
- Sending the same response
"""
clock = Clock()
sessions = Sessions(False, 10, clock)
trigger = DummyTrigger()
factory = GatheringFactory()
collector = Collector(sessions)
factory.protocol.set_handler(collector)
factory.protocol.set_trigger(trigger)
protocol = factory.buildProtocol(("127.0.0.1", 0))
transport = StringTransport()
protocol.makeConnection(transport)
protocol.dataReceived("hello")
uid, ip, data = collector.get()
collector.release(uid, data)
self.assertEqual(transport.value(), "hello")
示例7: test_incompleteUsername
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def test_incompleteUsername(self):
"""
Test that a login attempt using a username without a domain part
results in a customized authentication failure message which points
out that a domain part should be included in the username.
"""
mta = mail.MailTransferAgent(store=self.store)
installOn(mta, self.store)
factory = mta.getFactory()
protocol = factory.buildProtocol(("192.168.1.1", 12345))
transport = StringTransport()
transport.getHost = lambda: IPv4Address("TCP", "192.168.1.1", 54321)
transport.getPeer = lambda: IPv4Address("TCP", "192.168.1.1", 12345)
protocol.makeConnection(transport)
protocol.dataReceived("EHLO example.net\r\n")
protocol.dataReceived("AUTH LOGIN\r\n")
protocol.dataReceived("testuser".encode("base64") + "\r\n")
transport.clear()
protocol.dataReceived("password".encode("base64") + "\r\n")
written = transport.value()
protocol.connectionLost(failure.Failure(error.ConnectionDone()))
self.assertEquals(
written,
"535 Authentication failure [Username without domain name (ie "
'"yourname" instead of "[email protected]") not allowed; try '
"with a domain name.]\r\n",
)
示例8: testCookieHeaderParsing
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def testCookieHeaderParsing(self):
factory = client.HTTPClientFactory(b'http://foo.example.com/')
proto = factory.buildProtocol('127.42.42.42')
transport = StringTransport()
proto.makeConnection(transport)
for line in [
b'200 Ok',
b'Squash: yes',
b'Hands: stolen',
b'Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT',
b'Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/',
b'Set-Cookie: SHIPPING=FEDEX; path=/foo',
b'',
b'body',
b'more body',
]:
proto.dataReceived(line + b'\r\n')
self.assertEqual(transport.value(),
b'GET / HTTP/1.0\r\n'
b'Host: foo.example.com\r\n'
b'User-Agent: Twisted PageGetter\r\n'
b'\r\n')
self.assertEqual(factory.cookies,
{
b'CUSTOMER': b'WILE_E_COYOTE',
b'PART_NUMBER': b'ROCKET_LAUNCHER_0001',
b'SHIPPING': b'FEDEX',
})
示例9: test_earlyHeaders
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def test_earlyHeaders(self):
"""
When a connection is made, L{HTTPPagerGetter} sends the headers from
its factory's C{headers} dict. If I{Host} or I{Content-Length} is
present in this dict, the values are not sent, since they are sent with
special values before the C{headers} dict is processed. If
I{User-Agent} is present in the dict, it overrides the value of the
C{agent} attribute of the factory. If I{Cookie} is present in the
dict, its value is added to the values from the factory's C{cookies}
attribute.
"""
factory = client.HTTPClientFactory(
b'http://foo/bar',
agent=b"foobar",
cookies={b'baz': b'quux'},
postdata=b"some data",
headers={
b'Host': b'example.net',
b'User-Agent': b'fooble',
b'Cookie': b'blah blah',
b'Content-Length': b'12981',
b'Useful': b'value'})
transport = StringTransport()
protocol = client.HTTPPageGetter()
protocol.factory = factory
protocol.makeConnection(transport)
result = transport.value()
for expectedHeader in [
b"Host: example.net\r\n",
b"User-Agent: foobar\r\n",
b"Content-Length: 9\r\n",
b"Useful: value\r\n",
b"connection: close\r\n",
b"Cookie: blah blah; baz=quux\r\n"]:
self.assertIn(expectedHeader, result)
示例10: test_acceptSenderAddress
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def test_acceptSenderAddress(self):
"""
Test that a C{MAIL FROM} command with an acceptable address is
responded to with the correct success code.
"""
class AcceptanceDelivery(NotImplementedDelivery):
"""
Delivery object which accepts all senders as valid.
"""
def validateFrom(self, helo, origin):
return origin
realm = SingletonRealm(smtp.IMessageDelivery, AcceptanceDelivery())
portal = Portal(realm, [AllowAnonymousAccess()])
proto = smtp.SMTP()
proto.portal = portal
trans = StringTransport()
proto.makeConnection(trans)
# Deal with the necessary preliminaries
proto.dataReceived('HELO example.com\r\n')
trans.clear()
# Try to specify our sender address
proto.dataReceived('MAIL FROM:<[email protected]>\r\n')
# Clean up the protocol before doing anything that might raise an
# exception.
proto.connectionLost(error.ConnectionLost())
# Make sure that we received exactly the correct response
self.assertEqual(
trans.value(),
'250 Sender address accepted\r\n')
示例11: test_portalRejectedAnonymousSender
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def test_portalRejectedAnonymousSender(self):
"""
Test that a C{MAIL FROM} command issued without first authenticating
when a portal has been configured to disallow anonymous logins is
responded to with the correct error code.
"""
realm = SingletonRealm(smtp.IMessageDelivery, NotImplementedDelivery())
portal = Portal(realm, [])
proto = smtp.SMTP()
proto.portal = portal
trans = StringTransport()
proto.makeConnection(trans)
# Deal with the necessary preliminaries
proto.dataReceived('HELO example.com\r\n')
trans.clear()
# Try to specify our sender address
proto.dataReceived('MAIL FROM:<[email protected]>\r\n')
# Clean up the protocol before doing anything that might raise an
# exception.
proto.connectionLost(error.ConnectionLost())
# Make sure that we received exactly the correct response
self.assertEqual(
trans.value(),
'550 Cannot receive from specified address '
'<[email protected]>: Unauthenticated senders not allowed\r\n')
示例12: _test
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def _test(self, factory, testvalue):
transport = StringTransport()
protocol = client.ScrapyHTTPPageGetter()
protocol.factory = factory
protocol.makeConnection(transport)
self.assertEqual(transport.value(), testvalue)
return testvalue
示例13: MockClient
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
class MockClient(Client):
factory = MockFactory()
def __init__(self):
Client.__init__(self)
self.transport = StringTransport()
self.makeConnection(self.transport)
def connectionMade(self):
self.host = self.transport.getHost().host
self.server_host = 'testing_srv'
def dataReceived(self, data):
LineOnlyReceiver.dataReceived(self, data)
def t_get_data(self):
return self.transport.value()
def t_flush_data(self):
self.transport.clear()
def t_send_lines(self, *lines):
lines = '\n'.join(lines)
self.dataReceived(lines + '\n')
def t_send_line(self, line):
self.dataReceived(line + '\n')
示例14: test_transfer
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def test_transfer(self):
"""
An attempt is made to transfer the zone for the domain the
L{SecondaryAuthority} was constructed with from the server address it
was constructed with when L{SecondaryAuthority.transfer} is called.
"""
secondary = SecondaryAuthority.fromServerAddressAndDomain(
('192.168.1.2', 1234), 'example.com')
secondary._reactor = reactor = MemoryReactorClock()
secondary.transfer()
# Verify a connection attempt to the server address above
host, port, factory, timeout, bindAddress = reactor.tcpClients.pop(0)
self.assertEqual(host, '192.168.1.2')
self.assertEqual(port, 1234)
# See if a zone transfer query is issued.
proto = factory.buildProtocol((host, port))
transport = StringTransport()
proto.makeConnection(transport)
msg = Message()
# DNSProtocol.writeMessage length encodes the message by prepending a
# 2 byte message length to the buffered value.
msg.decode(StringIO(transport.value()[2:]))
self.assertEqual(
[dns.Query('example.com', dns.AXFR, dns.IN)], msg.queries)
示例15: testCookieHeaderParsing
# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import value [as 别名]
def testCookieHeaderParsing(self):
factory = client.HTTPClientFactory(b"http://foo.example.com/")
proto = factory.buildProtocol("127.42.42.42")
transport = StringTransport()
proto.makeConnection(transport)
for line in [
b"200 Ok",
b"Squash: yes",
b"Hands: stolen",
b"Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT",
b"Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/",
b"Set-Cookie: SHIPPING=FEDEX; path=/foo",
b"",
b"body",
b"more body",
]:
proto.dataReceived(line + b"\r\n")
self.assertEqual(
transport.value(),
b"GET / HTTP/1.0\r\n" b"Host: foo.example.com\r\n" b"User-Agent: Twisted PageGetter\r\n" b"\r\n",
)
self.assertEqual(
factory.cookies,
{b"CUSTOMER": b"WILE_E_COYOTE", b"PART_NUMBER": b"ROCKET_LAUNCHER_0001", b"SHIPPING": b"FEDEX"},
)