def test_expiry(): tracker = Tracker(parse_schedule, '') update = tracker.update(LOCATIONS) now = timestamp() assert 0 == len(tracker.expire(now - 60 * 1000)) assert len(update['positions']) == len(tracker.expire(now + 60 * 1000)) assert len(tracker.tracks) == 0
def test_update(): tracker = Tracker(parse_schedule, '') update = tracker.update(LOCATIONS) assert update is not None assert isinstance(update['positions'], list) positions: List[PositionUpdate] = update['positions'] assert len(positions) == 5 assert tracker.update(LOCATIONS) is None new_locations = LOCATIONS.replace('24713100,59441220', '24715100,59441220') update = tracker.update(new_locations) assert update is not None assert isinstance(update['positions'], list) positions = update['positions'] assert update is not None assert len(positions) == 1 assert positions[0]['line'] == '40'
async def test_poll_positions(): session = make_session("""2,17,24715550,59411480,,24,1035 2,17,24687130,59399520,,255,1038""") hub = Hub() tracker = Tracker(parse_schedule, 'TLN') with Subscription(hub) as queue: await poll_bus_positions(session, tracker, hub) pos = await queue.get() positions = pos['positions'] assert len(positions) == 2 assert positions[0]['id'] == 1035 assert positions[1]['id'] == 1038 assert queue.empty() # Repeat is ignored await poll_bus_positions(session, tracker, hub) assert queue.empty()
def test_get_tracks(): tracker = Tracker(parse_schedule, '') update = tracker.update(LOCATIONS) tracks = tracker.get_tracks() assert update['positions'] == tracks['positions']
def test_update_no_id(): def no_ids(_): yield {'lon': 59.01, 'lat': 24.41} tracker = Tracker(no_ids, '') assert tracker.update(LOCATIONS) is None
def test_send_update_no_id(): tracker = Tracker(parse_schedule, '') pos = {'lon': 59.01, 'lat': 24.41} assert tracker.send_update(pos) is False
from sanic import Sanic from sanic_cors import CORS from websockets import ConnectionClosed import asyncio import inspect import logging import msgpack logger = logging.getLogger(__name__) app = Sanic(__name__) CORS(app, automatic_options=True) hub = Hub(True) registry = UserRegistry(hub) tracker = Tracker(parse_schedule, 'TLN') @app.websocket('/feed') async def feed(request, ws): tracks = msgpack.packb(tracker.get_tracks()) await ws.send(tracks) registry.add(ws) try: async for message in ws: logger.info('message received') except ConnectionClosed: logger.info('Connection closed') finally: logger.info('Unregistering') registry.remove(ws)