对tools进行了整理,Xmake也改为相对路径,在线 LiDAR-IMU 定位器实现

This commit is contained in:
mzx committed 2026-11-23 14:32:42 +08:00
1 parent 0602144ac5
commit 4502296915
70 files changed
+2652 -1298

No files matched your search

+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Isolated live relay test. No Gazebo, TF, or real actuator subscribers."""
import argparse
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import project_env
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--binary', type=Path)
args=parser.parse_args()
try:
binary = args.binary or project_env.find_bin_dir()/'cmd_vel_relay'
binary = project_env.require_executable(binary, 'cmd_vel_relay')
except project_env.ProbeError as error:
parser.exit(1, f'{parser.prog}: {error}\n')
os.environ.update(ROS_DOMAIN_ID=str(130+int(uuid.uuid4().hex[:4],16)%40),
FASTDDS_BUILTIN_TRANSPORTS='UDPv4',ROS2CLI_DISABLE_DAEMON='1')
import rclpy
from geometry_msgs.msg import Twist
from std_msgs.msg import Bool
from action_msgs.srv import CancelGoal
rclpy.init();node=rclpy.create_node('test_motion_interlock')
received=[];cancellations=[]
subscription=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda m:received.append((time.monotonic(),m.linear.x)),100)
health=node.create_publisher(Bool,'/field_localization/navigation_valid',1)
final=node.create_publisher(Twist,'/cmd_vel',1)
upstream=node.create_publisher(Twist,'/cmd_vel_smoothed',1)
raw=node.create_publisher(Twist,'/cmd_vel_nav',1)
def cancel(req,response):
cancellations.append(time.monotonic());response.return_code=0
return response
services=[node.create_service(CancelGoal,name+'/_action/cancel_goal',cancel)
for name in ['/navigate_to_pose','/navigate_through_poses']]
process=subprocess.Popen([str(binary),'--ros-args','-p','navigation_mode:=true'],
start_new_session=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,text=True)
checks=0
def check(ok,message):
nonlocal checks
checks+=1
if not ok: raise RuntimeError(message)
print('PASS',message,flush=True)
def drive(duration,valid=True,publish_health=True,publish_final=True):
until=time.monotonic()+duration
while time.monotonic()<until:
if publish_health:
h=Bool();h.data=valid;health.publish(h)
if publish_final:
m=Twist();m.linear.x=0.1;final.publish(m)
m=Twist();m.linear.x=1.5;upstream.publish(m);raw.publish(m)
rclpy.spin_once(node,timeout_sec=0.01)
try:
deadline=time.monotonic()+10
while final.get_subscription_count()<1 and time.monotonic()<deadline:
rclpy.spin_once(node,timeout_sec=0.02)
check(final.get_subscription_count()==1,'one final velocity subscription')
drive(0.5,publish_health=False)
check(received and all(v==0 for _,v in received),'no motion before valid localization')
# A blocked nonzero command requests cancellation; allow both services to acknowledge.
drive(0.8)
check(any(v==0.1 for _,v in received),'valid final velocity reaches actuator')
check(all(v<=0.1 for _,v in received),'raw and smoothed topics cannot bypass collision output')
before=time.monotonic();drive(0.4,valid=False)
zeros=[t for t,v in received if t>=before and v==0]
check(bool(zeros) and min(zeros)-before<0.1,'invalid health stops within 100 ms')
check(len(cancellations)>=2,'navigation action servers receive cancellation')
drive(0.5)
before=time.monotonic();drive(0.6,publish_health=False)
zeros=[t for t,v in received if t>=before+0.3 and v==0]
check(bool(zeros) and min(zeros)-before<0.4,'stale health stops within 400 ms')
drive(0.5)
before=time.monotonic();drive(0.6,publish_final=False)
zeros=[t for t,v in received if t>=before+0.3 and v==0]
check(bool(zeros) and min(zeros)-before<0.4,'stale final command stops despite upstream traffic')
check(process.poll() is None,'relay remains alive')
print(f'{checks} live checks passed; health_stop_ms={(min(t for t,v in received if t>=before+0.3 and v==0)-before)*1000:.3f}')
finally:
if process.poll() is None:os.killpg(process.pid,signal.SIGINT)
try:process.wait(timeout=5)
except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait()
_=subscription,services
node.destroy_node();rclpy.shutdown()
if __name__=='__main__':main()
+154
View File
@@ -0,0 +1,154 @@
#!/usr/bin/env python3
"""Fault-injection checks using isolated ROS services, without Gazebo or motion commands."""
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import uuid
from types import SimpleNamespace
INTERNAL_TOOLS = Path(__file__).resolve().parents[1] / '_internal'
sys.path.insert(0, str(INTERNAL_TOOLS))
from dds_environment import defaults
def CHECK(condition, message):
if not condition:
raise RuntimeError(message)
def main():
env = defaults({'ROS_DOMAIN_ID': '77', 'FASTDDS_BUILTIN_TRANSPORTS': 'SHM'})
CHECK(env['ROS_DOMAIN_ID'] == '77' and env['FASTDDS_BUILTIN_TRANSPORTS'] == 'SHM',
'explicit environment override lost')
os.environ.update(defaults(os.environ))
os.environ['ROS_DOMAIN_ID'] = str(50+int(uuid.uuid4().hex[:8], 16) % 50)
import rclpy
from lifecycle_msgs.msg import State
from lifecycle_msgs.srv import GetState, ChangeState
from nav2_msgs.srv import IsPathValid, ManageLifecycleNodes
from rcl_interfaces.msg import ParameterValue, ParameterType
from rcl_interfaces.srv import GetParameters
from std_srvs.srv import Trigger
from nav2_startup import ready, failure_details, complete_endpoint
managed = ['planner_server', 'bt_navigator', 'waypoint_follower']
states = dict.fromkeys(managed, 3)
CHECK(ready(managed, states, True, True), 'valid readiness rejected')
CHECK(not ready([], {}, True, True), 'missing manager node list accepted')
CHECK(not ready(managed, {**states, 'bt_navigator': 2}, True, True), 'inactive node accepted')
CHECK(not ready(managed, states, False, True), 'manager incomplete accepted')
CHECK(not ready(managed, states, True, False), 'nonresponding path service accepted')
details = failure_details(managed, {}, True, False,
['"wait" action server not available after waiting for 60.00s'])
CHECK(details['missing_dependencies'] == ['wait'], 'missing action not identified')
CHECK(complete_endpoint(SimpleNamespace(endpoint_count=2, endpoint_gids=[[0]*16, [0]*16])),
'complete endpoint pair rejected')
CHECK(not complete_endpoint(SimpleNamespace(endpoint_count=2, endpoint_gids=[[0]*16, [1]*16])),
'stale endpoints from different participants accepted')
CHECK(not complete_endpoint(SimpleNamespace(endpoint_count=1, endpoint_gids=[[0]*16])),
'half-discovered service accepted')
rclpy.init()
node = rclpy.create_node('planner_server')
executor = rclpy.executors.SingleThreadedExecutor()
executor.add_node(node)
extra_nodes = []
state_id = [3]
starts = []
def parameters(request, response):
response.values = [ParameterValue(type=ParameterType.PARAMETER_STRING_ARRAY,
string_array_value=managed)]
return response
def active(request, response):
response.success = True
return response
def state(request, response):
response.current_state = State(id=state_id[0])
return response
services = [node.create_service(GetParameters, '/lifecycle_manager_nav2/get_parameters', parameters),
node.create_service(Trigger, '/lifecycle_manager_nav2/is_active', active)]
services += [node.create_service(GetState, f'/{name}/get_state', state) for name in managed]
command = [sys.executable, str(INTERNAL_TOOLS / 'nav2_startup.py')]
def run(arguments):
process = subprocess.Popen(command+arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, start_new_session=True)
try:
deadline = time.monotonic()+15
while process.poll() is None and time.monotonic() < deadline:
executor.spin_once(timeout_sec=0.02)
if process.poll() is None:
raise RuntimeError('test subprocess did not finish')
return process.returncode, process.communicate()[0]
finally:
if process.poll() is None:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
try:
code, text = run(['--preflight', '--discovery-seconds', '1'])
CHECK(code == 1 and 'planner_server' in text and '启动拒绝' in text,
'occupied domain was not rejected: '+text)
code, text = run(['--timeout', '3'])
CHECK(code == 1 and '激活失败' in text and '"is_path_valid_responded": false' in text,
'all active nodes with missing path service incorrectly reported ready: '+text)
def path(request, response):
response.success = True
response.is_valid = False # A collision result must not be confused with transport failure.
return response
services.append(node.create_service(IsPathValid, '/is_path_valid', path))
code, text = run(['--timeout', '8'])
CHECK(code == 0 and 'Nav2 就绪' in text, 'responsive service not accepted: '+text)
def startup(request, response):
starts.append(request.command)
state_id[0] = 3
response.success = True
return response
services.append(node.create_service(ManageLifecycleNodes, '/lifecycle_manager_nav2/manage_nodes', startup))
state_id[0] = 1
code, text = run(['--activate', '--timeout', '3'])
CHECK(code == 1 and not starts, 'STARTUP issued before lifecycle discovery was complete: '+text)
# Give each lifecycle server its actual node name, and create the manager's clients.
for service in services[2:5]:
node.destroy_service(service)
owners = [node]
for name in managed[1:]:
owner = rclpy.create_node(name)
extra_nodes.append(owner)
executor.add_node(owner)
owners.append(owner)
manager = rclpy.create_node('lifecycle_manager_nav2', start_parameter_services=False)
extra_nodes.append(manager)
executor.add_node(manager)
manager_clients = []
for name, owner in zip(managed, owners):
services.append(owner.create_service(GetState, f'/{name}/get_state', state))
services.append(owner.create_service(ChangeState, f'/{name}/change_state', lambda req, res: res))
manager_clients += [manager.create_client(GetState, f'/{name}/get_state'),
manager.create_client(ChangeState, f'/{name}/change_state')]
code, text = run(['--activate', '--timeout', '10'])
CHECK(code == 0 and starts == [ManageLifecycleNodes.Request.STARTUP] and 'Nav2 就绪' in text,
'gated STARTUP did not occur exactly once: '+text)
print('PASS: 15 checks including partial/stale discovery, startup gating, occupied domain, missing service, and readiness')
finally:
executor.shutdown()
for other in extra_nodes:
other.destroy_node()
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Exercise startup retry limits and process ownership without ROS or Gazebo."""
from pathlib import Path
import subprocess
import sys
import tempfile
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / '_internal'))
from run_nav2 import stop_owned, supervise
def CHECK(condition, message):
if not condition:
raise RuntimeError(message)
def main():
with tempfile.TemporaryDirectory(prefix='nav2-supervisor-test-') as directory:
root = Path(directory)
navigation = root/'navigation.py'
navigation.write_text('''import signal,sys,time
signal.signal(signal.SIGINT, lambda *args: sys.exit(0))
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
time.sleep(1)
sys.exit(int(sys.argv[1]))
''')
checker = root/'checker.py'
checker.write_text('''import json,sys
from pathlib import Path
counter=Path(sys.argv[1]);mode=sys.argv[2]
n=int(counter.read_text())+1 if counter.exists() else 1
counter.write_text(str(n))
passed=mode=='ready' or mode=='recover' and n==2
retryable=mode in ('recover','exhaust')
Path(sys.argv[sys.argv.index('--result')+1]).write_text(json.dumps({'passed':passed,'retryable':retryable}))
sys.exit(0 if passed else 1)
''')
unrelated = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'],
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for mode, expected_calls, nav_exit, expected_result in [
('recover', 2, 0, 0), ('exhaust', 3, 0, 1),
('unknown', 1, 0, 1), ('ready', 1, 1, 1)]:
counter = root/(mode+'.count')
result = supervise([sys.executable, str(navigation), str(nav_exit)],
[sys.executable, str(checker), str(counter), mode], 3, 2)
CHECK(result == expected_result and int(counter.read_text()) == expected_calls,
f'{mode}: wrong retry count/result')
CHECK(unrelated.poll() is None, 'unrelated process was stopped')
finally:
stop_owned(unrelated)
print('PASS: 5 supervisor checks (recovery, limit, unknown/active refusal, no retry after ready, process ownership)')
if __name__ == '__main__':
main()
+258
View File
@@ -0,0 +1,258 @@
#!/usr/bin/env python3
"""Exercise the shared environment probes through both CLI entry points."""
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
import unittest
from unittest.mock import patch
TOOLS = Path(__file__).resolve().parents[1]
WORKSPACE = TOOLS.parent
SCRIPTS = WORKSPACE / 'src/sentry_sim/scripts'
sys.path.insert(0, str(TOOLS))
import project_env
class EnvironmentTest(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory(prefix='sentry env ')
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.env = os.environ.copy()
self.env['PYTHONDONTWRITEBYTECODE'] = '1'
for name in ('ROS_SETUP', 'ROS_INSTALL_ROOT', 'ROS_DISTRO', 'AMENT_PREFIX_PATH',
'SENTRY_BIN_DIR', 'NAV_BIN_DIR', 'SENTRY_FIELD_ROOT', 'SENTRY_MAP_YAML',
'GZ_BIN', 'GZ_FORCE_VERSION', 'BRIDGE_WAIT_TIMEOUT', 'GZ_PARTITION'):
self.env.pop(name, None)
def run_command(self, command, **overrides):
return subprocess.run(command, cwd=self.root, env={**self.env, **overrides},
capture_output=True, text=True, timeout=12)
def cli(self, *args, **overrides):
return self.run_command([sys.executable, str(TOOLS/'project_env.py'), *map(str, args)],
**overrides)
def shell(self, *args, **overrides):
return self.run_command(['bash', '-c', 'source "$1"; shift; "$@"',
'env-test', str(SCRIPTS/'env_common.sh'), *map(str, args)],
**overrides)
def executable(self, path, script='exit 0'):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('#!/bin/bash\n' + script + '\n')
path.chmod(0o755)
return path
def expect_value(self, result, value):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, f'{value}\n')
def expect_error(self, result, text, code=1):
self.assertEqual(result.returncode, code, result.stderr)
self.assertEqual(result.stdout, '')
self.assertIn(text, result.stderr)
def test_map_overrides(self):
field = self.root/'field with spaces'
field.mkdir()
yaml = self.root/'custom map.yaml'
yaml.touch()
for bad in (self.root/'missing.yaml', field):
with self.subTest(path=bad):
self.expect_error(self.cli('--map', SENTRY_MAP_YAML=str(bad)), 'SENTRY_MAP_YAML')
self.expect_error(self.shell('env_map_yaml', field, SENTRY_MAP_YAML=str(bad)),
'SENTRY_MAP_YAML')
self.expect_value(self.cli('--map', SENTRY_MAP_YAML=yaml.name), yaml)
self.expect_value(self.shell('env_map_yaml', field, SENTRY_MAP_YAML=yaml.name), yaml)
with patch.dict(os.environ, {'SENTRY_MAP_YAML': str(field)}):
self.assertEqual(project_env.find_map_yaml(field, explicit=yaml), yaml)
def test_map_search_order(self):
field = self.root/'field'
maps = field/'src/guodong_sentry_sim/maps'
canonical = maps/'rmul_2027/rmul_2027.yaml'
named_first = maps/'a/rmul_2027.yaml'
named_last = maps/'z/rmul_2027.yaml'
fallback = maps/'a/001.yaml'
for path in (canonical, named_first, named_last, fallback):
path.parent.mkdir(parents=True, exist_ok=True)
path.touch()
(maps/'a/000.yaml').mkdir()
def expect_map(path):
self.expect_value(self.cli('--map', SENTRY_FIELD_ROOT=str(field)), path)
self.expect_value(self.shell('env_map_yaml', field), path)
expect_map(canonical)
canonical.unlink()
expect_map(named_first)
named_first.unlink()
expect_map(named_last)
named_last.unlink()
expect_map(fallback)
fallback.unlink()
self.expect_error(self.cli('--map', SENTRY_FIELD_ROOT=str(field)), 'SENTRY_MAP_YAML')
self.expect_error(self.shell('env_map_yaml', field), 'SENTRY_MAP_YAML')
def test_field_and_ros_setup_overrides(self):
field = self.root/'field'
other = self.root/'other field'
field.mkdir()
other.mkdir()
self.expect_error(self.cli('--field', SENTRY_FIELD_ROOT=str(field/'missing')),
'SENTRY_FIELD_ROOT')
self.expect_error(self.shell('env_field_root', self.root,
SENTRY_FIELD_ROOT=str(field/'missing')), 'SENTRY_FIELD_ROOT')
self.expect_value(self.cli('--field', SENTRY_FIELD_ROOT=field.name), field)
with patch.dict(os.environ, {'SENTRY_FIELD_ROOT': str(field)}):
self.assertEqual(project_env.find_field_root(self.root, explicit=other), other)
setup = self.root/'setup with spaces.bash'
setup.write_text('export SENTRY_SETUP_TEST=loaded\n')
for invalid in (field, self.root/'missing.bash'):
self.expect_error(self.cli('--ros-setup', ROS_SETUP=str(invalid)), 'ROS_SETUP')
self.expect_error(self.shell('env_source_ros', ROS_SETUP=str(invalid)), 'ROS_SETUP')
self.expect_value(self.cli('--ros-setup', ROS_SETUP=setup.name), setup)
result = self.run_command(
['bash', '-c', 'source "$1"; env_source_ros && printf "%s\\n" "$SENTRY_SETUP_TEST"',
'env-test', str(SCRIPTS/'env_common.sh')], ROS_SETUP=setup.name)
self.expect_value(result, 'loaded')
ros2 = self.executable(self.root/'ros bin/ros2')
self.expect_value(self.cli('--ros-setup', ROS_SETUP=str(setup), AMENT_PREFIX_PATH='/fake',
PATH=f'{ros2.parent}:{self.env["PATH"]}'), '')
def test_cli_status_and_stdout(self):
self.expect_error(self.cli('--unknown'), 'unrecognized arguments', code=2)
self.expect_error(self.cli('--map', '--gz'), 'not allowed', code=2)
self.expect_error(self.cli('--gz', '--field-root', self.root), 'requires --map', code=2)
self.expect_error(self.cli('--bin-dir', SENTRY_BIN_DIR=str(self.root/'missing')),
'SENTRY_BIN_DIR')
with (patch.object(project_env, '_GZ_CANDIDATES', ()),
patch.object(project_env.shutil, 'which', return_value=None),
patch.dict(os.environ, {'GZ_BIN': ''})):
with self.assertRaisesRegex(project_env.ProbeError, '找不到 Gazebo'):
project_env.find_gz_bin()
def test_build_directory_priority_matches_shell(self):
build = self.root/'build'
unified = build/'bin'
def expect_bin(path, **overrides):
self.expect_value(self.cli(self.root, '--bin-dir', **overrides), path)
self.expect_value(self.shell('env_bin_dir', self.root, **overrides), path)
expect_bin(unified)
debug = self.executable(build/'a/first/debug/self_filter')
expect_bin(debug.parent)
release_last = self.executable(build/'z/last/release/nav_client')
release_first = self.executable(build/'a/second/release/odom_tf')
(build/'a/first/release').mkdir()
(build/'a/first/release/nav_client').touch()
expect_bin(release_first.parent)
(unified/'self_filter').mkdir(parents=True)
(unified/'nav_client').touch()
expect_bin(release_first.parent)
self.executable(unified/'cmd_vel_relay')
expect_bin(unified)
expect_bin(release_last.parent, NAV_BIN_DIR=str(release_last.parent))
expect_bin(release_first.parent, SENTRY_BIN_DIR=str(release_first.parent),
NAV_BIN_DIR=str(release_last.parent))
def test_gz_executable_validation_matches_shell(self):
fake = self.executable(self.root/'fake gazebo')
alias = self.root/'link to gz'
alias.symlink_to(fake)
denied = self.root/'non-executable'
denied.touch()
for path in (self.root, denied, self.root/'missing'):
with self.subTest(path=path):
self.expect_error(self.cli('--gz', GZ_BIN=str(path)), 'GZ_BIN')
self.expect_error(self.shell('env_gz_bin', GZ_BIN=str(path)), 'GZ_BIN')
self.expect_error(self.cli('--gz-version-args', GZ_FORCE_VERSION='12',
GZ_BIN=str(path)), 'GZ_BIN')
self.expect_value(self.cli('--gz', GZ_BIN=alias.name), alias)
self.expect_value(self.shell('env_gz_bin', GZ_BIN=alias.name), alias)
def test_version_and_explicit_override_matches_shell(self):
fake = self.executable(self.root/'fake gz', '''
if [[ "$*" != "sim --version" || -v LD_LIBRARY_PATH ]]; then exit 4; fi
touch "$SENTRY_GZ_MARKER"
echo ' 10.5.0 '
''')
marker = self.root/'probe-called'
env = dict(GZ_BIN=str(fake), LD_LIBRARY_PATH='/test/vendor', SENTRY_GZ_MARKER=str(marker))
self.expect_value(self.cli('--gz-version-args', **env), '--force-version 10')
self.assertTrue(marker.is_file())
self.expect_value(self.shell('env_gz_version_args', **env), '--force-version\n10')
marker.unlink()
self.expect_value(self.cli('--gz-version-args', GZ_FORCE_VERSION='12', **env),
'--force-version 12')
self.expect_value(self.shell('env_gz_version_args', GZ_FORCE_VERSION='12', **env),
'--force-version\n12')
self.assertFalse(marker.exists())
def test_version_nonzero_and_unparseable_warn_and_continue(self):
fake = self.root/'gz'
for script, reason in (("echo '10.0'; exit 7", '退出码 7'), ('echo unknown', '无法解析版本')):
self.executable(fake, script)
cli = self.cli('--gz-version-args', GZ_BIN=str(fake))
shell = self.shell('env_gz_version_args', GZ_BIN=str(fake))
self.expect_value(cli, '')
self.assertIn(reason, cli.stderr)
self.assertEqual(shell.returncode, 0, shell.stderr)
self.assertEqual(shell.stdout, '')
self.assertIn(reason, shell.stderr)
def test_version_timeout_stops_owned_process_group(self):
marker = self.root/'child-pids'
fake = self.executable(self.root/'slow gz', '''
trap '' TERM
sleep 30 &
printf '%s %s\\n' "$$" "$!" > "$SENTRY_GZ_MARKER"
wait
''')
start = time.monotonic()
result = self.shell('env_gz_version_args', GZ_BIN=str(fake), SENTRY_GZ_MARKER=str(marker))
elapsed = time.monotonic() - start
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, '')
self.assertIn('超时', result.stderr)
self.assertGreaterEqual(elapsed, 5)
self.assertLess(elapsed, 8)
for pid in marker.read_text().split():
try:
state = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[0]
except FileNotFoundError:
continue
self.assertEqual(state, 'Z', f'Gazebo probe process {pid} is still live')
def test_bridge_does_not_start_without_clock(self):
fake_gz = self.executable(self.root/'fake gz', '''
[[ "$*" == 'topic -e -t /clock -n 1' && ! -v LD_LIBRARY_PATH ]] || exit 4
sleep 30
''')
fake_ros2 = self.executable(self.root/'bin/ros2', 'echo "bridge started"')
env = dict(BRIDGE_WAIT_TIMEOUT='0.3', GZ_BIN=str(fake_gz), LD_LIBRARY_PATH='/vendor',
PATH=f'{fake_ros2.parent}:{self.env["PATH"]}', GZ_PARTITION='isolated_test')
start = time.monotonic()
result = self.run_command(['bash', str(SCRIPTS/'bridge_after_gz.sh')], **env)
self.assertLess(time.monotonic() - start, 2)
self.expect_error(result, '等待 Gazebo /clock 超时')
self.assertIn('isolated_test', result.stderr)
self.executable(fake_gz, '''
[[ "$*" == 'topic -e -t /clock -n 1' && ! -v LD_LIBRARY_PATH ]] || exit 4
echo 'sim { sec: 1 }'
''')
result = self.run_command(['bash', str(SCRIPTS/'bridge_after_gz.sh')], **env)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('bridge started', result.stdout)
if __name__ == '__main__':
unittest.main(verbosity=2)