unity-mcp/TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ManageGameObjectModifyTests.cs

448 lines
15 KiB
C#
Raw Normal View History

🎮 GameObject Toolset Redesign and Streamlining (#518) * feat: Redesign GameObject API for better LLM ergonomics ## New Tools - find_gameobjects: Search GameObjects, returns paginated instance IDs only - manage_components: Component lifecycle (add, remove, set_property) ## New Resources - unity://scene/gameobject/{id}: Single GameObject data (no component serialization) - unity://scene/gameobject/{id}/components: All components (paginated) - unity://scene/gameobject/{id}/component/{name}: Single component by type ## Updated - manage_scene get_hierarchy: Now includes componentTypes array - manage_gameobject: Slimmed to lifecycle only (create, modify, delete) - Legacy actions (find, get_components, etc.) log deprecation warnings ## Extracted Utilities - ParamCoercion: Centralized int/bool/float/string coercion - VectorParsing: Vector3/Vector2/Quaternion/Color parsing - GameObjectLookup: Centralized GameObject search logic ## Test Coverage - 76 new Unity EditMode tests for ManageGameObject actions - 21 new pytest tests for Python tools/resources - New NL/T CI suite for GameObject API (GO-0 to GO-5) Addresses LLM confusion with parameter overload by splitting into focused tools and read-only resources. * feat: Add static gameobject_api helper resource for UI discoverability Adds unity://scene/gameobject-api resource that: - Shows in Cursor's resource list UI (no parameters needed) - Documents the parameterized gameobject resources - Explains the workflow: find_gameobjects → read resource - Lists examples and related tools * feat: Add GO tests to main NL/T CI workflow - Adds GO pass (GO-0 to GO-5) after T pass in claude-nl-suite.yml - Includes retry logic for incomplete GO tests - Updates all regex patterns to recognize GO-* test IDs - Updates DESIRED lists to include all 21 tests (NL-0..4, T-A..J, GO-0..5) - Updates default_titles for GO tests in markdown summary - Keeps separate claude-gameobject-suite.yml for standalone runs * feat: Add GameObject API stress tests and NL/T suite updates Stress Tests (12 new tests): - BulkCreate small/medium batches - FindGameObjects pagination with by_component search - AddComponents to single object - GetComponents with full serialization - SetComponentProperties (complex Rigidbody) - Deep hierarchy creation and path lookup - GetHierarchy with large scenes - Resource read performance tests - RapidFire create-modify-delete cycles NL/T Suite Updates: - Added GO-0..GO-10 tests in nl-gameobject-suite.md - Fixed tool naming: mcp__unity__ → mcp__UnityMCP__ Other: - Fixed LongUnityScriptClaudeTest.cs compilation errors - Added reports/, .claude/local/, scripts/local-test/ to .gitignore All 254 EditMode tests pass (250 run, 4 explicit skips) * fix: Address code review feedback - ParamCoercion: Use CultureInfo.InvariantCulture for float parsing - ManageComponents: Move Transform removal check before GetComponent - ManageGameObjectFindTests: Use try-finally for LogAssert.ignoreFailingMessages - VectorParsing: Document that quaternions are not auto-normalized - gameobject.py: Prefix unused ctx parameter with underscore * fix: Address additional code review feedback - ManageComponents: Reuse GameObjectLookup.FindComponentType instead of duplicate - ManageComponents: Log warnings when SetPropertiesOnComponent fails - GameObjectLookup: Make FindComponentType public for reuse - gameobject.py: Extract _normalize_response helper to reduce duplication - gameobject.py: Add TODO comment for unused typed response classes * fix: Address more code review feedback NL/T Prompt Fixes: - nl-gameobject-suite.md: Remove non-existent list_resources/read_resource from AllowedTools - nl-gameobject-suite.md: Fix parameter names (component_type, properties) - nl-unity-suite-nl.md: Remove unused manage_editor from AllowedTools Test Fixes: - GameObjectAPIStressTests: Add null check to ToJObject helper - GameObjectAPIStressTests: Clarify AudioSource usage comment - ManageGameObjectFindTests: Use built-in 'UI' layer instead of 'Water' - LongUnityScriptClaudeTest: Clean up NL/T test artifacts (Counte42 typo, HasTarget) * docs: Add documentation for API limitations and behaviors - GameObjectLookup.SearchByPath: Document and warn that includeInactive has no effect (Unity API limitation) - ManageComponents.TrySetProperty: Document case-insensitive lookup behavior * More test fixes and tighten parameters on python tools * fix: Align test expectation with implementation error message case * docs: update README tools and resources lists - Add missing tools: manage_components, batch_execute, find_gameobjects, refresh_unity - Add missing resources: gameobject_api, editor_state_v2 - Make descriptions more concise across all tools and resources - Ensure documentation matches current MCP server functionality * fix: Address code review feedback - ParamCoercion: Use InvariantCulture for int/double parsing consistency - ManageComponents: Remove redundant Undo.RecordObject (AddComponent handles undo) - ManageScene: Replace deprecated FindObjectsOfType with FindObjectsByType - GameObjectLookup: Add explanatory comment to empty catch block - gameobject.py: Extract _validate_instance_id helper to reduce duplication - Tests: Fix assertion for instanceID (Unity IDs can be negative) * chore: Remove accidentally committed test artifacts - Remove Materials folder (40 .mat files from interactive testing) - Remove Shaders folder (5 noise shaders from testing) - Remove test scripts (Bounce*, CylinderBounce* from testing) - Remove Temp.meta and commit.sh * test: Improve delete tests to verify actual deletion - Delete_ByTag_DeletesMatchingObjects: Verify objects are actually destroyed - Delete_ByLayer_DeletesMatchingObjects: Assert deletion using Unity null check - Delete_MultipleObjectsSameName_DeletesCorrectly: Document first-match behavior - Delete_Success_ReturnsDeletedCount: Verify count value if present All tests now verify deletion occurred rather than just checking for a result. * refactor: remove deprecated manage_gameobject actions - Remove deprecated switch cases: find, get_components, get_component, add_component, remove_component, set_component_property - Remove deprecated wrapper methods (423 lines deleted from ManageGameObject.cs) - Delete ManageGameObjectFindTests.cs (tests deprecated 'find' action) - Remove deprecated test methods from ManageGameObjectTests.cs - Add GameObject resource URIs to README documentation - Add batch_execute performance tips to README, tool description, and gameobject_api resource - Enhance batch_execute description to emphasize 10-100x performance gains Total: ~1200 lines removed. New API (find_gameobjects, manage_components, resources) is the recommended path forward. * fix: Remove starlette stubs from conftest.py Starlette is now a proper dependency via the mcp package, so we don't need to stub it anymore. The real package handles all HTTP transport needs.
2026-01-07 02:13:45 +08:00
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using Newtonsoft.Json.Linq;
using MCPForUnity.Editor.Tools;
namespace MCPForUnityTests.Editor.Tools
{
/// <summary>
/// Comprehensive baseline tests for ManageGameObject "modify" action.
/// These tests capture existing behavior before API redesign.
/// </summary>
public class ManageGameObjectModifyTests
{
private List<GameObject> testObjects = new List<GameObject>();
[SetUp]
public void SetUp()
{
// Create a standard test object for each test
var go = new GameObject("ModifyTestObject");
go.transform.position = Vector3.zero;
go.transform.rotation = Quaternion.identity;
go.transform.localScale = Vector3.one;
testObjects.Add(go);
}
[TearDown]
public void TearDown()
{
foreach (var go in testObjects)
{
if (go != null)
{
Object.DestroyImmediate(go);
}
}
testObjects.Clear();
}
private GameObject CreateTestObject(string name)
{
var go = new GameObject(name);
testObjects.Add(go);
return go;
}
#region Target Resolution Tests
[Test]
public void Modify_ByName_FindsAndModifiesObject()
{
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["searchMethod"] = "by_name",
["position"] = new JArray { 10.0f, 0.0f, 0.0f }
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual(new Vector3(10f, 0f, 0f), testObjects[0].transform.position);
}
[Test]
public void Modify_ByInstanceID_FindsAndModifiesObject()
{
int instanceID = testObjects[0].GetInstanceID();
var p = new JObject
{
["action"] = "modify",
["target"] = instanceID,
["searchMethod"] = "by_id",
["position"] = new JArray { 20.0f, 0.0f, 0.0f }
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual(new Vector3(20f, 0f, 0f), testObjects[0].transform.position);
}
[Test]
public void Modify_WithNameAlias_UsesNameAsTarget()
{
// When target is missing but name is provided, should use name as target
var p = new JObject
{
["action"] = "modify",
["name"] = "ModifyTestObject",
["position"] = new JArray { 30.0f, 0.0f, 0.0f }
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual(new Vector3(30f, 0f, 0f), testObjects[0].transform.position);
}
[Test]
public void Modify_NonExistentTarget_ReturnsError()
{
var p = new JObject
{
["action"] = "modify",
["target"] = "NonExistentObject12345",
["searchMethod"] = "by_name",
["position"] = new JArray { 0.0f, 0.0f, 0.0f }
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsFalse(resultObj.Value<bool>("success"), "Should fail for non-existent object");
}
[Test]
public void Modify_WithoutTarget_ReturnsError()
{
var p = new JObject
{
["action"] = "modify",
["position"] = new JArray { 0.0f, 0.0f, 0.0f }
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsFalse(resultObj.Value<bool>("success"), "Should fail without target");
}
#endregion
#region Transform Modification Tests
[Test]
public void Modify_Position_SetsNewPosition()
{
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["position"] = new JArray { 1.0f, 2.0f, 3.0f }
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual(new Vector3(1f, 2f, 3f), testObjects[0].transform.position);
}
[Test]
public void Modify_Rotation_SetsNewRotation()
{
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["rotation"] = new JArray { 0.0f, 90.0f, 0.0f }
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual(90f, testObjects[0].transform.eulerAngles.y, 0.1f);
}
[Test]
public void Modify_Scale_SetsNewScale()
{
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["scale"] = new JArray { 2.0f, 3.0f, 4.0f }
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual(new Vector3(2f, 3f, 4f), testObjects[0].transform.localScale);
}
[Test]
public void Modify_AllTransformProperties_SetsAll()
{
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["position"] = new JArray { 5.0f, 6.0f, 7.0f },
["rotation"] = new JArray { 45.0f, 45.0f, 45.0f },
["scale"] = new JArray { 0.5f, 0.5f, 0.5f }
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual(new Vector3(5f, 6f, 7f), testObjects[0].transform.position);
Assert.AreEqual(new Vector3(0.5f, 0.5f, 0.5f), testObjects[0].transform.localScale);
}
#endregion
#region Rename Tests
[Test]
public void Modify_Name_RenamesObject()
{
// Get instanceID first since name will change
int instanceID = testObjects[0].GetInstanceID();
var p = new JObject
{
["action"] = "modify",
["target"] = instanceID,
["searchMethod"] = "by_id",
["name"] = "RenamedObject" // Uses 'name' parameter, not 'newName'
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual("RenamedObject", testObjects[0].name);
}
[Test]
public void Modify_NameToEmpty_HandlesGracefully()
{
int instanceID = testObjects[0].GetInstanceID();
var p = new JObject
{
["action"] = "modify",
["target"] = instanceID,
["searchMethod"] = "by_id",
["name"] = "" // Empty name
};
var result = ManageGameObject.HandleCommand(p);
// Capture current behavior - may reject or allow empty name
Assert.IsNotNull(result, "Should return a result");
}
#endregion
#region Reparenting Tests
[Test]
public void Modify_Parent_ReparentsObject()
{
var parent = CreateTestObject("NewParent");
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["parent"] = "NewParent"
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual(parent.transform, testObjects[0].transform.parent);
}
[Test]
public void Modify_ParentToNull_UnparentsObject()
{
// First parent the object
var parent = CreateTestObject("TempParent");
testObjects[0].transform.SetParent(parent.transform);
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["parent"] = JValue.CreateNull()
};
var result = ManageGameObject.HandleCommand(p);
// Capture current behavior for null parent
Assert.IsNotNull(result, "Should return a result");
}
[Test]
public void Modify_ParentToNonExistent_HandlesGracefully()
{
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["parent"] = "NonExistentParent12345"
};
var result = ManageGameObject.HandleCommand(p);
// Should fail or handle gracefully
Assert.IsNotNull(result, "Should return a result");
}
#endregion
#region Active State Tests
[Test]
public void Modify_SetActive_DeactivatesObject()
{
Assert.IsTrue(testObjects[0].activeSelf, "Object should start active");
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["setActive"] = false
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.IsFalse(testObjects[0].activeSelf, "Object should be deactivated");
}
[Test]
public void Modify_SetActive_ActivatesObject()
{
testObjects[0].SetActive(false);
Assert.IsFalse(testObjects[0].activeSelf, "Object should start inactive");
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["setActive"] = true
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.IsTrue(testObjects[0].activeSelf, "Object should be activated");
}
#endregion
#region Tag and Layer Tests
[Test]
public void Modify_Tag_SetsNewTag()
{
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["tag"] = "MainCamera"
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual("MainCamera", testObjects[0].tag);
}
[Test]
public void Modify_Layer_SetsNewLayer()
{
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["layer"] = "UI"
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual(LayerMask.NameToLayer("UI"), testObjects[0].layer);
}
[Test]
public void Modify_InvalidTag_HandlesGracefully()
{
// Expect the error log from Unity about invalid tag
UnityEngine.TestTools.LogAssert.Expect(LogType.Error,
new System.Text.RegularExpressions.Regex("Tag:.*NonExistentTag12345.*not defined"));
var p = new JObject
{
["action"] = "modify",
["target"] = "ModifyTestObject",
["tag"] = "NonExistentTag12345"
};
var result = ManageGameObject.HandleCommand(p);
// Current behavior: logs error but continues
Assert.IsNotNull(result, "Should return a result");
}
#endregion
#region Multiple Modifications Tests
[Test]
public void Modify_MultipleProperties_AppliesAll()
{
var parent = CreateTestObject("MultiModifyParent");
int instanceID = testObjects[0].GetInstanceID();
var p = new JObject
{
["action"] = "modify",
["target"] = instanceID,
["searchMethod"] = "by_id",
["name"] = "MultiModifiedObject", // Uses 'name' not 'newName'
["position"] = new JArray { 100.0f, 200.0f, 300.0f },
["scale"] = new JArray { 5.0f, 5.0f, 5.0f },
["parent"] = "MultiModifyParent",
["tag"] = "MainCamera"
};
var result = ManageGameObject.HandleCommand(p);
var resultObj = result as JObject ?? JObject.FromObject(result);
Assert.IsTrue(resultObj.Value<bool>("success"), resultObj.ToString());
Assert.AreEqual("MultiModifiedObject", testObjects[0].name);
Assert.AreEqual(parent.transform, testObjects[0].transform.parent);
Assert.AreEqual("MainCamera", testObjects[0].tag);
}
#endregion
}
}