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

93 lines
3.6 KiB
C#
Raw Normal View History

feat: Add `manage_material` tool for dedicated material manipulation (#440) * WIP: Material management tool implementation and tests - Add ManageMaterial tool for creating and modifying materials - Add MaterialOps helper for material property operations - Add comprehensive test suite for material management - Add string parameter parsing support for material properties - Update related tools (ManageGameObject, manage_asset, etc.) - Add test materials and scenes for material testing * refactor: unify material property logic into MaterialOps - Move and logic from to - Update to delegate to - Update to use enhanced for creation and property setting - Add texture path loading support to * Add parameter aliasing support: accept 'name' as alias for 'target' in manage_gameobject modify action * Refactor ManageMaterial and fix code review issues - Fix Python server tools (redundant imports, exception handling, string formatting) - Clean up documentation and error reports - Improve ManageMaterial.cs (overwrite checks, error handling) - Enhance MaterialOps.cs (robustness, logging, dead code removal) - Update tests (assertions, unused imports) - Fix manifest.json relative path - Remove temporary test artifacts and manual setup scripts * Remove test scene * remove extra mat * Remove unnecessary SceneTemplateSettings.json * Remove unnecessary SceneTemplateSettings.json * Fix MaterialOps issues * Fix: Case-insensitive material property lookup and missing HasProperty checks * Rabbit fixes * Improve material ops logging and test coverage * Fix: NormalizePath now handles backslashes correctly using AssetPathUtility * Fix: Address multiple nitpicks (test robustness, shader resolution, HasProperty checks) * Add manage_material tool documentation and fix MaterialOps texture property checks - Add comprehensive ManageMaterial tool documentation to MCPForUnity/README.md - Add manage_material to tools list in README.md and README-zh.md - Fix MaterialOps.cs to check HasProperty before SetTexture calls to prevent Unity warnings - Ensures consistency with other property setters in MaterialOps * Fix ManageMaterial shader reflection for Unity 6 and improve texture logging
2025-12-08 11:39:52 +08:00
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
using MCPForUnity.Editor.Tools;
using MCPForUnity.Editor.Helpers;
namespace MCPForUnityTests.Editor.Tools
{
public class ReadConsoleTests
{
[Test]
public void HandleCommand_Clear_Works()
{
// Arrange
// Ensure there's something to clear
Debug.Log("Log to clear");
// Verify content exists before clear
Codex/optimize and paginate read console tool (#511) * Optimize read_console defaults and paging * Fix read_console truncate test expectations * Reduce read_console default count from 50 to 10 Further optimize token usage by reducing the default count from 50 to 10 entries. Even 10-20 messages with stack traces can be token-heavy. Added tests for default behavior and paging functionality. Updated tool description to document defaults and paging support. * Fix ReadConsoleTests to include log type messages The default types filter changed to ['error', 'warning'] (excluding 'log'), so tests using Debug.Log() need to explicitly request log messages. Also added format='detailed' to HandleCommand_Get_Works test since it accesses structured message fields. * Address CodeRabbit review feedback - Fix property naming consistency: next_cursor -> nextCursor (C# camelCase) - Remove redundant EndGettingEntries call from catch block (already in finally) - Extract stacktrace stripping to helper function (reduce duplication) - Fix test mock to match actual C# response structure (items, nextCursor, truncated, total) * perf: add early exit optimization for ReadConsole paging - Add early exit in paging loop once page is filled, avoiding iteration through remaining console entries (total becomes 'at least N') - Prefix unused mock arguments with underscores in test_read_console_truncate.py to suppress Ruff linter warnings * refactor: give pageSize independent default, clarify count semantics - Change pageSize resolution from 'pageSize ?? count ?? 50' to 'pageSize ?? 50' so pageSize has its own default independent of count - count now only serves as the non-paging limit - Add XML docs to GetConsoleEntries with clear parameter descriptions - Update Python tool annotations to document pageSize default (50) and clarify that count is ignored when paging
2026-01-05 06:46:52 +08:00
var getBefore = ToJObject(ReadConsole.HandleCommand(new JObject { ["action"] = "get", ["types"] = new JArray { "error", "warning", "log" }, ["count"] = 10 }));
feat: Add `manage_material` tool for dedicated material manipulation (#440) * WIP: Material management tool implementation and tests - Add ManageMaterial tool for creating and modifying materials - Add MaterialOps helper for material property operations - Add comprehensive test suite for material management - Add string parameter parsing support for material properties - Update related tools (ManageGameObject, manage_asset, etc.) - Add test materials and scenes for material testing * refactor: unify material property logic into MaterialOps - Move and logic from to - Update to delegate to - Update to use enhanced for creation and property setting - Add texture path loading support to * Add parameter aliasing support: accept 'name' as alias for 'target' in manage_gameobject modify action * Refactor ManageMaterial and fix code review issues - Fix Python server tools (redundant imports, exception handling, string formatting) - Clean up documentation and error reports - Improve ManageMaterial.cs (overwrite checks, error handling) - Enhance MaterialOps.cs (robustness, logging, dead code removal) - Update tests (assertions, unused imports) - Fix manifest.json relative path - Remove temporary test artifacts and manual setup scripts * Remove test scene * remove extra mat * Remove unnecessary SceneTemplateSettings.json * Remove unnecessary SceneTemplateSettings.json * Fix MaterialOps issues * Fix: Case-insensitive material property lookup and missing HasProperty checks * Rabbit fixes * Improve material ops logging and test coverage * Fix: NormalizePath now handles backslashes correctly using AssetPathUtility * Fix: Address multiple nitpicks (test robustness, shader resolution, HasProperty checks) * Add manage_material tool documentation and fix MaterialOps texture property checks - Add comprehensive ManageMaterial tool documentation to MCPForUnity/README.md - Add manage_material to tools list in README.md and README-zh.md - Fix MaterialOps.cs to check HasProperty before SetTexture calls to prevent Unity warnings - Ensures consistency with other property setters in MaterialOps * Fix ManageMaterial shader reflection for Unity 6 and improve texture logging
2025-12-08 11:39:52 +08:00
Assert.IsTrue(getBefore.Value<bool>("success"), getBefore.ToString());
var entriesBefore = getBefore["data"] as JArray;
// Ideally we'd assert count > 0, but other tests/system logs might affect this.
// Just ensuring the call doesn't fail is a baseline, but let's try to be stricter if possible.
// Since we just logged, there should be at least one entry.
Assert.IsTrue(entriesBefore != null && entriesBefore.Count > 0, "Setup failed: console should have logs.");
// Act
var result = ToJObject(ReadConsole.HandleCommand(new JObject { ["action"] = "clear" }));
// Assert
Assert.IsTrue(result.Value<bool>("success"), result.ToString());
// Verify clear effect
Codex/optimize and paginate read console tool (#511) * Optimize read_console defaults and paging * Fix read_console truncate test expectations * Reduce read_console default count from 50 to 10 Further optimize token usage by reducing the default count from 50 to 10 entries. Even 10-20 messages with stack traces can be token-heavy. Added tests for default behavior and paging functionality. Updated tool description to document defaults and paging support. * Fix ReadConsoleTests to include log type messages The default types filter changed to ['error', 'warning'] (excluding 'log'), so tests using Debug.Log() need to explicitly request log messages. Also added format='detailed' to HandleCommand_Get_Works test since it accesses structured message fields. * Address CodeRabbit review feedback - Fix property naming consistency: next_cursor -> nextCursor (C# camelCase) - Remove redundant EndGettingEntries call from catch block (already in finally) - Extract stacktrace stripping to helper function (reduce duplication) - Fix test mock to match actual C# response structure (items, nextCursor, truncated, total) * perf: add early exit optimization for ReadConsole paging - Add early exit in paging loop once page is filled, avoiding iteration through remaining console entries (total becomes 'at least N') - Prefix unused mock arguments with underscores in test_read_console_truncate.py to suppress Ruff linter warnings * refactor: give pageSize independent default, clarify count semantics - Change pageSize resolution from 'pageSize ?? count ?? 50' to 'pageSize ?? 50' so pageSize has its own default independent of count - count now only serves as the non-paging limit - Add XML docs to GetConsoleEntries with clear parameter descriptions - Update Python tool annotations to document pageSize default (50) and clarify that count is ignored when paging
2026-01-05 06:46:52 +08:00
var getAfter = ToJObject(ReadConsole.HandleCommand(new JObject { ["action"] = "get", ["types"] = new JArray { "error", "warning", "log" }, ["count"] = 10 }));
feat: Add `manage_material` tool for dedicated material manipulation (#440) * WIP: Material management tool implementation and tests - Add ManageMaterial tool for creating and modifying materials - Add MaterialOps helper for material property operations - Add comprehensive test suite for material management - Add string parameter parsing support for material properties - Update related tools (ManageGameObject, manage_asset, etc.) - Add test materials and scenes for material testing * refactor: unify material property logic into MaterialOps - Move and logic from to - Update to delegate to - Update to use enhanced for creation and property setting - Add texture path loading support to * Add parameter aliasing support: accept 'name' as alias for 'target' in manage_gameobject modify action * Refactor ManageMaterial and fix code review issues - Fix Python server tools (redundant imports, exception handling, string formatting) - Clean up documentation and error reports - Improve ManageMaterial.cs (overwrite checks, error handling) - Enhance MaterialOps.cs (robustness, logging, dead code removal) - Update tests (assertions, unused imports) - Fix manifest.json relative path - Remove temporary test artifacts and manual setup scripts * Remove test scene * remove extra mat * Remove unnecessary SceneTemplateSettings.json * Remove unnecessary SceneTemplateSettings.json * Fix MaterialOps issues * Fix: Case-insensitive material property lookup and missing HasProperty checks * Rabbit fixes * Improve material ops logging and test coverage * Fix: NormalizePath now handles backslashes correctly using AssetPathUtility * Fix: Address multiple nitpicks (test robustness, shader resolution, HasProperty checks) * Add manage_material tool documentation and fix MaterialOps texture property checks - Add comprehensive ManageMaterial tool documentation to MCPForUnity/README.md - Add manage_material to tools list in README.md and README-zh.md - Fix MaterialOps.cs to check HasProperty before SetTexture calls to prevent Unity warnings - Ensures consistency with other property setters in MaterialOps * Fix ManageMaterial shader reflection for Unity 6 and improve texture logging
2025-12-08 11:39:52 +08:00
Assert.IsTrue(getAfter.Value<bool>("success"), getAfter.ToString());
var entriesAfter = getAfter["data"] as JArray;
Assert.IsTrue(entriesAfter == null || entriesAfter.Count == 0, "Console should be empty after clear.");
}
[Test]
public void HandleCommand_Get_Works()
{
// Arrange
string uniqueMessage = $"Test Log Message {Guid.NewGuid()}";
Debug.Log(uniqueMessage);
var paramsObj = new JObject
{
["action"] = "get",
Codex/optimize and paginate read console tool (#511) * Optimize read_console defaults and paging * Fix read_console truncate test expectations * Reduce read_console default count from 50 to 10 Further optimize token usage by reducing the default count from 50 to 10 entries. Even 10-20 messages with stack traces can be token-heavy. Added tests for default behavior and paging functionality. Updated tool description to document defaults and paging support. * Fix ReadConsoleTests to include log type messages The default types filter changed to ['error', 'warning'] (excluding 'log'), so tests using Debug.Log() need to explicitly request log messages. Also added format='detailed' to HandleCommand_Get_Works test since it accesses structured message fields. * Address CodeRabbit review feedback - Fix property naming consistency: next_cursor -> nextCursor (C# camelCase) - Remove redundant EndGettingEntries call from catch block (already in finally) - Extract stacktrace stripping to helper function (reduce duplication) - Fix test mock to match actual C# response structure (items, nextCursor, truncated, total) * perf: add early exit optimization for ReadConsole paging - Add early exit in paging loop once page is filled, avoiding iteration through remaining console entries (total becomes 'at least N') - Prefix unused mock arguments with underscores in test_read_console_truncate.py to suppress Ruff linter warnings * refactor: give pageSize independent default, clarify count semantics - Change pageSize resolution from 'pageSize ?? count ?? 50' to 'pageSize ?? 50' so pageSize has its own default independent of count - count now only serves as the non-paging limit - Add XML docs to GetConsoleEntries with clear parameter descriptions - Update Python tool annotations to document pageSize default (50) and clarify that count is ignored when paging
2026-01-05 06:46:52 +08:00
["types"] = new JArray { "error", "warning", "log" },
["format"] = "detailed",
feat: Add `manage_material` tool for dedicated material manipulation (#440) * WIP: Material management tool implementation and tests - Add ManageMaterial tool for creating and modifying materials - Add MaterialOps helper for material property operations - Add comprehensive test suite for material management - Add string parameter parsing support for material properties - Update related tools (ManageGameObject, manage_asset, etc.) - Add test materials and scenes for material testing * refactor: unify material property logic into MaterialOps - Move and logic from to - Update to delegate to - Update to use enhanced for creation and property setting - Add texture path loading support to * Add parameter aliasing support: accept 'name' as alias for 'target' in manage_gameobject modify action * Refactor ManageMaterial and fix code review issues - Fix Python server tools (redundant imports, exception handling, string formatting) - Clean up documentation and error reports - Improve ManageMaterial.cs (overwrite checks, error handling) - Enhance MaterialOps.cs (robustness, logging, dead code removal) - Update tests (assertions, unused imports) - Fix manifest.json relative path - Remove temporary test artifacts and manual setup scripts * Remove test scene * remove extra mat * Remove unnecessary SceneTemplateSettings.json * Remove unnecessary SceneTemplateSettings.json * Fix MaterialOps issues * Fix: Case-insensitive material property lookup and missing HasProperty checks * Rabbit fixes * Improve material ops logging and test coverage * Fix: NormalizePath now handles backslashes correctly using AssetPathUtility * Fix: Address multiple nitpicks (test robustness, shader resolution, HasProperty checks) * Add manage_material tool documentation and fix MaterialOps texture property checks - Add comprehensive ManageMaterial tool documentation to MCPForUnity/README.md - Add manage_material to tools list in README.md and README-zh.md - Fix MaterialOps.cs to check HasProperty before SetTexture calls to prevent Unity warnings - Ensures consistency with other property setters in MaterialOps * Fix ManageMaterial shader reflection for Unity 6 and improve texture logging
2025-12-08 11:39:52 +08:00
["count"] = 1000 // Fetch enough to likely catch our message
};
// Act
var result = ToJObject(ReadConsole.HandleCommand(paramsObj));
// Assert
Assert.IsTrue(result.Value<bool>("success"), result.ToString());
var data = result["data"] as JArray;
Assert.IsNotNull(data, "Data array should not be null.");
Assert.IsTrue(data.Count > 0, "Should retrieve at least one log entry.");
// Verify content
bool found = false;
foreach (var entry in data)
{
if (entry["message"]?.ToString().Contains(uniqueMessage) == true)
{
found = true;
break;
}
}
Assert.IsTrue(found, $"The unique log message '{uniqueMessage}' was not found in retrieved logs.");
}
private static JObject ToJObject(object result)
{
if (result == null)
{
Assert.Fail("ReadConsole.HandleCommand returned null.");
return new JObject(); // Unreachable, but satisfies return type.
}
return result as JObject ?? JObject.FromObject(result);
}
}
}