当前位置: 首页>>代码示例>>Python>>正文


Python StringTransport.clear方法代码示例

本文整理汇总了Python中twisted.test.proto_helpers.StringTransport.clear方法的典型用法代码示例。如果您正苦于以下问题:Python StringTransport.clear方法的具体用法?Python StringTransport.clear怎么用?Python StringTransport.clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.test.proto_helpers.StringTransport的用法示例。


在下文中一共展示了StringTransport.clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_portalRejectedAnonymousSender

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [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')
开发者ID:Almad,项目名称:twisted,代码行数:31,代码来源:test_smtp.py

示例2: test_incompleteUsername

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [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",
        )
开发者ID:pombredanne,项目名称:quotient,代码行数:30,代码来源:test_mta.py

示例3: MockClient

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [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')

        
开发者ID:BrendanBenshoof,项目名称:ChordRelayChat,代码行数:30,代码来源:mock_client.py

示例4: test_acceptSenderAddress

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [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')
开发者ID:Almad,项目名称:twisted,代码行数:36,代码来源:test_smtp.py

示例5: test_stop_pinging_on_connection_lost

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [as 别名]
 def test_stop_pinging_on_connection_lost(self):
     """
     When the protocol loses its connection, it stops trying to send
     ``NoOp`` commands.
     """
     reactor = Clock()
     protocol = self.build_protocol(reactor)
     transport = StringTransport()
     protocol.makeConnection(transport)
     transport.clear()
     protocol.connectionLost(Failure(ConnectionDone("test, simulated")))
     reactor.advance(PING_INTERVAL.total_seconds())
     self.assertEqual(b"", transport.value())
开发者ID:stmcginnis,项目名称:flocker,代码行数:15,代码来源:test_protocol.py

示例6: test_client_requires_trailing_slashes

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [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, {})
开发者ID:matrix-org,项目名称:synapse,代码行数:53,代码来源:test_fedclient.py

示例7: _versionTest

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [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")
开发者ID:Almad,项目名称:twisted,代码行数:18,代码来源:test_msn.py

示例8: WorkerProtocolTests

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [as 别名]
class WorkerProtocolTests(TestCase):
    """
    Tests for L{WorkerProtocol}.
    """

    def setUp(self):
        """
        Set up a transport, a result stream and a protocol instance.
        """
        self.serverTransport = StringTransport()
        self.clientTransport = StringTransport()
        self.server = WorkerProtocol()
        self.server.makeConnection(self.serverTransport)
        self.client = FakeAMP()
        self.client.makeConnection(self.clientTransport)


    def test_run(self):
        """
        Calling the L{workercommands.Run} command on the client returns a
        response with C{success} sets to C{True}.
        """
        d = self.client.callRemote(workercommands.Run, testCase="doesntexist")

        def check(result):
            self.assertTrue(result['success'])

        d.addCallback(check)
        self.server.dataReceived(self.clientTransport.value())
        self.clientTransport.clear()
        self.client.dataReceived(self.serverTransport.value())
        self.serverTransport.clear()
        return d


    def test_start(self):
        """
        The C{start} command changes the current path.
        """
        curdir = os.path.realpath(os.path.curdir)
        self.addCleanup(os.chdir, curdir)
        self.server.start('..')
        self.assertNotEqual(os.path.realpath(os.path.curdir), curdir)
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:45,代码来源:test_worker.py

示例9: WsClientSendingTestCase

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [as 别名]
class WsClientSendingTestCase(unittest.TestCase):
    def setUp(self):
        self.transport = StringTransport()
        self.handler = Handler()
        self.factory = WebSocketFactory(self.handler)
    
    def test_buildProtocol(self):
        proto = self.factory.buildProtocol(None)
        self.assertIsInstance(proto, WebSocketDeviceHiveProtocol)
    
    def test_send_message(self):
        # testing headers sending
        # this should result in connected event

        proto = self.factory.buildProtocol(None)
        proto.makeConnection(self.transport)

        origin = ''.join((
            'GET /device HTTP/1.1\r\n',
            'Host: localhost\r\n',
            'Upgrade: websocket\r\n',
            'Connection: Upgrade\r\n',
            'Sec-WebSocket-Key: {0}\r\n'.format(proto.socket.security_key),
            'Origin: http://localhost\r\n',
            'Sec-WebSocket-Protocol: device-hive, devicehive\r\n',
            'Sec-WebSocket-Version: 13\r\n\r\n',
        ))
        self.assertEquals(origin, self.transport.value())

        proto.dataReceived('HTTP/1.1 101 OK\r\n\r\n')
        self.assertTrue(self.handler.is_connected)

        self.transport.clear()
        # testing message sending
        proto.socket.rand = Random(1)
        defer = self.factory.send_message({'test': True})
        self.assertIsInstance(defer, Deferred)
        self.assertEquals('{{"test": true, "requestId": {0}}}'.format(max(proto.msg_callbacks.keys())), decode_ws_message(self.transport.value()))
        self.assertFalse(defer.called)
        # testing message response
        request_id = max(proto.msg_callbacks.keys())
        proto.socket.frame_received(WS_OPCODE_TEXT_FRAME, '{{"requestId":{0},"done":1}}'.format(request_id))
        self.assertTrue(defer.called)
开发者ID:FirstCypress,项目名称:LiV,代码行数:45,代码来源:test_wsdev.py

示例10: test_buffer

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [as 别名]
    def test_buffer(self):
        """
        Exercise a lot of the SMTP client code.  This is a "shotgun" style unit
        test.  It does a lot of things and hopes that something will go really
        wrong if it is going to go wrong.  This test should be replaced with a
        suite of nicer tests.
        """
        transport = StringTransport()
        a = self.serverClass()
        class fooFactory:
            domain = 'foo.com'

        a.factory = fooFactory()
        a.makeConnection(transport)
        for (send, expect, msg, msgexpect) in self.data:
            if send:
                a.dataReceived(send)
            data = transport.value()
            transport.clear()
            if not re.match(expect, data):
                raise AssertionError, (send, expect, data)
            if data[:3] == '354':
                for line in msg.splitlines():
                    if line and line[0] == '.':
                        line = '.' + line
                    a.dataReceived(line + '\r\n')
                a.dataReceived('.\r\n')
                # Special case for DATA. Now we want a 250, and then
                # we compare the messages
                data = transport.value()
                transport.clear()
                resp, msgdata = msgexpect
                if not re.match(resp, data):
                    raise AssertionError, (resp, data)
                for recip in msgdata[2]:
                    expected = list(msgdata[:])
                    expected[2] = [recip]
                    self.assertEquals(
                        a.message[(recip,)],
                        tuple(expected)
                    )
        a.setTimeout(None)
开发者ID:Almad,项目名称:twisted,代码行数:44,代码来源:test_smtp.py

示例11: test_client_does_not_retry_on_400_plus

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [as 别名]
    def test_client_does_not_retry_on_400_plus(self):
        """
        Another test for trailing slashes but now test that we don't retry on
        trailing slashes on a non-400/M_UNRECOGNIZED response.

        See test_client_requires_trailing_slashes() for context.
        """
        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 404 Not Found\r\n"
            b"Content-Type: application/json\r\n"
            b"Content-Length: 2\r\n"
            b"\r\n"
            b"{}"
        )

        # We should not get another request
        self.assertEqual(conn.value(), b"")

        # We should get a 404 failure response
        self.failureResultOf(d)
开发者ID:matrix-org,项目名称:synapse,代码行数:44,代码来源:test_fedclient.py

示例12: encode

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [as 别名]
def encode(bananaFactory, obj):
    """
    Banana encode an object using L{banana.Banana.sendEncoded}.

    @param bananaFactory: A no-argument callable which will return a new,
        unconnected protocol instance to use to do the encoding (this should
        most likely be a L{banana.Banana} instance).

    @param obj: The object to encode.
    @type obj: Any type supported by Banana.

    @return: A L{bytes} instance giving the encoded form of C{obj}.
    """
    transport = StringTransport()
    banana = bananaFactory()
    banana.makeConnection(transport)
    transport.clear()

    banana.sendEncoded(obj)
    return transport.value()
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:22,代码来源:test_banana.py

示例13: test_incompleteUsername

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [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.
        """
        factory = POP3ServerFactory(self.portal)
        protocol = factory.buildProtocol(('192.168.1.1', 12345))
        transport = StringTransport()
        protocol.makeConnection(transport)
        protocol.dataReceived("USER testuser\r\n")
        transport.clear()
        protocol.dataReceived("PASS password\r\n")
        written = transport.value()
        protocol.connectionLost(Failure(ConnectionDone()))

        self.assertEquals(
            written,
            '-ERR Username without domain name (ie "yourname" instead of '
            '"[email protected]") not allowed; try with a domain name.\r\n')
开发者ID:pombredanne,项目名称:quotient,代码行数:22,代码来源:test_popout.py

示例14: test_challenge

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [as 别名]
    def test_challenge(self):
        """
        L{NotificationClient} responds to a I{CHL} message by sending a I{QRY}
        back which included a hash based on the parameters of the I{CHL}.
        """
        transport = StringTransport()
        self.client.makeConnection(transport)
        transport.clear()

        challenge = "15570131571988941333"
        self.client.dataReceived('CHL 0 ' + challenge + '\r\n')
        # md5 of the challenge and a magic string defined by the protocol
        response = "8f2f5a91b72102cd28355e9fc9000d6e"
        # Sanity check - the response is what the comment above says it is.
        self.assertEquals(
            response, md5(challenge + "Q1P7W2E4J9R8U3S5").hexdigest())
        self.assertEquals(
            transport.value(),
            # 2 is the next transaction identifier.  32 is the length of the
            # response.
            "QRY 2 [email protected] 32\r\n" + response)
开发者ID:Almad,项目名称:twisted,代码行数:23,代码来源:test_msn.py

示例15: test_portalRejectedSenderAddress

# 需要导入模块: from twisted.test.proto_helpers import StringTransport [as 别名]
# 或者: from twisted.test.proto_helpers.StringTransport import clear [as 别名]
    def test_portalRejectedSenderAddress(self):
        """
        Test that a C{MAIL FROM} command with an address rejected by an
        L{smtp.SMTP} instance's portal is responded to with the correct error
        code.
        """
        class DisallowAnonymousAccess(object):
            """
            Checker for L{IAnonymous} which rejects authentication attempts.
            """
            implements(ICredentialsChecker)

            credentialInterfaces = (IAnonymous,)

            def requestAvatarId(self, credentials):
                return defer.fail(UnauthorizedLogin())

        realm = SingletonRealm(smtp.IMessageDelivery, NotImplementedDelivery())
        portal = Portal(realm, [DisallowAnonymousAccess()])
        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]>: Sender not acceptable\r\n')
开发者ID:Almad,项目名称:twisted,代码行数:42,代码来源:test_smtp.py


注:本文中的twisted.test.proto_helpers.StringTransport.clear方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。