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


Python proto_helpers.StringTransport类代码示例

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


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

示例1: test_acceptSenderAddress

    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,代码行数:34,代码来源:test_smtp.py

示例2: test_earlyHeaders

 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)
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:35,代码来源:test_webclient.py

示例3: testCookieHeaderParsing

 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"},
     )
开发者ID:ragercool,项目名称:twisted,代码行数:25,代码来源:test_webclient.py

示例4: test_transfer

    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)
开发者ID:ali-hallaji,项目名称:twisted,代码行数:29,代码来源:test_names.py

示例5: setUp

    def setUp(self):
        """
        Set up a store with a location, a player and an observer.
        """
        self.store = store.Store()
        locContainer = createLocation(
            self.store, u"Test Location", u"Location for testing.")
        self.location = locContainer.thing
        self.world = ImaginaryWorld(store=self.store, origin=self.location)
        self.player = self.world.create(
            u"Test Player", gender=self.genderForTest)
        self.playerContainer = iimaginary.IContainer(self.player)
        self.playerWrapper = player.Player(self.player)

        self.playerWrapper.useColors = False
        locContainer.add(self.player)
        self.transport = StringTransport()
        self.playerWrapper.setProtocol(PlayerProtocol(self.transport))

        self.observer = self.world.create(
            u"Observer Player", gender=language.Gender.FEMALE)
        self.observerWrapper = player.Player(self.observer)
        locContainer.add(self.observer)
        self.otransport = StringTransport()
        self.observerWrapper.setProtocol(PlayerProtocol(self.otransport))

        # Clear the transport, since we don't care about the observer
        # arrival event.
        self.transport.clear()
开发者ID:glyph,项目名称:imaginary,代码行数:29,代码来源:commandutils.py

示例6: testCookieHeaderParsing

 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',
         })
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:28,代码来源:test_webclient.py

示例7: setUp

    def setUp(self):
        """
        Set up a store with a location, a player and an observer.
        """
        self.store = store.Store()

        self.location = objects.Thing(
            store=self.store,
            name=u"Test Location",
            description=u"Location for testing.",
            proper=True)

        locContainer = objects.Container.createFor(self.location, capacity=1000)

        self.world = ImaginaryWorld(store=self.store, origin=self.location)
        self.player = self.world.create(
            u"Test Player", gender=language.Gender.FEMALE)
        self.playerContainer = iimaginary.IContainer(self.player)
        self.playerWrapper = player.Player(self.player)

        self.playerWrapper.useColors = False
        locContainer.add(self.player)
        self.transport = StringTransport()
        self.playerWrapper.setProtocol(PlayerProtocol(self.transport))

        self.observer = self.world.create(
            u"Observer Player", gender=language.Gender.FEMALE)
        self.observerWrapper = player.Player(self.observer)
        locContainer.add(self.observer)
        self.otransport = StringTransport()
        self.observerWrapper.setProtocol(PlayerProtocol(self.otransport))

        # Clear the transport, since we don't care about the observer
        # arrival event.
        self.transport.clear()
开发者ID:rcarmo,项目名称:divmod.org,代码行数:35,代码来源:commandutils.py

示例8: MockClient

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,代码行数:28,代码来源:mock_client.py

示例9: _test

 def _test(self, factory, testvalue):
     transport = StringTransport()
     protocol = client.ScrapyHTTPPageGetter()
     protocol.factory = factory
     protocol.makeConnection(transport)
     self.assertEqual(transport.value(), testvalue)
     return testvalue
开发者ID:bihicheng,项目名称:scrapy,代码行数:7,代码来源:test_webclient.py

示例10: test_portalRejectedAnonymousSender

    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,代码行数:29,代码来源:test_smtp.py

示例11: test03_make_echo_with_collector

    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")
开发者ID:inkhey,项目名称:mmc,代码行数:30,代码来源:server.py

示例12: _test

 def _test(self, factory, testvalue):
     transport = StringTransport()
     protocol = client.pyrakeHTTPPageGetter()
     protocol.factory = factory
     protocol.makeConnection(transport)
     self.assertEqual(
         set(transport.value().splitlines()),
         set(testvalue.splitlines()))
     return testvalue
开发者ID:elkingtowa,项目名称:pyrake,代码行数:9,代码来源:test_webclient.py

示例13: request

    def request(self, method, uri, headers=None, bodyProducer=None):
        """
        Implement IAgent.request.
        """
        # We want to use Agent to parse the HTTP response, so let's ask it to
        # make a request against our in-memory reactor.
        response = self._realAgent.request(method, uri, headers, bodyProducer)

        # That will try to establish an HTTP connection with the reactor's
        # connectTCP method, and MemoryReactor will place Agent's factory into
        # the tcpClients list.  We'll extract that.
        host, port, factory, timeout, bindAddress = (
            self._memoryReactor.tcpClients[0])

        # Then we need to convince that factory it's connected to something and
        # it will give us a protocol for that connection.
        protocol = factory.buildProtocol(None)

        # We want to capture the output of that connection so we'll make an
        # in-memory transport.
        clientTransport = AbortableStringTransport()

        # When the protocol is connected to a transport, it ought to send the
        # whole request because callers of this should not use an asynchronous
        # bodyProducer.
        protocol.makeConnection(clientTransport)

        # Get the data from the request.
        requestData = clientTransport.io.getvalue()

        # Now time for the server to do its job.  Ask it to build an HTTP
        # channel.
        channel = get_site(self._rootResource).buildProtocol(None)

        # Connect the channel to another in-memory transport so we can collect
        # the response.
        serverTransport = StringTransport()
        serverTransport.hostAddr = IPv4Address('TCP', '127.0.0.1', 80)
        channel.makeConnection(serverTransport)

        # Feed it the data that the Agent synthesized.
        channel.dataReceived(requestData)

        # Tell it that the connection is now complete so it can clean up.
        channel.connectionLost(Failure(ConnectionDone()))

        # Now we have the response data, let's give it back to the Agent.
        protocol.dataReceived(serverTransport.io.getvalue())

        # By now the Agent should have all it needs to parse a response.
        protocol.connectionLost(Failure(ConnectionDone()))

        # Return the response in the accepted format (Deferred firing
        # IResponse).  This should be synchronously fired, and if not, it's the
        # system under test's problem.
        return response
开发者ID:BenjamenMeyer,项目名称:mimic,代码行数:56,代码来源:helpers.py

示例14: setUp

 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)
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:10,代码来源:test_worker.py

示例15: test_init

 def test_init(self):
     """
     Initialize it with a chunk of stdin.
     """
     p = SimpleProtocol('foo')
     t = StringTransport()            
     t.closeStdin = Mock()
     p.makeConnection(t)
     self.assertEqual(t.value(), 'foo')
     self.assertTrue(t.closeStdin.called)
开发者ID:hagna,项目名称:mold,代码行数:10,代码来源:test_process.py


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