import asyncio
import struct
import os
import pytest
import cbor2
from katzenpost_thinclient.core import ThinClient, Config
def make_config():
cfg = Config.__new__(Config)
cfg.network = "tcp"
cfg.address = "127.0.0.1:0"
async def noop_event(event):
pass
cfg.handle_connection_status_event = noop_event
cfg.handle_new_pki_document_event = noop_event
cfg.handle_message_sent_event = noop_event
cfg.handle_message_reply_event = noop_event
cfg.handle_daemon_disconnected_event = noop_event
return cfg
class TestInstanceToken:
def test_instance_token_exists(self):
cfg = make_config()
client = ThinClient.__new__(ThinClient)
client.instance_token = os.urandom(16)
assert hasattr(client, 'instance_token')
assert len(client.instance_token) == 16
def test_instance_token_is_random(self):
cfg = make_config()
token1 = os.urandom(16)
token2 = os.urandom(16)
assert token1 != token2
def test_instance_token_nonzero(self):
token = os.urandom(16)
assert token != b'\x00' * 16
class TestDisconnect:
def test_disconnect_method_exists(self):
assert hasattr(ThinClient, 'disconnect')
def test_disconnect_does_not_send_thin_close(self):
assert hasattr(ThinClient, 'disconnect')
assert hasattr(ThinClient, 'stop')
assert ThinClient.disconnect is not ThinClient.stop
class TestSessionTokenProtocol:
def test_session_token_cbor_encoding(self):
token = os.urandom(16)
request = {
"session_token": {
"client_instance_token": token,
}
}
encoded = cbor2.dumps(request)
decoded = cbor2.loads(encoded)
assert decoded["session_token"]["client_instance_token"] == token
def test_session_token_reply_decoding(self):
app_id = os.urandom(16)
reply = {
"session_token_reply": {
"app_id": app_id,
"resumed": True,
}
}
encoded = cbor2.dumps(reply)
decoded = cbor2.loads(encoded)
assert decoded["session_token_reply"]["app_id"] == app_id
assert decoded["session_token_reply"]["resumed"] is True
def test_session_token_reply_not_resumed(self):
reply = {
"session_token_reply": {
"app_id": os.urandom(16),
"resumed": False,
}
}
encoded = cbor2.dumps(reply)
decoded = cbor2.loads(encoded)
assert decoded["session_token_reply"]["resumed"] is False
class TestHandleSessionTokenReply:
@pytest.mark.asyncio
async def test_handle_response_session_token_reply(self):
cfg = make_config()
client = ThinClient.__new__(ThinClient)
client.config = cfg
client.pki_doc = None
client._is_connected = False
client._stopping = False
client._received_shutdown = False
client._daemon_instance_token = None
client.reply_received_event = asyncio.Event()
client.response_queues = {}
client.ack_queues = {}
import logging
client.logger = logging.getLogger('test')
response = {
"session_token_reply": {
"app_id": os.urandom(16),
"resumed": False,
}
}
await client.handle_response(response)