unity2moveit2/unity-project/Assets/Scripts/Tests/ROSConnectionTest.cs
ayuan9957 fe15edcbd5 Initial commit: Unity-MoveIt2 integrated robotic arm simulation system
- Unity frontend with ROS-TCP-Connector for ROS2 communication
- Docker-based ROS2 Jazzy backend with MoveIt2 integration
- Support for 1-9 DOF manipulators
- UR5 robot configuration and URDF files
- Assembly task feasibility analysis tools
- Comprehensive documentation and deployment guides

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-13 12:08:34 +08:00

272 lines
10 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using Unity.Robotics.ROSTCPConnector;
namespace UnityMoveIt2.Tests
{
/// <summary>
/// ROS连接测试 / ROS Connection Test
/// 验证Unity与ROS2之间的TCP通信功能 / Verify TCP communication between Unity and ROS2
/// </summary>
public class ROSConnectionTest
{
private ROSConnection rosConnection;
private GameObject testGameObject;
#region / Test Setup and Teardown
[SetUp]
public void SetUp()
{
// 创建测试游戏对象 / Create test game object
testGameObject = new GameObject("TestROSConnection");
rosConnection = testGameObject.AddComponent<ROSConnection>();
// 配置连接参数 / Configure connection parameters
rosConnection.RosIPAddress = "127.0.0.1";
rosConnection.RosPort = 10000;
rosConnection.ConnectOnStart = false; // 手动控制连接 / Manual connection control
}
[TearDown]
public void TearDown()
{
// 清理测试对象 / Clean up test objects
if (rosConnection != null)
{
rosConnection.Disconnect();
}
if (testGameObject != null)
{
Object.DestroyImmediate(testGameObject);
}
}
#endregion
#region / Basic Connection Tests
/// <summary>
/// 测试1: 验证ROSConnection组件创建
/// Test 1: Verify ROSConnection component creation
/// </summary>
[Test]
public void Test01_ROSConnection_ComponentCreation()
{
// 验证组件已创建 / Verify component is created
Assert.IsNotNull(rosConnection, "ROSConnection组件应该被创建 / ROSConnection component should be created");
// 验证默认配置 / Verify default configuration
Assert.AreEqual("127.0.0.1", rosConnection.RosIPAddress, "默认IP应该是127.0.0.1 / Default IP should be 127.0.0.1");
Assert.AreEqual(10000, rosConnection.RosPort, "默认端口应该是10000 / Default port should be 10000");
Debug.Log("[测试通过] ROSConnection组件创建成功 / [Test Passed] ROSConnection component created successfully");
}
/// <summary>
/// 测试2: 验证连接到ROS2 TCP端点
/// Test 2: Verify connection to ROS2 TCP endpoint
/// </summary>
[UnityTest]
public IEnumerator Test02_ROSConnection_ConnectToROS2()
{
Debug.Log("[测试开始] 正在连接到ROS2... / [Test Start] Connecting to ROS2...");
// 尝试连接 / Attempt connection
rosConnection.Connect();
// 等待连接建立 / Wait for connection establishment
yield return new WaitForSeconds(2f);
// 验证连接状态 / Verify connection status
bool hasError = rosConnection.HasConnectionError;
if (!hasError)
{
Debug.Log("[测试通过] ✓ 成功连接到ROS2 TCP端点 / [Test Passed] ✓ Successfully connected to ROS2 TCP endpoint");
Assert.IsFalse(hasError, "连接应该成功 / Connection should succeed");
}
else
{
Debug.LogWarning("[测试警告] ✗ 连接失败 - 请确保ROS2服务正在运行 / [Test Warning] ✗ Connection failed - Make sure ROS2 service is running");
Debug.LogWarning("提示: 运行 'docker-compose up -d' 启动ROS2服务 / Hint: Run 'docker-compose up -d' to start ROS2 service");
// 这里不使用Assert.Fail因为ROS2服务可能未启动
// Don't use Assert.Fail here as ROS2 service might not be running
Assert.Inconclusive("ROS2服务未运行,测试无法完成 / ROS2 service not running, test inconclusive");
}
}
/// <summary>
/// 测试3: 验证连接保持
/// Test 3: Verify connection persistence
/// </summary>
[UnityTest]
public IEnumerator Test03_ROSConnection_KeepAlive()
{
Debug.Log("[测试开始] 测试连接保持... / [Test Start] Testing connection keep-alive...");
// 建立连接 / Establish connection
rosConnection.Connect();
yield return new WaitForSeconds(1f);
if (rosConnection.HasConnectionError)
{
Debug.LogWarning("[测试跳过] ROS2服务未运行 / [Test Skipped] ROS2 service not running");
Assert.Inconclusive("需要ROS2服务运行 / Requires ROS2 service running");
yield break;
}
// 保持连接5秒 / Keep connection for 5 seconds
Debug.Log("[测试中] 保持连接5秒... / [Testing] Keeping connection for 5 seconds...");
yield return new WaitForSeconds(5f);
// 验证连接仍然有效 / Verify connection is still valid
bool stillConnected = !rosConnection.HasConnectionError;
Assert.IsTrue(stillConnected, "连接应该保持活跃 / Connection should remain active");
Debug.Log("[测试通过] ✓ 连接保持成功 / [Test Passed] ✓ Connection kept alive successfully");
}
/// <summary>
/// 测试4: 验证断开连接
/// Test 4: Verify disconnection
/// </summary>
[UnityTest]
public IEnumerator Test04_ROSConnection_Disconnect()
{
Debug.Log("[测试开始] 测试断开连接... / [Test Start] Testing disconnection...");
// 先连接 / Connect first
rosConnection.Connect();
yield return new WaitForSeconds(1f);
if (rosConnection.HasConnectionError)
{
Debug.LogWarning("[测试跳过] ROS2服务未运行 / [Test Skipped] ROS2 service not running");
Assert.Inconclusive("需要ROS2服务运行 / Requires ROS2 service running");
yield break;
}
// 断开连接 / Disconnect
rosConnection.Disconnect();
yield return new WaitForSeconds(0.5f);
// 验证已断开 / Verify disconnection
bool isDisconnected = rosConnection.HasConnectionError;
Assert.IsTrue(isDisconnected, "应该显示为已断开 / Should show as disconnected");
Debug.Log("[测试通过] ✓ 断开连接成功 / [Test Passed] ✓ Disconnection successful");
}
#endregion
#region / Configuration Tests
/// <summary>
/// 测试5: 验证IP地址配置
/// Test 5: Verify IP address configuration
/// </summary>
[Test]
public void Test05_ROSConnection_IPConfiguration()
{
// 测试不同的IP配置 / Test different IP configurations
string[] testIPs = { "127.0.0.1", "localhost", "172.17.0.1" };
foreach (string ip in testIPs)
{
rosConnection.RosIPAddress = ip;
Assert.AreEqual(ip, rosConnection.RosIPAddress,
$"IP应该设置为{ip} / IP should be set to {ip}");
}
Debug.Log("[测试通过] IP配置测试成功 / [Test Passed] IP configuration test successful");
}
/// <summary>
/// 测试6: 验证端口配置
/// Test 6: Verify port configuration
/// </summary>
[Test]
public void Test06_ROSConnection_PortConfiguration()
{
// 测试不同的端口配置 / Test different port configurations
int[] testPorts = { 10000, 10001, 10002 };
foreach (int port in testPorts)
{
rosConnection.RosPort = port;
Assert.AreEqual(port, rosConnection.RosPort,
$"端口应该设置为{port} / Port should be set to {port}");
}
Debug.Log("[测试通过] 端口配置测试成功 / [Test Passed] Port configuration test successful");
}
#endregion
#region / Singleton Pattern Tests
/// <summary>
/// 测试7: 验证单例模式
/// Test 7: Verify singleton pattern
/// </summary>
[Test]
public void Test07_ROSConnection_SingletonPattern()
{
// 获取单例实例 / Get singleton instance
ROSConnection instance1 = ROSConnection.GetOrCreateInstance();
ROSConnection instance2 = ROSConnection.GetOrCreateInstance();
// 验证是同一个实例 / Verify same instance
Assert.AreSame(instance1, instance2,
"两次获取应该返回同一个实例 / Should return same instance twice");
Debug.Log("[测试通过] 单例模式验证成功 / [Test Passed] Singleton pattern verified");
}
#endregion
#region / Integration Test Notes
/// <summary>
/// 集成测试说明 / Integration Test Notes
///
/// 运行这些测试前,请确保:
/// Before running these tests, please ensure:
///
/// 1. Docker已安装并运行 / Docker is installed and running
/// 2. ROS2服务已启动: / ROS2 service is started:
/// cd docker
/// docker-compose up -d
/// 3. 端口10000可访问 / Port 10000 is accessible
/// 4. 防火墙允许连接 / Firewall allows connection
///
/// 查看ROS2服务状态: / Check ROS2 service status:
/// docker-compose ps
/// docker-compose logs ros2-unity
///
/// 测试网络连接: / Test network connection:
/// PowerShell: Test-NetConnection -ComputerName 127.0.0.1 -Port 10000
/// Python: python scripts/test_ros_tcp_connection.py
/// </summary>
[Test]
public void Test99_Integration_Instructions()
{
Debug.Log("=== ROS连接测试使用说明 / ROS Connection Test Instructions ===");
Debug.Log("1. 启动ROS2服务: docker-compose up -d");
Debug.Log("2. 验证服务状态: docker-compose ps");
Debug.Log("3. 运行测试套件: Unity Test Runner");
Debug.Log("4. 查看测试结果: 检查Console输出");
Debug.Log("================================================================");
Assert.Pass("这是一个说明性测试 / This is an informational test");
}
#endregion
}
}