2018-11-12 23:57:40 +08:00
|
|
|
import pytest
|
|
|
|
|
2018-11-25 14:45:13 +08:00
|
|
|
from libp2p.libp2p import *
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
@pytest.mark.asyncio
|
|
|
|
async def test_simple_messages():
|
2018-11-25 14:45:13 +08:00
|
|
|
hostA = await new_node(transport_opt=["/ip4/127.0.0.1/tcp/8001/ipfs/hostA"])
|
|
|
|
hostB = await new_node(transport_opt=["/ip4/127.0.0.1/tcp/8000/ipfs/hostB"])
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
async def stream_handler(stream):
|
|
|
|
while True:
|
|
|
|
read_string = (await stream.read()).decode()
|
|
|
|
print("host B received:" + read_string)
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
response = "ack:" + read_string
|
|
|
|
print("sending response:" + response)
|
|
|
|
await stream.write(response.encode())
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
hostB.set_stream_handler("/echo/1.0.0", stream_handler)
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
# Associate the peer with local ip address (see default parameters of Libp2p())
|
|
|
|
hostA.get_peerstore().add_addr("hostB", "/ip4/127.0.0.1/tcp/8000", 10)
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
stream = await hostA.new_stream("hostB", "/echo/1.0.0")
|
|
|
|
messages = ["hello" + str(x) for x in range(10)]
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
for message in messages:
|
|
|
|
await stream.write(message.encode())
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
response = (await stream.read()).decode()
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
print("res: " + response)
|
|
|
|
assert response == ("ack:" + message)
|
2018-11-12 01:36:15 +08:00
|
|
|
|
2018-11-12 23:57:40 +08:00
|
|
|
# Success, terminate pending tasks.
|
|
|
|
return
|