### Test Player Setup With Fail Fast Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/test-case.md This example shows how to use 'fail fast' by checking for failures after critical assertions. This ensures that subsequent tests only run if preceding conditions are met, preventing cascading errors and improving clarity. ```gdscript func test_player_setup(): var player = create_player() # Check critical precondition first assert_object(player).is_not_null() if is_failure(): return # Now we can safely test player properties using fluent syntax assert_str(player.name)" \ .is_equal("Hero")\ .starts_with("H") if is_failure(): return assert_int(player.health)" \ .is_equal(100)" \ .is_greater(0) if is_failure(): return assert_bool(player.is_alive()).is_true() ``` -------------------------------- ### C# Signal Monitoring and Assertion Example Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/signals.md This C# example demonstrates starting signal monitoring on an emitter, verifying initial monitoring status, emitting signals, and asserting their emission with a timeout. It also checks the monitoring status of signals. ```csharp using System.Threading.Tasks; using GdUnit4.Asserts; using GdUnit4.Core.Signals; using static Assertions; [TestSuite] public partial class SignalAssertTest { public sealed partial class MyEmitter : Godot.Node { [Godot.Signal] public delegate void SignalAEventHandler(); [Godot.Signal] public delegate void SignalBEventHandler(string value); public void DoEmitSignalA() => EmitSignal(SignalName.SignalA); public void DoEmitSignalB() => EmitSignal(SignalName.SignalB, "foo"); } [TestCase(Timeout = 1000)] public async Task MonitorOnSignal() { var emitterA = AutoFree(new MyEmitter())!; var emitterB = AutoFree(new MyEmitter())!; // verify initial the emitters are not monitored AssertThat(GodotSignalCollector.Instance.IsSignalCollecting(emitterA, MyEmitter.SignalName.SignalA)).IsFalse(); AssertThat(GodotSignalCollector.Instance.IsSignalCollecting(emitterA, MyEmitter.SignalName.SignalB)).IsFalse(); AssertThat(GodotSignalCollector.Instance.IsSignalCollecting(emitterB, MyEmitter.SignalName.SignalA)).IsFalse(); AssertThat(GodotSignalCollector.Instance.IsSignalCollecting(emitterB, MyEmitter.SignalName.SignalB)).IsFalse(); // start monitoring on the emitter A AssertSignal(emitterA).StartMonitoring(); // verify the emitters are now monitored AssertThat(GodotSignalCollector.Instance.IsSignalCollecting(emitterA, MyEmitter.SignalName.SignalA)).IsTrue(); AssertThat(GodotSignalCollector.Instance.IsSignalCollecting(emitterA, MyEmitter.SignalName.SignalB)).IsTrue(); AssertThat(GodotSignalCollector.Instance.IsSignalCollecting(emitterB, MyEmitter.SignalName.SignalA)).IsFalse(); AssertThat(GodotSignalCollector.Instance.IsSignalCollecting(emitterB, MyEmitter.SignalName.SignalB)).IsFalse(); // verify the signals are not emitted initial await AssertSignal(emitterA).IsNotEmitted(MyEmitter.SignalName.SignalA).WithTimeout(50); ``` -------------------------------- ### Check .NET SDK Installation Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/CONTRIBUTING.md Verify that the .NET SDK is installed on your system. This command lists all installed SDK versions. ```bash dotnet --list-sdks ``` -------------------------------- ### GdScript Signal Monitoring Example Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/signals.md This example demonstrates starting signal monitoring on two emitter objects, verifying initial non-emission, emitting signals, and asserting their emission. It also shows verifying signals on one emitter while the other remains unmonitored. ```gdscript extends GdUnitTestSuite class MyEmitter extends Node: signal my_signal_a signal my_signal_b(value :String) func do_emit_a() -> void: my_signal_a.emit() func do_emit_b() -> void: my_signal_b.emit("foo") func test_monitor_signals() -> void: # start monitoring on the emitter to collect all emitted signals # use typed variables to enable Signal reference syntax (since v6.1) var emitter_a: MyEmitter = monitor_signals(MyEmitter.new()) var emitter_b: MyEmitter = monitor_signals(MyEmitter.new()) # verify the signals are not emitted initial await assert_signal(emitter_a).wait_until(50).is_not_emitted(emitter_a.my_signal_a) await assert_signal(emitter_a).wait_until(50).is_not_emitted(emitter_a.my_signal_b) await assert_signal(emitter_b).wait_until(50).is_not_emitted(emitter_b.my_signal_a) await assert_signal(emitter_b).wait_until(50).is_not_emitted(emitter_b.my_signal_b) # emit signal `my_signal_a` on emitter_a emitter_a.do_emit_a() await assert_signal(emitter_a).is_emitted(emitter_a.my_signal_a) # emit signal `my_signal_b` on emitter_a (variadic args since v6.1) emitter_a.do_emit_b() await assert_signal(emitter_a).is_emitted(emitter_a.my_signal_b, "foo") # verify emitter_b still has nothing emitted await assert_signal(emitter_b).wait_until(50).is_not_emitted(emitter_b.my_signal_a) await assert_signal(emitter_b).wait_until(50).is_not_emitted(emitter_b.my_signal_b) # now verify emitter b emitter_b.do_emit_a() await assert_signal(emitter_b).wait_until(50).is_emitted(emitter_b.my_signal_a) ``` -------------------------------- ### Verify .NET SDK Installation Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_csharp_project_setup/csharp-setup.md Run this command in your terminal to list installed .NET SDKs and ensure version 8.0 or 9.0 is present. ```bash dotnet --list-sdks 8.0.201 [C:\Program Files\dotnet\sdk] 9.0.100 [C:\Program Files\dotnet\sdk] ``` -------------------------------- ### Test Player Setup Without Fail Fast Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/test-case.md This example demonstrates a test case where assertions continue after a potential failure. In debug mode, a null reference error can halt execution, while in release mode, it may lead to confusing assertion failures. ```gdscript func test_player_setup(): var player = create_player() # If this fails, the following assertions may not make sense assert_object(player).is_not_null() # In debug mode: debugger will break here with null reference error if player is null # In release mode: will continue and show confusing assertion failure messages assert_str(player.name)" \ .is_equal("Hero")\ .starts_with("H") assert_int(player.health).is_equal(100) assert_bool(player.is_alive()).is_true() ``` -------------------------------- ### Example Class to Test Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/argument_matchers.md A simple class used in the argument matcher example. ```gdscript class_name MyClass extends Reference var _value:int func set_value(value :int): _value = value ``` -------------------------------- ### Assert String Starts With (C#) Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/assert-string.md Verifies that the current string starts with the specified prefix. This assertion fails if the string does not begin with the prefix. ```csharp AssertThat("This is a String").StartsWith("This is"); // this assertion fails AssertThat("This is a String").StartsWith("a String"); ``` -------------------------------- ### starts_with Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/assert-string.md Verifies that the current String or StringName starts with the given prefix. ```APIDOC ## starts_with ### Description Verifies that the current String or StringName starts with the given prefix. ### Parameters - **current** (String/StringName) - Required - The string to evaluate. - **expected** (String) - Required - The prefix to check. ### Example ```gd assert_str("This is a String").starts_with("This is") # Succeeds ``` ```cs AssertThat("This is a String").StartsWith("This is"); // Succeeds ``` ``` -------------------------------- ### Invoke scene method in C# Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/accessors.md Example demonstrating how to load a scene and access the instance via the SceneRunner. ```C# ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Invokes the function `start_color_cycle` var currentScene = runner.Scene(); ``` -------------------------------- ### Quick Start C# Test Suite Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/llms.txt Demonstrates basic assertions and parameterized testing using the GdUnit4 C# API. ```csharp using GdUnit4; using static GdUnit4.Assertions; [TestSuite] public class MyTest { [TestCase] public void StringContains() => AssertThat("Hello GdUnit4").Contains("GdUnit4"); [TestCase] public void ArrayHasSize() => AssertThat(new[] { 1, 2, 3 }).HasSize(3); // Parameterized test — each [TestCase] attribute is one run [TestCase("foo", 3)] [TestCase("hello", 5)] public void StringLength(string value, int expectedLength) => AssertThat(value).HasLength(expectedLength); } ``` -------------------------------- ### Test Resource as String Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/tools.md Example usage of resource_as_string. ```gdscript var rows = "row a\nrow b\n" var file_content := resource_as_string("res://myproject/test/resources/TestRows.txt") assert_string(rows).is_equal(file_content) ``` -------------------------------- ### Assert String Starts With (GdScript) Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/assert-string.md Verifies that the current string starts with the specified prefix. This assertion fails if the string does not begin with the prefix. ```gdscript assert_str("This is a String").starts_with("This is") # this assertion fails assert_str("This is a String").starts_with("a String") ``` -------------------------------- ### Complete C# Project Configuration Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_csharp_project_setup/csharp-setup.md Example of a fully configured .csproj file for a Godot 4.5 project using .NET 9.0 and GdUnit4. ```xml net9.0 13.0 enable true NU1605 none runtime; build; native; contentfiles; analyzers; buildtransitive ``` -------------------------------- ### Test Resource as Array Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/tools.md Example usage of resource_as_array. ```gdscript var rows = ["row a", "row b"] var file_content := resource_as_array("res://myproject/test/resources/TestRows.txt") assert_array(rows).contains_exactly(file_content) ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/CLAUDE.md Commands to build the Jekyll documentation site locally. Navigate to the documentation directory and install dependencies before serving. ```bash cd documentation bundle install bundle exec jekyll serve ``` -------------------------------- ### Simulate and Await Input Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/sync_inputs.md Example usage of simulating key presses and awaiting input processing completion. ```gd var runner := scene_runner("res://test_scene.tscn") # Simulates key combination ctrl+C is pressed runner.simulate_key_pressed(KEY_C, false, true) # finalize the input event processing await runner.await_input_processed() ``` ```cs ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Simulates key combination ctrl+C is pressed runner .SimulateKeyPress(Key.Ctrl) .SimulateKeyPress(Key.C); // finalize the input event processing await runner.AwaitInputProcessed(); ``` -------------------------------- ### GdUnit4 Core Assert Functions and Chaining Examples Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/addons/gdUnit4/test/CLAUDE.md Examples of using core GdUnit4 assert functions for primitives (bool, int, float, String) and objects, demonstrating chaining for multiple validations. ```gdscript # Primitives assert_bool(value).is_true() assert_bool(value).is_false() assert_int(value).is_equal(42) assert_int(value).is_not_equal(0) assert_int(value).is_greater(10).is_less(100) assert_float(value).is_equal_approx(3.14, 0.001) assert_str(value).is_equal("expected") assert_str(value).is_not_null().has_length(5).starts_with("ab").ends_with("cd").contains("bc") assert_str(value).is_empty() # Objects / variants assert_object(value).is_not_null() assert_object(value).is_instanceof(MyClass) assert_that(value).is_null() assert_that(value).is_equal(expected) assert_that(value).is_instanceof(Node) ``` -------------------------------- ### Configure Mock Working Modes Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/mock.md Examples demonstrating how to initialize mocks with different working modes to control function return values. ```gd var mock := mock(TestClass) as TestClass # Returns a default value (for String an empty value) assert_str(mock.message()).is_equal("") ``` ```gd # build a mock with mode CALL_REAL_FUNC var mock := mock(TestClass, CALL_REAL_FUNC) as TestClass # returns the real implementation value assert_str(mock.message()).is_equal("a message") # set a the return value to 'custom message' for the function message() do_return("custom message").on(mock).message() # now the function message will return 'custom message' assert_str(mock.message()).is_equal("custom message") ``` ```gd # build a mock with mode RETURN_DEEP_STUB var mock := mock(TestClass, RETURN_DEEP_STUB) as TestClass # returns a default value assert_str(mock.message()).is_equal("") # returns a mocked Path value assert_object(mock.path()).is_not_null() ``` -------------------------------- ### Basic GdUnit Test Example Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/README.md A simple GdUnit test case demonstrating basic assertion methods for string manipulation. Ensure the GdUnit plugin is installed to run this code. ```gdscript class_name GdUnitExampleTest extends GdUnitTestSuite func test_example(): assert_str("This is an example message")\ .has_length(26)\ .starts_with("This is an ex") ``` -------------------------------- ### Define Test Root Folder Paths Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_first_steps/settings.md Example paths showing the relationship between source files and their corresponding test files in the configured root folder. ```python res://project/src/folder_a/folder_b/my_class.gd res://project/test/folder_a/folder_b/my_class_test.gd ``` -------------------------------- ### Python Syntax Highlighting Example Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/addons/gdUnit4/test/update/resources/markdown.txt This snippet demonstrates Python syntax highlighting. It includes a simple print statement. ```python s = "Python syntax highlighting" print s ``` -------------------------------- ### Simulate Action Press in C# Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/actions.md Defines the SimulateActionPress method signature and provides a usage example. ```csharp /// /// Simulates that an action is press. /// /// The name of the action, e.g., "ui_up". /// The SceneRunner instance. ISceneRunner SimulateActionPress(string action); ``` ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Simulate the UP key is press by using the action "ui_up" runner.SimulateActionPress("ui_up"); await runner.AwaitInputProcessed(); ``` -------------------------------- ### Simulate Action Release in C# Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/actions.md Defines the SimulateActionRelease method signature and provides a usage example. ```csharp /// /// Simulates that an action has been released. /// /// The name of the action, e.g., "ui_up". /// The SceneRunner instance. ISceneRunner SimulateActionRelease(string action); ``` ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Simulate the UP key is released by using the action "ui_up" runner.SimulateActionRelease("ui-up"); await runner.AwaitInputProcessed(); ``` -------------------------------- ### Quick Start GDScript Test Suite Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/llms.txt Demonstrates basic assertions, signal monitoring, mocking, and scene interaction using the GdUnit4 GDScript API. ```gdscript extends GdUnitTestSuite func test_string_contains() -> void: assert_str("Hello GdUnit4").contains("GdUnit4") func test_array_has_size() -> void: assert_array([1, 2, 3]).has_size(3).contains(1, 2) func test_signal_emitted() -> void: var timer := auto_free(Timer.new()) add_child(timer) timer.start(0.1) await assert_signal(timer).is_emitted("timeout") func test_mock_example() -> void: var mock_node := mock(Node) mock_node.get_name() verify(mock_node).get_name() func test_scene_runner() -> void: # load a scene and wrap it in a runner var runner := scene_runner("res://scenes/MyGame.tscn") # simulate a key press and advance frames runner.simulate_key_pressed(KEY_SPACE) await runner.simulate_frames(30) # assert expected scene state assert_object(runner.find_child("Player")).is_not_null() ``` -------------------------------- ### Await Signal in C# Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/signals.md Provides the method signature and a test case example for awaiting signals in C#. ```csharp /// /// Waits for the specified signal to be emitted by a particular source node. /// If the signal is not emitted within the given timeout, the operation fails. /// /// The object from which the signal is emitted. /// The name of the signal to wait. /// An optional set of signal arguments. /// Task to wait. static async Task AwaitSignalOn(GodotObject source, string signal, params Variant[] args) ``` ```csharp [TestCase] public async Task ColorChangedSignals() { var sceneRunner = ISceneRunner.Load("res://test_scene.tscn"); var box1 = sceneRunner.GetProperty("Box1")!; var box2 = sceneRunner.GetProperty("Box2")!; var box3 = sceneRunner.GetProperty("Box3")!; // call function `start_color_cycle` to start the color cycle sceneRunner.Invoke("ColorCycle"); await AwaitSignalOn(box1, TestScene.SignalName.PanelColorChange, new Color(1, 0, 0)).WithTimeout(100); await AwaitSignalOn(box2, TestScene.SignalName.PanelColorChange, new Color(0, 0, 1)).WithTimeout(100); await AwaitSignalOn(box3, TestScene.SignalName.PanelColorChange, new Color(0, 1, 0)).WithTimeout(100); } ``` -------------------------------- ### JavaScript Syntax Highlighting Example Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/addons/gdUnit4/test/update/resources/markdown.txt This snippet demonstrates JavaScript syntax highlighting. It includes a simple alert function. ```javascript var s = "JavaScript syntax highlighting"; alert(s); ``` -------------------------------- ### Check gdlint Version Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/CLAUDE.md Verify the installed version of gdlint before proceeding with linting. ```bash gdlint --version ``` -------------------------------- ### Simulate Scene Interactions Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/sceneRunner.md Example of accessing scene properties, invoking methods, and simulating frame progression. ```gd func test_simulate_frames(timeout = 5000) -> void: # Create the scene runner for scene `test_scene.tscn` var runner := scene_runner("res://test_scene.tscn") # Get access to the loaded scene node var my_scene := runner.scene() # Get access to scene property '_box1' var box1: ColorRect = runner.get_property("_box1") # Verify it is initially set to white assert_object(box1.color).is_equal(Color.WHITE) # Start the color cycle by invoking the function 'start_color_cycle' and await 10 frames being processed runner.invoke("start_color_cycle") await runner.simulate_frames(10) # After 10 frames, the color should have changed to black assert_object(box1.color).is_equal(Color.BLACK) ``` ```cs [TestCase] public async Task simulate_frame() { // Create the scene runner for scene `test_scene.tscn` ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Get access to the loaded scene node var my_scene = runner.Scene(); // Get access to scene property '_box1' ColorRect box1 = runner.GetProperty("_box1"); // Verify it is initially set to white AssertObject(box1.color).IsEqual(Color.WHITE); // Start the color cycle by invoking the function 'start_color_cycle' and await 10 frames being processed runner.Invoke("start_color_cycle") await runner.SimulateFrames(10); // After 10 frames, the color should have changed to black AssertObject(box1.color).IsEqual(Color.BLACK); } ``` -------------------------------- ### GdScript ProjectSettings Management (Unnecessary) Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/hooks.md This example shows an unnecessary way to save and restore ProjectSettings. GdUnit4 automatically handles this, so manual saving and restoring in before/after hooks is not required. ```gdscript # unnecessary — the framework restores ProjectSettings automatically func before(): _saved = ProjectSettings.get_setting("some/setting") ProjectSettings.set_setting("some/setting", true) func after(): ProjectSettings.set_setting("some/setting", _saved) ``` -------------------------------- ### Spy and Verify Function Calls in GDScript Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/spy.md This example demonstrates creating a spy on a custom class instance, calling a method, and then verifying that the method was called exactly once. ```gdscript class_name TestClass extends Node func message() -> String: return "a message" func test_spy(): var instance = auto_free(TestClass.new()) # Build a spy on the instance var spy = spy(instance) # Call function `message` on the spy to track the interaction spy.message() # Verify the function 'message' is called one times verify(spy, 1).message() ``` -------------------------------- ### Example of using AutoFree() in C# Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/tools.md Register a Path object for freeing after the test is finished using AutoFree(). ```csharp using static Assertions; ... // using AutoFree() on Path object to register for freeing after the test is finished AssertObject(AutoFree(new Godot.Path())).IsNotInstanceOf(); ``` -------------------------------- ### Simulate mouse button press in C# Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/mouse.md Interface definition and usage example for mouse button presses in C#. ```cs /// /// Simulates a mouse button pressed. /// /// The mouse button identifier, one of the ButtonList button or button wheel constants. /// SceneRunner ISceneRunner SimulateMouseButtonPressed(ButtonList button); ``` ```cs ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Simulates pressing the left mouse button runner.SimulateMouseButtonPressed(ButtonList.Left); await runner.AwaitInputProcessed(); ``` -------------------------------- ### GdScript ProjectSettings Management (Correct) Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/hooks.md This example shows the correct way to set ProjectSettings for tests when needed. GdUnit4 automatically snapshots and restores ProjectSettings, so only the necessary changes for the test should be made. ```gdscript # correct — just set what the tests need func before(): ProjectSettings.set_setting("some/setting", true) ``` -------------------------------- ### Simulate absolute mouse movement in C# Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/mouse.md Interface definition and usage example for absolute mouse movement in C#. ```cs /// /// Simulates a mouse move to the absolute coordinates. /// /// The final position of the mouse. /// The time to move the mouse to the final position in seconds (default is 1 second). /// Sets the type of transition used (default is Linear). /// SceneRunner Task SimulateMouseMoveAbsolute(Vector2 position, double time = 1.0, Tween.TransitionType transitionType = Tween.TransitionType.Linear); ``` ```cs ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Set mouse position to an initial position runner.SimulateMouseMove(Vector2(10, 20)); await runner.AwaitInputProcessed(); // Simulate a mouse move from the current position to the absolute position within 1 second // the final position will be (400, 200) when is completed await runner.SimulateMouseMoveAbsolute(new Vector2(400, 200)); ``` -------------------------------- ### Simulate Mouse Button Press (C#) Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/mouse.md Simulates a mouse button press in C#. The method signature and usage example are provided. ```C# /// /// Simulates a mouse button press. (holding) /// /// The mouse button identifier, one of the ButtonList button or button wheel constants. /// Set to true to simulate a double-click. /// SceneRunner ISceneRunner SimulateMouseButtonPress(ButtonList button); ``` ```C# ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // simulates mouse left button is press runner.SimulateMouseButtonPress(ButtonList.Left); await runner.AwaitInputProcessed(); ``` -------------------------------- ### Verify Function Call Counts with Arguments Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/spy.md This example shows how to verify specific function call counts with different arguments. It includes verifying calls with `false` and `true` arguments, and demonstrates a failing verification. ```gdscript var spyed_node :Node = spy(Node.new()) # Verify we have no interactions currently on this instance verify_no_interactions(spyed_node) # Call with different arguments spyed_node.set_process(false) # 1 times spyed_node.set_process(true) # 1 times spyed_node.set_process(true) # 2 times # Verify how often we called the function with different argument verify(spyed_node, 1).set_process(false)# in sum one time with false verify(spyed_node, 2).set_process(true) # in sum two times with true # Verify will fail because we expect the function `set_process(true)` to be called 3 times but it was only called 2 times verify(spyed_node, 3).set_process(true) ``` -------------------------------- ### Simulate Mouse Button Release (C#) Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/mouse.md Simulates a mouse button release in C#. The method signature and usage example are provided. ```C# /// /// Simulates a mouse button released. /// /// The mouse button identifier, one of the ButtonList button or button wheel constants. /// SceneRunner ISceneRunner SimulateMouseButtonRelease(ButtonList button); ``` ```C# ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Simulates a mouse left button is released runner.SimulateMouseButtonRelease(ButtonList.Left); await runner.AwaitInputProcessed(); ``` -------------------------------- ### GdScript Resource Cleanup Example Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/hooks.md Demonstrates cleaning up resources like file handles and timers in after_test hooks. Timers can be automatically freed using auto_free(). ```gdscript func before_test(): _file = FileAccess.open("test.txt", FileAccess.WRITE) _timer = auto_free(Timer.new()) func after_test(): if _file: _file.close() # Timer is auto-freed ``` -------------------------------- ### TestSuite 'before' Hook Example (GdScript) Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/hooks.md Use the 'before()' function within a TestSuite to set up resources or data required by all test cases in the suite. This is ideal for tasks like establishing database connections or initializing global configuration objects. ```gdscript class_name GdUnitExampleTest extends GdUnitTestSuite var _test_data :Node var _config :Dictionary func before(): _test_data = Node.new() _config = {"host": "localhost", "port": 1234} print("TestSuite setup complete.") func test_example(): assert_true(_test_data != null) assert_eq(_config.host, "localhost") print("Running test_example.") func after(): _test_data.queue_free() print("TestSuite teardown complete.") ``` -------------------------------- ### ProjectSettings Isolation (GDScript) Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_faq/solutions.md GdUnit4 automatically snapshots and restores ProjectSettings before and after tests. This example demonstrates the GDScript context where this isolation is handled automatically. ```gdscript func test_project_settings_isolation() -> void: # GdUnit4 automatically snapshots and restores ProjectSettings # No manual intervention is needed here. ``` -------------------------------- ### Initialize Mocked Instances Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/mock.md Shows how to instantiate mocks using class names or resource paths. ```gd # Example class class_name TestClass extends Node ... ``` ```gd # Create a mocked instance of the class 'TestClass' var mock := mock(TestClass) # Or create it by using the full resource path if no `class_name` is defined var mock := mock("res://project_name/src/TestClass.gd") ``` -------------------------------- ### Float Assert Examples - is_equal Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/assert-float.md Example of using the `is_equal` assertion for float values in GdScript. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier for the newly created user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": 123, "name": "John Doe", "email": "john.doe@example.com" } ``` ``` -------------------------------- ### GdScript AssertThat Example Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/assert-that.md Use AssertThat for unknown types in GdScript. For better readability, prefer type-specific asserts. Example shows string equality and numeric greater than assertions. ```gdscript assert_that("This is a test message").is_equal("This is a test message") assert_that(23).is_greater(20) ``` -------------------------------- ### Run All Tests with CLI Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/llms.txt Set the Godot binary path using an environment variable and then execute all tests. Ensure the path to the Godot executable is correctly set. ```bash # Set Godot binary, then run all tests export GODOT_BIN=/path/to/godot ./addons/gdUnit4/runtest.sh ``` -------------------------------- ### C# AssertThat Example Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/assert-that.md In C#, AssertThat is preferred due to static typing. It intelligently selects the appropriate assert implementation based on the inferred type. Examples demonstrate string equality and numeric greater than assertions. ```csharp AssertThat("This is a test message").is_equal("This is a test message"); AssertThat(23).IsGreater(20); ``` -------------------------------- ### Initialize Scene Runner Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/sceneRunner.md Load a scene into the runner to begin testing. ```gd var runner := scene_runner("res://my_scene.tscn") ``` ```cs ISceneRunner runner = ISceneRunner.Load("res://my_scene.tscn"); ``` -------------------------------- ### Get Managed Scene Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/accessors.md Retrieves the scene instance currently managed by the SceneRunner. ```gd ## Returns the scene instance that is currently loaded and managed by this SceneRunner. ## [member return] : The node representing the current running scene func scene() -> Node: ``` ```gd var runner := scene_runner("res://test_scene.tscn") ``` -------------------------------- ### Display GdUnit4 Command Line Help Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/cmd.md View available commands and options for the GdUnit4 CLI. ```bash ---------------------------------------------------------------------------------------------- GdUnit4 Commandline Tool Usage: runtest -a runtest -a -i -- Options --------------------------------------------------------------------------------------- [-help] Shows this help message. [--help-advanced] Shows advanced options. [-a, --add] Adds the given test suite or directory to the execution pipeline. -a [-i, --ignore] Adds the given test suite or test case to the ignore list. -i [-c, --continue] By default GdUnit will abort on first test failure to be fail fast, instead of stop after first failure you can use this option to run the complete test set. [-conf, --config] Run all tests by given test configuration. Default is 'GdUnitRunner.cfg' -conf [testconfiguration.cfg] ``` -------------------------------- ### simulate_screen_touch_drag_drop Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/touchscreen.md Simulates a complete drag and drop event from a start position to a drop position. ```APIDOC ## simulate_screen_touch_drag_drop ### Description Simulates a complete drag and drop event from one position to another, useful for testing complex UI interactions. ### Parameters - **index** (int) - Required - The touch index for multi-touch events. - **position** (Vector2) - Required - The drag start position. - **drop_position** (Vector2) - Required - The drop position. - **time** (float) - Optional - Time to complete the movement in seconds (default 1.0). - **trans_type** (Tween.TransitionType) - Optional - Transition type (default TRANS_LINEAR). ### Request Example await runner.simulate_screen_touch_drag_drop(0, Vector2(50, 50), Vector2(100, 50)) ``` -------------------------------- ### Test Create Temporary File Usage Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/tools.md Shows creating a file in before() and reading it in a test function. ```gdscript # setup test data func before(): # opens a tmp file with WRITE mode under "user://tmp/examples/game/game.sav" (auto closed) var file := create_temp_file("examples/game", "game.sav") assert_object(file).is_not_null() # write some example data file.store_line("some data") # not needs to be manually close, will be auto closed before test execution func test_create_temp_file(): # opens the stored tmp file with READ mode under "user://tmp/examples/game/game.sav" (auto closed) var file_read := create_temp_file("examples/game", "game.sav", File.READ) assert_object(file_read).is_not_null() assert_str(file_read.get_as_text()).is_equal("some data\n") # not needs to be manually close, will be auto closed after test suite execution ``` -------------------------------- ### is_false Assertion Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/assert-bool.md Verifies that the current boolean value is false. Examples provided for GdScript and C#. ```APIDOC ## is_false Assertion ### Description Verifies that the current value is false. ### GdScript #### Method Signature ```gdscript func assert_bool() -> GdUnitBoolAssert ``` #### Example ```gdscript # this assertion succeeds assert_bool(false).is_false() # this assertion fails because the value is true and not false assert_bool(true).is_false() ``` ### C# #### Method Signature ```csharp public static IBoolAssert AssertThat() ``` #### Example ```csharp // this assertion succeeds AssertThat(false).IsFalse(); // this assertion fails because the value is true and not false AssertThat(true).IsFalse(); ``` ``` -------------------------------- ### is_true Assertion Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/assert-bool.md Verifies that the current boolean value is true. Examples provided for GdScript and C#. ```APIDOC ## is_true Assertion ### Description Verifies that the current value is true. ### GdScript #### Method Signature ```gdscript func assert_bool() -> GdUnitBoolAssert ``` #### Example ```gdscript # this assertion succeeds assert_bool(true).is_true() # this assertion fails because the value is false and not true assert_bool(false).is_true() ``` ### C# #### Method Signature ```csharp public static IBoolAssert AssertThat() ``` #### Example ```csharp // this assertion succeeds AssertThat(true).IsTrue(); // this assertion fails because the value is false and not true AssertThat(false).IsTrue(); ``` ``` -------------------------------- ### Simulate Action Release in GDScript Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/actions.md Defines the simulate_action_release method signature and provides a usage example. ```gdscript # action : the action e.g. "ui_up" func simulate_action_release(action: String) -> GdUnitSceneRunner: ``` ```gdscript var runner := scene_runner("res://test_scene.tscn") # Simulate the UP key is released by using the action "ui_up" runner.simulate_action_release("ui-up") await runner.await_input_processed() ``` -------------------------------- ### Build C# Project Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/llms-full.txt Builds the C# project in debug mode and formats the code, verifying no changes. ```bash dotnet build --debug ``` ```bash dotnet format gdUnit4.csproj --verify-no-changes --verbosity diagnostic ``` -------------------------------- ### Build C# Project Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/CONTRIBUTING.md Compile the C# project to ensure all dependencies are met and the build process is successful. A successful build should output 'Build succeeded'. ```bash dotnet build ``` -------------------------------- ### Define a Test Class for Mocking Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/mock.md A simple class definition used as the target for mocking examples. ```gd class_name TestClass extends Node func message() -> String: return "a message" ``` -------------------------------- ### Example of using auto_free() in GdScript Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/tools.md Register a Path object for freeing after the test is finished using auto_free(). ```gdscript # using auto_free() on Path object to register for freeing after the test is finished assert_object(auto_free(Path.new())).is_not_instanceof(Tree) ``` -------------------------------- ### C# Build and Format Commands Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/CLAUDE.md Commands for building C# projects in debug mode and verifying code formatting using dotnet format. ```bash # Build dotnet build --debug ``` ```bash # Verify formatting (CI-style check, no changes applied) dotnet format gdUnit4.csproj --verify-no-changes --verbosity diagnostic ``` -------------------------------- ### Handle Errors in Startup Hook Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/hooks.md Demonstrates returning GdUnitResult objects to signal initialization success or failure. ```gdscript func startup(session: GdUnitTestSession) -> GdUnitResult: if not initialize_resources(): return GdUnitResult.error("Failed to initialize resources: %s" % get_last_error()) if not validate_configuration(): return GdUnitResult.error("Invalid configuration: missing required settings") session.send_message("All systems initialized successfully") return GdUnitResult.success() ``` -------------------------------- ### GDScript: await_func_on Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/scene_runner/functions.md Example of using `await_func_on` in GDScript to wait for a function's return value with a timeout. ```APIDOC ## GDScript: await_func_on ### Description Waits until the function `has_parent()` on source `door` returns false or fails after a timeout of 100ms. ### Method AWAIT ### Endpoint runner.await_func_on(box1, "panel_color_change", [box1, Color.RED]).wait_until(100).is_false() ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Test Save Game Data with Temporary Directory Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/tools.md Demonstrates using create_temp_dir to store and verify temporary file data. ```gdscript func test_save_game_data(): # create a temporay directory to store test data var temp_dir := create_temp_dir("examples/game/save") var file_to_save := temp_dir + "/save_game.dat" var data = { 'user': "Hoschi", 'level': 42 } var file := File.new() file.open(file_to_save, File.WRITE) file.store_line(JSON.print(data)) file.close() # the data is saved at "user://tmp/examples/game/save/save_game.dat" assert_bool(file.file_exists(file_to_save)).is_true() ``` -------------------------------- ### Get Screen Touch Drag Position Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/addons/gdUnit4/test/update/resources/http_response_releases.txt Retrieves the current position of a screen touch drag event. ```APIDOC ## GET /get/screen/touch/drag/position ### Description Returns the actual position of the touch drag position by given index. ### Method GET ### Endpoint /get/screen/touch/drag/position ### Parameters #### Query Parameters - **index** (int) - Required - The touch index in the case of a multi-touch event. ``` -------------------------------- ### Get Screen Touch Drag Position Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/addons/gdUnit4/test/update/resources/http_response_releases.txt Retrieves the current position of a touch drag event by its index. ```gdscript func get_screen_touch_drag_position(index: int) -> Vector2: ``` -------------------------------- ### auto_free() Helper Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_advanced_testing/tools.md The auto_free() helper automatically releases objects after test execution. Objects covered by auto_free() only live in the scope where they are used (test suite setup, test case setup, and tests themselves). Note that objects do not manage memory; if a class inherits from Object, its instances must be deleted manually. References manage their own internal reference counter and are released when no longer in use. ```APIDOC ## auto_free() ### Description A helper for automatically releasing objects after test execution. ### Method Signature #### GdScript ```ruby func auto_free(obj :Object) -> Object: ``` #### C# ```cs public static T AutoFree(T obj); ``` ### Parameters #### GdScript - **obj** (Object) - The object to be automatically freed. #### C# - **obj** (T) - The object to be automatically freed. ### Request Example #### GdScript ```ruby # using auto_free() on Path object to register for freeing after the test is finished assert_object(auto_free(Path.new())).is_not_instanceof(Tree) ``` #### C# ```cs using static Assertions; ... // using AutoFree() on Path object to register for freeing after the test is finished AssertObject(AutoFree(new Godot.Path())).IsNotInstanceOf(); ``` ### Extended Example This example demonstrates the usage of `auto_free()` and memory freeing across different scopes within a test suite. ```ruby extends GdUnitTestSuite var _obj_a; var _obj_b; var _obj_c; # Scope test suite setup func before(): _obj_a = auto_free(Node.new()) print_obj_usage("before") # Scope test case setup func before_test(): _obj_b = auto_free(Node.new()) print_obj_usage("before_test") # Scope test func test(): _obj_c = auto_free(Node.new()) # _obj_a still lives here # _obj_b still lives here # _obj_c still lives here print_obj_usage("test") # Scope test case setup func after_test(): # _obj_a still lives here # _obj_b still lives here # _obj_c is freed print_obj_usage("after_test") # Scope test suite setup func after(): # _obj_a still lives here # _obj_b is auto freed # _obj_c is freed print_obj_usage("after") func _notification(what): if what == NOTIFICATION_PATH_CHANGED: print_header() else: print_obj_usage(GdObjects.notification_as_string(what)) func print_header() : prints("|%16s | %16s | %16s | %16s |" % ["", "_obj_a", "_obj_b", "_obj_c"]) prints("----------------------------------------------------------------------------") func print_obj_usage(name :String) : prints("|%16s | %16s | %16s | %16s |" % [name, _obj_a, _obj_b, _obj_c]) ``` ### Expected Output Table | State | _obj_a | _obj_b | _obj_c | |--- | --- | --- | --- | | PARENTED | Null | Null | Null | | ENTER_TREE | Null | Null | Null | | POST_ENTER_TREE | Null | Null | Null | | READY | Null | Null | Null | | before | [Node:1515] | Null | Null | | before_test | [Node:1515] | [Node:1519] | Null | | test | [Node:1515] | [Node:1519] | [Node:1521] | | after_test | [Node:1515] | [Node:1519] | [Deleted Object] | | after | [Node:1515] | [Deleted Object] | [Deleted Object] | | EXIT_TREE | [Deleted Object] | [Deleted Object] | [Deleted Object] | | UNPARENTED | [Deleted Object] | [Deleted Object] | [Deleted Object] | | PREDELETE | [Deleted Object] | [Deleted Object] | [Deleted Object] | ``` -------------------------------- ### is_not_equal Assertion Source: https://github.com/godot-gdunit-labs/gdunit4/blob/master/documentation/doc/_testing/assert-bool.md Verifies that the current boolean value is not equal to the expected value. Examples provided for GdScript and C#. ```APIDOC ## is_not_equal Assertion ### Description Verifies that the current value is not equal to the given one. ### GdScript #### Method Signature ```gdscript func assert_bool().is_not_equal() -> GdUnitBoolAssert ``` #### Example ```gdscript # this assertion succeeds assert_bool(false).is_not_equal(true) # this assertion fails because the value is false and should not be false assert_bool(false).is_not_equal(false) ``` ### C# #### Method Signature ```csharp public static IBoolAssert AssertThat().IsNotEqual() ``` #### Example ```csharp // this assertion succeeds AssertThat(false).IsNotEqual(true); // this assertion fails because the value is false and should not be false AssertThat(false).IsNotEqual(false); ``` ```