Python asyncio.Transport() Examples

The following are 30 code examples of asyncio.Transport(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module asyncio , or try the search function .
Example #1
Source File: __init__.py    From python-insteonplm with MIT License 6 votes vote down vote up
def _connect_serial(self):
        try:
            if self._hub_version == 1:
                url = "socket://{}:{}".format(self._host, self._port)
                _LOGGER.info("Connecting to Insteon Hub v1 on %s", url)
                # pylint: disable=unused-variable
                transport, protocol = await create_serial_connection(
                    self._loop, lambda: self.protocol, url, baudrate=19200
                )
            else:
                _LOGGER.info("Connecting to PLM on %s", self._device)
                # pylint: disable=unused-variable
                transport, protocol = await create_serial_connection(
                    self._loop, lambda: self.protocol, self._device, baudrate=19200
                )
            self._closed = False
        except OSError:
            self._closed = True
        return not self._closed


# Hub version 1 (2242) is untested using the HTTP Transport.
# It is tested using the PLM socket interface on port 9761.
# pylint: disable=too-many-instance-attributes 
Example #2
Source File: test_xmppserver.py    From bumper with GNU General Public License v3.0 6 votes vote down vote up
def test_ping_server(*args, **kwargs):
    test_transport = asyncio.Transport()
    test_transport.get_extra_info = mock.Mock(return_value=mock_transport_extra_info())
    test_transport.write = mock.Mock(return_value=return_send_data)
    xmppclient = bumper.xmppserver.XMPPAsyncClient(test_transport)
    xmppclient.state = xmppclient.READY  # Set client state to READY
    xmppclient.uid = "E0000000000000001234"
    xmppclient.devclass = "159"
    mock_send = xmppclient.send = mock.Mock(side_effect=return_send_data)

    # Ping from bot
    test_data = '<iq xmlns:ns0="urn:xmpp:ping" from="E000BVTNX18700260382@159.ecorobot.net/atom" id="2542" to="159.ecorobot.net" type="get"><ping /></iq>'.encode(
        "utf-8"
    )
    xmppclient._parse_data(test_data)

    assert (
        mock_send.mock_calls[0].args[0]
        == '<iq type="result" id="2542" from="159.ecorobot.net" />'
    )  # ping response 
Example #3
Source File: test_events.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_create_datagram_endpoint_sock(self):
        sock = None
        local_address = ('127.0.0.1', 0)
        infos = self.loop.run_until_complete(
            self.loop.getaddrinfo(
                *local_address, type=socket.SOCK_DGRAM))
        for family, type, proto, cname, address in infos:
            try:
                sock = socket.socket(family=family, type=type, proto=proto)
                sock.setblocking(False)
                sock.bind(address)
            except:
                pass
            else:
                break
        else:
            assert False, 'Can not create socket.'

        f = self.loop.create_connection(
            lambda: MyDatagramProto(loop=self.loop), sock=sock)
        tr, pr = self.loop.run_until_complete(f)
        self.assertIsInstance(tr, asyncio.Transport)
        self.assertIsInstance(pr, MyDatagramProto)
        tr.close()
        self.loop.run_until_complete(pr.done) 
Example #4
Source File: tcp_helpers.py    From Galaxy_Plugin_Bethesda with MIT License 6 votes vote down vote up
def tcp_cork(transport: asyncio.Transport, value: bool) -> None:
    sock = transport.get_extra_info('socket')

    if CORK is None:
        return

    if sock is None:
        return

    if sock.family not in (socket.AF_INET, socket.AF_INET6):
        return

    value = bool(value)

    with suppress(OSError):
        sock.setsockopt(
            socket.IPPROTO_TCP, CORK, value) 
Example #5
Source File: test_transports.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_flowcontrol_mixin_set_write_limits(self):

        class MyTransport(transports._FlowControlMixin,
                          transports.Transport):

            def get_write_buffer_size(self):
                return 512

        loop = mock.Mock()
        transport = MyTransport(loop=loop)
        transport._protocol = mock.Mock()

        self.assertFalse(transport._protocol_paused)

        with self.assertRaisesRegex(ValueError, 'high.*must be >= low'):
            transport.set_write_buffer_limits(high=0, low=1)

        transport.set_write_buffer_limits(high=1024, low=128)
        self.assertFalse(transport._protocol_paused)
        self.assertEqual(transport.get_write_buffer_limits(), (128, 1024))

        transport.set_write_buffer_limits(high=256, low=128)
        self.assertTrue(transport._protocol_paused)
        self.assertEqual(transport.get_write_buffer_limits(), (128, 256)) 
Example #6
Source File: client.py    From lbry-sdk with MIT License 6 votes vote down vote up
def __init__(self, loop: asyncio.AbstractEventLoop, peer_timeout: typing.Optional[float] = 10,
                 connection_manager: typing.Optional['ConnectionManager'] = None):
        self.loop = loop
        self.peer_port: typing.Optional[int] = None
        self.peer_address: typing.Optional[str] = None
        self.transport: typing.Optional[asyncio.Transport] = None
        self.peer_timeout = peer_timeout
        self.connection_manager = connection_manager
        self.writer: typing.Optional['HashBlobWriter'] = None
        self.blob: typing.Optional['AbstractBlob'] = None

        self._blob_bytes_received = 0
        self._response_fut: typing.Optional[asyncio.Future] = None
        self.buf = b''

        # this is here to handle the race when the downloader is closed right as response_fut gets a result
        self.closed = asyncio.Event(loop=self.loop) 
Example #7
Source File: test_events.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_create_datagram_endpoint_sock(self):
        sock = None
        local_address = ('127.0.0.1', 0)
        infos = self.loop.run_until_complete(
            self.loop.getaddrinfo(
                *local_address, type=socket.SOCK_DGRAM))
        for family, type, proto, cname, address in infos:
            try:
                sock = socket.socket(family=family, type=type, proto=proto)
                sock.setblocking(False)
                sock.bind(address)
            except:
                pass
            else:
                break
        else:
            assert False, 'Can not create socket.'

        f = self.loop.create_connection(
            lambda: MyDatagramProto(loop=self.loop), sock=sock)
        tr, pr = self.loop.run_until_complete(f)
        self.assertIsInstance(tr, asyncio.Transport)
        self.assertIsInstance(pr, MyDatagramProto)
        tr.close()
        self.loop.run_until_complete(pr.done) 
Example #8
Source File: test_transports.py    From annotated-py-projects with MIT License 6 votes vote down vote up
def test_flowcontrol_mixin_set_write_limits(self):

        class MyTransport(transports._FlowControlMixin,
                          transports.Transport):

            def get_write_buffer_size(self):
                return 512

        loop = mock.Mock()
        transport = MyTransport(loop=loop)
        transport._protocol = mock.Mock()

        self.assertFalse(transport._protocol_paused)

        with self.assertRaisesRegex(ValueError, 'high.*must be >= low'):
            transport.set_write_buffer_limits(high=0, low=1)

        transport.set_write_buffer_limits(high=1024, low=128)
        self.assertFalse(transport._protocol_paused)
        self.assertEqual(transport.get_write_buffer_limits(), (128, 1024))

        transport.set_write_buffer_limits(high=256, low=128)
        self.assertTrue(transport._protocol_paused)
        self.assertEqual(transport.get_write_buffer_limits(), (128, 256)) 
Example #9
Source File: protocol.py    From grpclib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(
        self,
        connection: Connection,
        h2_connection: H2Connection,
        transport: Transport,
        *,
        stream_id: Optional[int] = None,
        wrapper: Optional[Wrapper] = None
    ) -> None:
        self.connection = connection
        self._h2_connection = h2_connection
        self._transport = transport
        self.wrapper = wrapper

        if stream_id is not None:
            self.init_stream(stream_id, self.connection)

        self.window_updated = Event()
        self.headers: Optional['_Headers'] = None
        self.headers_received = Event()
        self.trailers: Optional['_Headers'] = None
        self.trailers_received = Event() 
Example #10
Source File: connector.py    From Galaxy_Plugin_Bethesda with MIT License 6 votes vote down vote up
def _wrap_create_connection(
            self, *args: Any,
            req: 'ClientRequest',
            timeout: 'ClientTimeout',
            client_error: Type[Exception]=ClientConnectorError,
            **kwargs: Any) -> Tuple[asyncio.Transport, ResponseHandler]:
        try:
            with CeilTimeout(timeout.sock_connect):
                return cast(
                    Tuple[asyncio.Transport, ResponseHandler],
                    await self._loop.create_connection(*args, **kwargs))
        except cert_errors as exc:
            raise ClientConnectorCertificateError(
                req.connection_key, exc) from exc
        except ssl_errors as exc:
            raise ClientConnectorSSLError(req.connection_key, exc) from exc
        except OSError as exc:
            raise client_error(req.connection_key, exc) from exc 
Example #11
Source File: test_transports.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_flowcontrol_mixin_set_write_limits(self):

        class MyTransport(transports._FlowControlMixin,
                          transports.Transport):

            def get_write_buffer_size(self):
                return 512

        loop = mock.Mock()
        transport = MyTransport(loop=loop)
        transport._protocol = mock.Mock()

        self.assertFalse(transport._protocol_paused)

        with self.assertRaisesRegex(ValueError, 'high.*must be >= low'):
            transport.set_write_buffer_limits(high=0, low=1)

        transport.set_write_buffer_limits(high=1024, low=128)
        self.assertFalse(transport._protocol_paused)
        self.assertEqual(transport.get_write_buffer_limits(), (128, 1024))

        transport.set_write_buffer_limits(high=256, low=128)
        self.assertTrue(transport._protocol_paused)
        self.assertEqual(transport.get_write_buffer_limits(), (128, 256)) 
Example #12
Source File: test_transports.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_ctor_extra_is_none(self):
        transport = asyncio.Transport()
        self.assertEqual(transport._extra, {}) 
Example #13
Source File: test_transports.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_writelines(self):
        transport = asyncio.Transport()
        transport.write = mock.Mock()

        transport.writelines([b'line1',
                              bytearray(b'line2'),
                              memoryview(b'line3')])
        self.assertEqual(1, transport.write.call_count)
        transport.write.assert_called_with(b'line1line2line3') 
Example #14
Source File: test_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def _basetest_create_connection(self, connection_fut, check_sockname=True):
        tr, pr = self.loop.run_until_complete(connection_fut)
        self.assertIsInstance(tr, asyncio.Transport)
        self.assertIsInstance(pr, asyncio.Protocol)
        self.assertIs(pr.transport, tr)
        if check_sockname:
            self.assertIsNotNone(tr.get_extra_info('sockname'))
        self.loop.run_until_complete(pr.done)
        self.assertGreater(pr.nbytes, 0)
        tr.close() 
Example #15
Source File: test_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_create_connection_sock(self):
        with test_utils.run_test_server() as httpd:
            sock = None
            infos = self.loop.run_until_complete(
                self.loop.getaddrinfo(
                    *httpd.address, type=socket.SOCK_STREAM))
            for family, type, proto, cname, address in infos:
                try:
                    sock = socket.socket(family=family, type=type, proto=proto)
                    sock.setblocking(False)
                    self.loop.run_until_complete(
                        self.loop.sock_connect(sock, address))
                except:
                    pass
                else:
                    break
            else:
                assert False, 'Can not create socket.'

            f = self.loop.create_connection(
                lambda: MyProto(loop=self.loop), sock=sock)
            tr, pr = self.loop.run_until_complete(f)
            self.assertIsInstance(tr, asyncio.Transport)
            self.assertIsInstance(pr, asyncio.Protocol)
            self.loop.run_until_complete(pr.done)
            self.assertGreater(pr.nbytes, 0)
            tr.close() 
Example #16
Source File: test_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def _basetest_create_ssl_connection(self, connection_fut,
                                        check_sockname=True,
                                        peername=None):
        tr, pr = self.loop.run_until_complete(connection_fut)
        self.assertIsInstance(tr, asyncio.Transport)
        self.assertIsInstance(pr, asyncio.Protocol)
        self.assertTrue('ssl' in tr.__class__.__name__.lower())
        self.check_ssl_extra_info(tr, check_sockname, peername)
        self.loop.run_until_complete(pr.done)
        self.assertGreater(pr.nbytes, 0)
        tr.close() 
Example #17
Source File: server.py    From lbry-sdk with MIT License 5 votes vote down vote up
def __init__(self, loop: asyncio.AbstractEventLoop, blob_manager: 'BlobManager', lbrycrd_address: str,
                 idle_timeout: float = 30.0, transfer_timeout: float = 60.0):
        self.loop = loop
        self.blob_manager = blob_manager
        self.idle_timeout = idle_timeout
        self.transfer_timeout = transfer_timeout
        self.server_task: typing.Optional[asyncio.Task] = None
        self.started_listening = asyncio.Event(loop=self.loop)
        self.buf = b''
        self.transport: typing.Optional[asyncio.Transport] = None
        self.lbrycrd_address = lbrycrd_address
        self.peer_address_and_port: typing.Optional[str] = None
        self.started_transfer = asyncio.Event(loop=self.loop)
        self.transfer_finished = asyncio.Event(loop=self.loop)
        self.close_on_idle_task: typing.Optional[asyncio.Task] = None 
Example #18
Source File: test_events.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_create_datagram_endpoint_sock(self):
        if (sys.platform == 'win32' and
                isinstance(self.loop, proactor_events.BaseProactorEventLoop)):
            raise unittest.SkipTest(
                'UDP is not supported with proactor event loops')

        sock = None
        local_address = ('127.0.0.1', 0)
        infos = self.loop.run_until_complete(
            self.loop.getaddrinfo(
                *local_address, type=socket.SOCK_DGRAM))
        for family, type, proto, cname, address in infos:
            try:
                sock = socket.socket(family=family, type=type, proto=proto)
                sock.setblocking(False)
                sock.bind(address)
            except:
                pass
            else:
                break
        else:
            assert False, 'Can not create socket.'

        f = self.loop.create_datagram_endpoint(
            lambda: MyDatagramProto(loop=self.loop), sock=sock)
        tr, pr = self.loop.run_until_complete(f)
        self.assertIsInstance(tr, asyncio.Transport)
        self.assertIsInstance(pr, MyDatagramProto)
        tr.close()
        self.loop.run_until_complete(pr.done) 
Example #19
Source File: tcp.py    From pyrdp with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super().__init__(TCPParser())
        self.connectedEvent = asyncio.Event()
        self.transport: asyncio.Transport = None 
Example #20
Source File: test_transfer_blob.py    From lbry-sdk with MIT License 5 votes vote down vote up
def test_server_chunked_request(self):
        blob_hash = "7f5ab2def99f0ddd008da71db3a3772135f4002b19b7605840ed1034c8955431bd7079549e65e6b2a3b9c17c773073ed"
        server_protocol = BlobServerProtocol(self.loop, self.server_blob_manager, self.server.lbrycrd_address)
        transport = asyncio.Transport(extra={'peername': ('ip', 90)})
        received_data = BytesIO()
        transport.is_closing = lambda: received_data.closed
        transport.write = received_data.write
        server_protocol.connection_made(transport)
        blob_request = BlobRequest.make_request_for_blob_hash(blob_hash).serialize()
        for byte in blob_request:
            server_protocol.data_received(bytes([byte]))
        await asyncio.sleep(0.1)  # yield execution
        self.assertGreater(len(received_data.getvalue()), 0) 
Example #21
Source File: base_protocol.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def connection_made(self, transport: asyncio.BaseTransport) -> None:
        tr = cast(asyncio.Transport, transport)
        tcp_nodelay(tr, True)
        self.transport = tr 
Example #22
Source File: base_protocol.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
        self._loop = loop  # type: asyncio.AbstractEventLoop
        self._paused = False
        self._drain_waiter = None  # type: Optional[asyncio.Future[None]]
        self._connection_lost = False
        self._reading_paused = False

        self.transport = None  # type: Optional[asyncio.Transport] 
Example #23
Source File: tcp_helpers.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def tcp_nodelay(transport: asyncio.Transport, value: bool) -> None:
    sock = transport.get_extra_info('socket')

    if sock is None:
        return

    if sock.family not in (socket.AF_INET, socket.AF_INET6):
        return

    value = bool(value)

    # socket may be closed already, on windows OSError get raised
    with suppress(OSError):
        sock.setsockopt(
            socket.IPPROTO_TCP, socket.TCP_NODELAY, value) 
Example #24
Source File: tcp_helpers.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def tcp_keepalive(
            transport: asyncio.Transport) -> None:  # pragma: no cover
        pass 
Example #25
Source File: http_websocket.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def __init__(self, protocol: BaseProtocol, transport: asyncio.Transport, *,
                 use_mask: bool=False, limit: int=DEFAULT_LIMIT,
                 random: Any=random.Random(),
                 compress: int=0, notakeover: bool=False) -> None:
        self.protocol = protocol
        self.transport = transport
        self.use_mask = use_mask
        self.randrange = random.randrange
        self.compress = compress
        self.notakeover = notakeover
        self._closing = False
        self._limit = limit
        self._output_size = 0
        self._compressobj = None  # type: Any  # actually compressobj 
Example #26
Source File: connector.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def transport(self) -> Optional[asyncio.Transport]:
        if self._protocol is None:
            return None
        return self._protocol.transport 
Example #27
Source File: web_server.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def __init__(self,
                 handler: _RequestHandler,
                 *,
                 request_factory: Optional[_RequestFactory]=None,
                 loop: Optional[asyncio.AbstractEventLoop]=None,
                 **kwargs: Any) -> None:
        self._loop = get_running_loop(loop)
        self._connections = {}  # type: Dict[RequestHandler, asyncio.Transport]
        self._kwargs = kwargs
        self.requests_count = 0
        self.request_handler = handler
        self.request_factory = request_factory or self._make_request 
Example #28
Source File: client_reqrep.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def check(self, transport: asyncio.Transport) -> None:
        if not transport.get_extra_info('sslcontext'):
            return
        sslobj = transport.get_extra_info('ssl_object')
        cert = sslobj.getpeercert(binary_form=True)
        got = self._hashfunc(cert).digest()
        if got != self._fingerprint:
            host, port, *_ = transport.get_extra_info('peername')
            raise ServerFingerprintMismatch(self._fingerprint,
                                            got, host, port) 
Example #29
Source File: http_writer.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def transport(self) -> Optional[asyncio.Transport]:
        return self._transport 
Example #30
Source File: web_request.py    From Galaxy_Plugin_Bethesda with MIT License 5 votes vote down vote up
def transport(self) -> Optional[asyncio.Transport]:
        if self._protocol is None:
            return None
        return self._protocol.transport