2019-10-24 18:50:38 +08:00
|
|
|
import secrets
|
|
|
|
|
|
|
|
import pytest
|
2019-12-06 17:06:37 +08:00
|
|
|
import trio
|
2019-10-24 18:50:38 +08:00
|
|
|
|
2019-11-07 07:04:17 +08:00
|
|
|
from libp2p.host.ping import ID, PING_LENGTH
|
2019-11-26 19:24:30 +08:00
|
|
|
from libp2p.tools.factories import host_pair_factory
|
2019-10-24 18:50:38 +08:00
|
|
|
|
|
|
|
|
2019-12-01 19:17:32 +08:00
|
|
|
@pytest.mark.trio
|
|
|
|
async def test_ping_once(is_host_secure):
|
|
|
|
async with host_pair_factory(is_host_secure) as (host_a, host_b):
|
2019-11-08 13:01:08 +08:00
|
|
|
stream = await host_b.new_stream(host_a.get_id(), (ID,))
|
|
|
|
some_ping = secrets.token_bytes(PING_LENGTH)
|
|
|
|
await stream.write(some_ping)
|
2019-12-01 19:17:32 +08:00
|
|
|
await trio.sleep(0.01)
|
2019-11-08 13:01:08 +08:00
|
|
|
some_pong = await stream.read(PING_LENGTH)
|
|
|
|
assert some_ping == some_pong
|
|
|
|
await stream.close()
|
2019-10-24 18:50:38 +08:00
|
|
|
|
|
|
|
|
|
|
|
SOME_PING_COUNT = 3
|
|
|
|
|
|
|
|
|
2019-12-01 19:17:32 +08:00
|
|
|
@pytest.mark.trio
|
|
|
|
async def test_ping_several(is_host_secure):
|
|
|
|
async with host_pair_factory(is_host_secure) as (host_a, host_b):
|
2019-11-08 13:01:08 +08:00
|
|
|
stream = await host_b.new_stream(host_a.get_id(), (ID,))
|
|
|
|
for _ in range(SOME_PING_COUNT):
|
|
|
|
some_ping = secrets.token_bytes(PING_LENGTH)
|
|
|
|
await stream.write(some_ping)
|
|
|
|
some_pong = await stream.read(PING_LENGTH)
|
|
|
|
assert some_ping == some_pong
|
|
|
|
# NOTE: simulate some time to sleep to mirror a real
|
|
|
|
# world usage where a peer sends pings on some periodic interval
|
|
|
|
# NOTE: this interval can be `0` for this test.
|
2019-12-01 19:17:32 +08:00
|
|
|
await trio.sleep(0)
|
2019-11-08 13:01:08 +08:00
|
|
|
await stream.close()
|