• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python proto_helpers.StringTransport类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: test_pid

 def test_pid(self):
     """
     Should have the same pid as the transport.
     """
     p = Channel3Protocol('joe', None, MagicMock())
     self.assertEqual(p.pid, None)
     t = StringTransport()
     t.pid = 23
     p.makeConnection(t)
     self.assertEqual(p.pid, 23)
开发者ID:hagna,项目名称:mold,代码行数:10,代码来源:test_process.py


示例17: FingerTestCase

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")
开发者ID:0004c,项目名称:VTK,代码行数:55,代码来源:test_finger.py


示例18: require

def require(packageName, fixName):
    if (packageName, fixName) in _alreadyInstalled:
        return

    if (packageName, fixName) == ("twisted", "filepath_copyTo"):
        from twisted.python import filepath

        if filepath.FilePath("a") != filepath.FilePath("a"):
            from vmc.contrib.epsilon.hotfixes import filepath_copyTo

            filepath_copyTo.install()
    elif (packageName, fixName) == ("twisted", "timeoutmixin_calllater"):
        from twisted.protocols import policies

        if not hasattr(policies.TimeoutMixin, "callLater"):
            from vmc.contrib.epsilon.hotfixes import timeoutmixin_calllater

            timeoutmixin_calllater.install()
    elif (packageName, fixName) == ("twisted", "delayedcall_seconds"):
        from twisted.internet import base

        args = inspect.getargs(base.DelayedCall.__init__.func_code)[0]
        if "seconds" not in args:
            from vmc.contrib.epsilon.hotfixes import delayedcall_seconds

            delayedcall_seconds.install()
    elif (packageName, fixName) == ("twisted", "deferredgenerator_tfailure"):
        from twisted.internet import defer

        result = []

        def test():
            d = defer.waitForDeferred(defer.succeed(1))
            yield d
            result.append(d.getResult())

        defer.deferredGenerator(test)()
        if result == [1]:
            from vmc.contrib.epsilon.hotfixes import deferredgenerator_tfailure

            deferredgenerator_tfailure.install()
        else:
            assert result == [None]
    elif (packageName, fixName) == ("twisted", "proto_helpers_stringtransport"):
        from twisted.test.proto_helpers import StringTransport

        st = StringTransport()
        try:
            st.write(u"foo")
        except TypeError, e:
            pass
        else:
            from vmc.contrib.epsilon.hotfixes import proto_helpers_stringtransport

            proto_helpers_stringtransport.install()
开发者ID:mrader11,项目名称:vodafone-mobile-connect,代码行数:55,代码来源:hotfix.py


示例19: PlayerTest

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")
开发者ID:ashfall,项目名称:imaginary,代码行数:54,代码来源:test_player.py


示例20: write

    def write(self, data):
        """Write some data"""
        StringTransport.write(self, data)
        if not self.done:
            if "\r\n\r\n" in self.value():
                self.done = True
                self.reply_func(self.value())

        else:
            if self.remote_func is not None:
                self.remote_func(self.value())
开发者ID:magicicada-bot,项目名称:magicicada-protocol,代码行数:11,代码来源:test_proxy_tunnel.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python proto_helpers.StringTransportWithDisconnection类代码示例发布时间:2022-05-27
下一篇:
Python proto_helpers.MemoryReactor类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap