import time from types import SimpleNamespace import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from starlette.websockets import WebSocketDisconnect from k1link.fleet.rover_channel import RoverChannel from k1link.fleet.rover_control import RoverControl from k1link.web.rover_api import router @pytest.fixture def fixture(): control = RoverControl() control.exchange("node", {"relay_id": "a"*32, "rover": { "supported": True, "instance": "fixture", "state": "observing"}}) channel = RoverChannel(control) channel.vehicles["vehicle"] = {"node_id": "node", "enrollment": "paired"} app = FastAPI() app.state.fleet = SimpleNamespace(rover_channel=channel) app.include_router(router) with TestClient(app, base_url="http://127.0.0.1:8000", client=("127.0.0.1", 12345)) as client: yield control, client def connect(client, origin="http://127.0.0.1:8000"): return client.websocket_connect("ws://127.0.0.1:8000/api/v1/fleet/vehicle/rover-channel", headers={"Origin": origin}) def reply(socket): while True: value = socket.receive_json() if value["type"] == "reply": return value def arm(socket, clock, offset=350): socket.send_json({"id": 1, "action": "arm", "expires_ms": clock+offset, "body": {"standstill_confirmed": True, "current_a": 5, "max_erpm": 1000}}) return reply(socket) def test_socket_observation_and_commands_share_existing_authority(fixture): control, client = fixture with connect(client) as socket: first = socket.receive_json() assert first["value"]["fresh"] acknowledged = arm(socket, first["clock_ms"]) assert acknowledged["state"]["controlling"] identifier = acknowledged["value"]["session_id"] socket.send_json({"id": 2, "action": "command", "expires_ms": first["clock_ms"]+300, "body": {"session_id": identifier, "sequence": 1, "left": 0, "right": 0, "stop": False}}) assert reply(socket)["value"]["accepted_sequence"] == 1 command = control.stream("node", "a"*32)["command"] assert command["left"] == 0 assert command["expires_mono_ms"] == pytest.approx(first["clock_ms"]+300) assert not control.view("node")["controlling"] @pytest.mark.parametrize("offset", [-1, 10000]) def test_queued_or_overlong_request_cannot_create_a_lease(fixture, offset): control, client = fixture with connect(client) as socket: first = socket.receive_json() assert arm(socket, first["clock_ms"], offset)["status"] == 408 assert not control.view("node")["controlling"] def test_observer_disconnect_does_not_retire_other_operator(fixture): control, client = fixture with connect(client) as owner: first = owner.receive_json() identifier = arm(owner, first["clock_ms"])["value"]["session_id"] with connect(client) as observer: observed = observer.receive_json() observer.send_json({"id": 2, "action": "command", "expires_ms": observed["clock_ms"]+300, "body": {"session_id": identifier, "sequence": 1, "left": 0, "right": 0, "stop": True}}) assert reply(observer)["status"] == 409 assert control.view("node")["controlling"] control.disconnect("node", "other-session") assert control.stream("node", "a"*32)["command"]["id"] == identifier def test_state_push_cannot_renew_motion_lease(fixture): control, client = fixture with connect(client) as socket: first = socket.receive_json() arm(socket, first["clock_ms"]) time.sleep(.42) assert not control.view("node")["controlling"] @pytest.mark.parametrize("origin", ["https://example.com", "null", "http://localhost:8000"]) def test_cross_origin_websocket_is_rejected_before_accept(fixture, origin): _, client = fixture with pytest.raises(WebSocketDisconnect) as error: with connect(client, origin): pass assert error.value.code == 1008 def test_malformed_frame_cannot_invoke_control(fixture): control, client = fixture with connect(client) as socket: socket.receive_json() socket.send_json({"id": 1, "action": "arm", "body": {}, "expires_ms": "forever"}) with pytest.raises(WebSocketDisconnect): reply(socket) assert not control.view("node")["controlling"] def test_live_owner_socket_holds_neutral_while_browser_js_sends_nothing(fixture): control, client = fixture with connect(client) as socket: first = socket.receive_json() identifier = arm(socket, first['clock_ms'])['value']['session_id'] socket.send_json({'id':2,'action':'hold','expires_ms':time.monotonic()*1000+350, 'body':{'session_id':identifier,'sequence':1}}) assert reply(socket)['value']['accepted_sequence'] == 1 sequences=[] for _ in range(60): # Synthetic board feedback stays fresh while browser JS is silent. control.exchange('node', {'relay_id':'a'*32,'rover':{ 'instance':'fixture','supported':True,'state':'ready','session_id':identifier}}) time.sleep(.1) frame=control.stream('node','a'*32)['command'] assert frame and frame['id']==identifier assert frame['left']==frame['right']==0 sequences.append(frame['sequence']) assert len(set(sequences))>=40 socket.send_json({'id':3,'action':'command','expires_ms':time.monotonic()*1000+350, 'body':{'session_id':identifier,'sequence':2,'left':.5,'right':.5,'stop':False}}) assert reply(socket)['value']['accepted_sequence']==2 frame=control.stream('node','a'*32)['command'] assert frame['left']==.5 and frame['sequence']>max(sequences) time.sleep(.42) assert not control.view('node')['controlling'], 'native loop must not renew resumed movement' assert not control.view('node')['controlling'] def test_observer_cannot_hold_and_owner_socket_close_retires_neutral(fixture): control, client = fixture with connect(client) as owner: first=owner.receive_json();identifier=arm(owner, first['clock_ms'])['value']['session_id'] with connect(client) as observer: observer.receive_json() observer.send_json({'id':1,'action':'hold','expires_ms':time.monotonic()*1000+350, 'body':{'session_id':identifier,'sequence':1}}) assert reply(observer)['status']==409 owner.send_json({'id':2,'action':'hold','expires_ms':time.monotonic()*1000+350, 'body':{'session_id':identifier,'sequence':1}}) assert reply(owner)['value']['accepted_sequence']==1 assert not control.view('node')['controlling'] assert not control.maintain_neutral('node',identifier) def test_browser_cannot_invoke_native_maintenance_directly(fixture): _, client=fixture with connect(client) as socket: socket.receive_json() socket.send_json({'id':1,'action':'maintain_neutral','expires_ms':time.monotonic()*1000+350,'body':{}}) with pytest.raises(WebSocketDisconnect):reply(socket)