68 lines
3.2 KiB
Python
68 lines
3.2 KiB
Python
"""Run from the protocol-builder venv: python test_agent.py <built agent.pyz>."""
|
|
import importlib.util
|
|
import os
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
import uuid
|
|
|
|
sys.path.insert(0,sys.argv.pop(1))
|
|
spec = importlib.util.spec_from_file_location('opn_channel', Path(__file__).with_name('agent.py'))
|
|
a = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(a)
|
|
|
|
|
|
class Reconnect(unittest.TestCase):
|
|
def test_lost_ack_keeps_original_identity_after_restart(self):
|
|
with tempfile.TemporaryDirectory() as temp:
|
|
db = sqlite3.connect(':memory:')
|
|
db.executescript('CREATE TABLE sequence(id INTEGER PRIMARY KEY,n INTEGER);INSERT INTO sequence VALUES(1,0);'
|
|
'CREATE TABLE pending(id INTEGER PRIMARY KEY,envelope BLOB,observed INTEGER);')
|
|
cache = Path(temp)/'inventory.json'
|
|
cache.write_text('{}')
|
|
identity = {'agent_id':str(uuid.uuid4())}
|
|
instance = str(uuid.uuid4())
|
|
captures = []
|
|
generation = 0
|
|
|
|
def gateway(_ctx,path,data,media):
|
|
nonlocal generation
|
|
req = a.pb.MessageBatch.FromString(data).messages[0]
|
|
reply = a.pb.Envelope()
|
|
reply.CopyFrom(req)
|
|
kind = req.WhichOneof('payload')
|
|
if kind == 'client_hello':
|
|
generation += 1
|
|
reply.connection_generation = generation
|
|
reply.server_hello.CopyFrom(a.pb.ServerHello(connection_generation=generation,max_message_bytes=1024*1024))
|
|
else:
|
|
if kind == 'inventory_snapshot':
|
|
captures.append(req)
|
|
if len(captures)==1: raise OSError('lost ACK')
|
|
reply.ack.CopyFrom(a.pb.Ack(message_id=req.message_id))
|
|
return a.pb.MessageBatch(protocol_major=1,messages=[reply]).SerializeToString()
|
|
|
|
with patch.object(a,'context'), patch.object(a,'renew',return_value=False), \
|
|
patch.object(a,'post',gateway), patch.object(a,'Path',return_value=cache), \
|
|
patch.object(a,'usage',return_value=(a.pb.SystemUsage(),[])), \
|
|
patch.object(a.time,'clock_gettime',return_value=100), \
|
|
patch.object(a.time,'CLOCK_UPTIME',1,create=True), patch.object(a.time,'sleep',side_effect=StopIteration):
|
|
with self.assertRaises(OSError):
|
|
a.session(db,identity,str(uuid.uuid4()),instance)
|
|
self.assertIsNotNone(db.execute('SELECT 1 FROM pending').fetchone())
|
|
os.unlink(cache)
|
|
with self.assertRaises(StopIteration):
|
|
a.session(db,identity,str(uuid.uuid4()),instance)
|
|
self.assertIsNone(db.execute('SELECT 1 FROM pending').fetchone())
|
|
self.assertEqual(len(captures),2)
|
|
self.assertNotEqual(captures[0].connection_generation,captures[1].connection_generation)
|
|
captures[0].connection_generation=captures[1].connection_generation
|
|
self.assertEqual(captures[0],captures[1])
|
|
|
|
|
|
if __name__=='__main__':
|
|
unittest.main()
|