am-freescan/scripts/test_robot_simulator.py

166 lines
8.2 KiB
Python
Raw Normal View History

2026-10-22 16:18:37 +08:00
import unittest
import tempfile
from pathlib import Path
from datetime import datetime, timedelta, timezone
from unittest.mock import MagicMock, patch
from robot_simulator import SimulatedAgv, ResourceStore, OWNER, write_json, read_json
class SimulatorStateFileTest(unittest.TestCase):
def test_transient_windows_reader_lock_does_not_stop_state_updates(self):
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / 'state.json'
write_json(path, {'running': False})
original = Path.replace
attempts = []
def briefly_locked(source, target):
attempts.append(1)
if len(attempts) <= 2:
raise PermissionError('Windows reader temporarily holds target open')
return original(source, target)
with patch.object(Path, 'replace', briefly_locked), patch('robot_simulator.time.sleep'):
write_json(path, {'running': True})
self.assertEqual({'running': True}, read_json(path))
self.assertEqual(3, len(attempts))
class SimulatorHeartbeatTest(unittest.TestCase):
def test_heartbeat_uses_application_clock_instead_of_database_clock(self):
store = ResourceStore.__new__(ResourceStore)
store.connection = MagicMock()
cursor = store.connection.cursor.return_value.__enter__.return_value
cursor.fetchone.side_effect = [{'archived_status': '0', 'create_by': OWNER}, {'id': 'sim-device'}]
before = datetime.now(timezone(timedelta(hours=8))).replace(tzinfo=None)
self.assertTrue(store.heartbeat(58071, SimulatedAgv()))
after = datetime.now(timezone(timedelta(hours=8))).replace(tzinfo=None)
updates = [(sql, parameters) for (sql, parameters), _ in cursor.execute.call_args_list
if sql.startswith('UPDATE')]
self.assertEqual(2, len(updates))
for sql, parameters in updates:
self.assertNotIn('NOW()', sql)
timestamps = [value for value in parameters if isinstance(value, datetime)]
self.assertTrue(timestamps, 'Heartbeat must bind its own application timestamp')
self.assertTrue(all(before <= value <= after for value in timestamps))
class SimulatedAgvTest(unittest.TestCase):
def test_navigation_updates_position_and_reports_simulation(self):
world = SimulatedAgv()
world.navigate(1.5, -2, 0.25)
self.assertEqual((1.5, -2, 0.25), world.pose)
self.assertEqual(1.0, world.progress)
self.assertIn('SIMULATED', world.message)
def test_emergency_stop_rejects_movement_until_fault_is_cleared(self):
world = SimulatedAgv()
world.emergency_stop()
with self.assertRaisesRegex(ValueError, '急停'):
world.navigate(5, 1, 0)
self.assertEqual((0.0, 0.0, 0.0), world.pose)
world.clear_fault()
world.navigate(5, 1, 0)
self.assertEqual((5, 1, 0), world.pose)
def test_station_navigation_resolves_known_station_only(self):
world = SimulatedAgv()
world.navigate_station('SIM-STATION-1')
self.assertEqual((1.0, 1.0, 0.0), world.pose)
with self.assertRaisesRegex(ValueError, '模拟站点不存在'):
world.navigate_station('real-unknown-station')
def test_invalid_or_infinite_coordinates_are_rejected(self):
world = SimulatedAgv()
with self.assertRaises(ValueError):
world.navigate(float('nan'), 0, 0)
with self.assertRaises(ValueError):
world.navigate(0, float('inf'), 0)
class SimulatedGrpcTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
import grpc
from robot_simulator import create_grpc_server, protocol, DEVICE_ID
cls.common, cls.command, cls.service, cls.message = protocol()
cls.device = DEVICE_ID
cls.world = SimulatedAgv()
cls.server, port = create_grpc_server(0, cls.world)
cls.server.start()
cls.channel = grpc.insecure_channel('127.0.0.1:' + str(port))
cls.stub = cls.service.AgvServiceStub(cls.channel)
@classmethod
def tearDownClass(cls):
cls.channel.close()
cls.server.stop(0).wait()
def test_native_protocol_navigation_and_runtime_state(self):
head = self.common.CommandHeader.Request(device_id=self.device)
result = self.stub.navigateToPose(self.command.AgvNavigateToPoseCommand.Request(header=head,
pose=self.message.AgvPose2d(x=2, y=3, theta=0.5)), timeout=2)
self.assertTrue(result.header.success)
state = self.stub.getRuntimeState(self.command.AgvRuntimeStateCommand.Request(header=head), timeout=2).state
self.assertEqual((2, 3, 0.5), (state.pose.x, state.pose.y, state.pose.theta))
self.assertIn('SIMULATED', state.last_error)
def test_unknown_device_is_rejected_instead_of_returning_fake_success(self):
result = self.stub.getRuntimeState(self.command.AgvRuntimeStateCommand.Request(
header=self.common.CommandHeader.Request(device_id='another-real-device')), timeout=2)
self.assertFalse(result.header.success)
def test_common_command_header_stop_and_clear_fault_contract(self):
head = self.common.CommandHeader.Request(device_id=self.device)
self.assertTrue(self.stub.emergencyStop(head, timeout=2).success)
rejected = self.stub.navigateToPose(self.command.AgvNavigateToPoseCommand.Request(
header=head, pose=self.message.AgvPose2d(x=100)), timeout=2)
self.assertFalse(rejected.header.success)
self.assertTrue(self.stub.clearFault(head, timeout=2).success)
def test_system_stop_all_acknowledges_only_simulated_motion(self):
from cmvr.api import system_command_pb2, system_service_pb2_grpc
stub = system_service_pb2_grpc.SystemServiceStub(self.channel)
self.world.navigation_state, self.world.progress = 2, 0.4
result = stub.StopAll(system_command_pb2.StopAllCommand.Request(
header=self.common.CommandHeader.Request(device_id='')), timeout=2)
self.assertTrue(result.header.success)
self.assertIn('SIMULATED', result.header.error_message)
self.assertEqual(6, self.world.navigation_state)
self.assertFalse(self.world.estop, 'normal cancellation must not require physical fault reset')
self.assertEqual(0, self.world.progress)
def test_system_stop_all_rejects_unknown_real_device(self):
from cmvr.api import system_command_pb2, system_service_pb2_grpc
stub = system_service_pb2_grpc.SystemServiceStub(self.channel)
self.world.navigation_state = 2
result = stub.StopAll(system_command_pb2.StopAllCommand.Request(
header=self.common.CommandHeader.Request(device_id='real-arm')), timeout=2)
self.assertFalse(result.header.success)
self.assertEqual(2, self.world.navigation_state)
def test_failed_stop_does_not_fabricate_a_stopped_state(self):
from cmvr.api import system_command_pb2, system_service_pb2_grpc
stub=system_service_pb2_grpc.SystemServiceStub(self.channel)
self.world.navigation_state=2;self.world.stop_failure=True
try:
response=stub.StopAll(system_command_pb2.StopAllCommand.Request(),timeout=2)
self.assertFalse(response.header.success)
self.assertEqual(2,self.world.navigation_state)
finally:self.world.stop_failure=False
2026-10-22 16:18:37 +08:00
def test_system_inventory_contains_only_simulated_agv_and_arm_commands_are_unsupported(self):
import grpc
from cmvr.api import system_command_pb2, system_service_pb2_grpc
stub = system_service_pb2_grpc.SystemServiceStub(self.channel)
result = stub.GetSystemStatus(system_command_pb2.GetSystemStatusCommand.Request(), timeout=2)
self.assertTrue(result.header.success)
self.assertEqual([self.device], [device.device_id for device in result.device_list])
self.assertIn('SIMULATED', result.header.error_message)
with self.assertRaises(grpc.RpcError) as rejected:
stub.ExecuteActionQueue(system_command_pb2.ActionQueueCommand.Request(), timeout=2)
self.assertEqual(grpc.StatusCode.UNIMPLEMENTED, rejected.exception.code())
if __name__ == '__main__':
unittest.main()