2019-12-01 16:26:16 +08:00
|
|
|
from multiaddr import Multiaddr
|
2018-12-08 04:00:46 +08:00
|
|
|
import pytest
|
2019-12-01 16:26:16 +08:00
|
|
|
import trio
|
|
|
|
|
|
|
|
from libp2p.network.connection.raw_connection import RawConnection
|
2019-12-06 17:06:37 +08:00
|
|
|
from libp2p.tools.constants import LISTEN_MADDR
|
2019-12-24 02:19:43 +08:00
|
|
|
from libp2p.transport.exceptions import OpenConnectionError
|
2019-12-01 16:26:16 +08:00
|
|
|
from libp2p.transport.tcp.tcp import TCP
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.trio
|
|
|
|
async def test_tcp_listener(nursery):
|
|
|
|
transport = TCP()
|
|
|
|
|
|
|
|
async def handler(tcp_stream):
|
2020-02-05 20:36:42 +08:00
|
|
|
pass
|
2019-12-01 16:26:16 +08:00
|
|
|
|
|
|
|
listener = transport.create_listener(handler)
|
|
|
|
assert len(listener.get_addrs()) == 0
|
|
|
|
await listener.listen(LISTEN_MADDR, nursery)
|
|
|
|
assert len(listener.get_addrs()) == 1
|
|
|
|
await listener.listen(LISTEN_MADDR, nursery)
|
|
|
|
assert len(listener.get_addrs()) == 2
|
|
|
|
|
2018-12-08 04:00:46 +08:00
|
|
|
|
2019-12-01 16:26:16 +08:00
|
|
|
@pytest.mark.trio
|
|
|
|
async def test_tcp_dial(nursery):
|
|
|
|
transport = TCP()
|
|
|
|
raw_conn_other_side = None
|
2019-12-24 02:19:43 +08:00
|
|
|
event = trio.Event()
|
2018-12-08 04:00:46 +08:00
|
|
|
|
2019-12-01 16:26:16 +08:00
|
|
|
async def handler(tcp_stream):
|
|
|
|
nonlocal raw_conn_other_side
|
|
|
|
raw_conn_other_side = RawConnection(tcp_stream, False)
|
2019-12-24 02:19:43 +08:00
|
|
|
event.set()
|
2019-12-01 16:26:16 +08:00
|
|
|
await trio.sleep_forever()
|
2018-12-08 04:00:46 +08:00
|
|
|
|
2019-12-24 02:19:43 +08:00
|
|
|
# Test: `OpenConnectionError` is raised when trying to dial to a port which
|
|
|
|
# no one is not listening to.
|
|
|
|
with pytest.raises(OpenConnectionError):
|
2019-12-01 16:26:16 +08:00
|
|
|
await transport.dial(Multiaddr("/ip4/127.0.0.1/tcp/1"))
|
2018-12-08 04:00:46 +08:00
|
|
|
|
2019-12-01 16:26:16 +08:00
|
|
|
listener = transport.create_listener(handler)
|
|
|
|
await listener.listen(LISTEN_MADDR, nursery)
|
2019-12-17 15:50:55 +08:00
|
|
|
addrs = listener.get_addrs()
|
|
|
|
assert len(addrs) == 1
|
|
|
|
listen_addr = addrs[0]
|
2019-12-01 16:26:16 +08:00
|
|
|
raw_conn = await transport.dial(listen_addr)
|
2019-12-24 02:19:43 +08:00
|
|
|
await event.wait()
|
2018-12-08 04:00:46 +08:00
|
|
|
|
2019-12-01 16:26:16 +08:00
|
|
|
data = b"123"
|
|
|
|
await raw_conn_other_side.write(data)
|
|
|
|
assert (await raw_conn.read(len(data))) == data
|