1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +00:00
royalnet/tests/test_network.py

58 lines
2 KiB
Python
Raw Normal View History

2019-05-15 00:40:17 +00:00
import pytest
import uuid
2019-05-15 13:11:07 +00:00
import asyncio
2019-05-22 00:20:20 +00:00
import logging
2019-09-28 16:04:35 +00:00
from royalnet.network import Package, NetworkLink, NetworkServer, ConnectionClosedError, Request
2019-05-22 00:20:20 +00:00
log = logging.root
stream_handler = logging.StreamHandler()
stream_handler.formatter = logging.Formatter("{asctime}\t{name}\t{levelname}\t{message}", style="{")
log.addHandler(stream_handler)
log.setLevel(logging.WARNING)
2019-05-15 13:11:07 +00:00
@pytest.fixture
def async_loop():
loop = asyncio.get_event_loop()
yield loop
loop.close()
2019-05-22 00:20:20 +00:00
async def echo_request_handler(message):
2019-05-15 13:11:07 +00:00
return message
2019-05-15 00:40:17 +00:00
def test_package_serialization():
2019-05-15 13:11:07 +00:00
pkg = Package({"ciao": "ciao"},
2019-05-15 00:40:17 +00:00
source=str(uuid.uuid4()),
destination=str(uuid.uuid4()),
source_conv_id=str(uuid.uuid4()),
destination_conv_id=str(uuid.uuid4()))
assert pkg == Package.from_dict(pkg.to_dict())
assert pkg == Package.from_json_string(pkg.to_json_string())
assert pkg == Package.from_json_bytes(pkg.to_json_bytes())
2019-05-15 13:11:07 +00:00
2019-05-22 00:20:20 +00:00
def test_request_creation():
request = Request("pytest", {"testing": "is fun", "bugs": "are less fun"})
assert request == Request.from_dict(request.to_dict())
2019-05-15 13:11:07 +00:00
def test_links(async_loop: asyncio.AbstractEventLoop):
2019-05-22 00:20:20 +00:00
address, port = "127.0.0.1", 1235
2019-10-01 19:24:46 +00:00
master = NetworkServer(address, port, "test", loop=async_loop)
run_server_task = async_loop.create_task(master.run())
2019-05-15 13:11:07 +00:00
# Test invalid secret
2019-09-28 16:04:35 +00:00
wrong_secret_link = NetworkLink("ws://127.0.0.1:1235", "invalid", "test", echo_request_handler, loop=async_loop)
2019-05-15 13:11:07 +00:00
with pytest.raises(ConnectionClosedError):
async_loop.run_until_complete(wrong_secret_link.run())
# Test regular connection
2019-09-28 16:04:35 +00:00
link1 = NetworkLink("ws://127.0.0.1:1235", "test", "one", echo_request_handler, loop=async_loop)
2019-05-22 00:20:20 +00:00
async_loop.create_task(link1.run())
2019-09-28 16:04:35 +00:00
link2 = NetworkLink("ws://127.0.0.1:1235", "test", "two", echo_request_handler, loop=async_loop)
2019-05-22 00:20:20 +00:00
async_loop.create_task(link2.run())
2019-05-15 13:11:07 +00:00
message = {"ciao": "ciao"}
response = async_loop.run_until_complete(link1.request(message, "two"))
assert message == response