### GDScript Test Case with Assertion (Resource Path) Source: https://mikeschulze.github.io/gdUnit4/first_steps/getting-started An example of a completed GDScript test case using GdUnit4. It instantiates the 'TestPerson' class via its resource path and asserts the correctness of the 'full_name()' method's output. ```gdscript func test_full_name() -> void: var person = load("res://first_steps/test_person.gd").new("King", "Arthur") assert_str(person.full_name()).is_equal("King Arthur") ``` -------------------------------- ### Check Installed .NET SDK Versions Source: https://mikeschulze.github.io/gdUnit4/csharp_project_setup/csharp-setup This command-line snippet demonstrates how to check the installed .NET SDK versions on your system. It is crucial to ensure that .NET 8 or .NET 9 SDKs are installed, as required by GdUnit4Net for C# testing. The output will list the available SDK versions and their installation paths. ```bash dotnet --list-sdks ``` -------------------------------- ### GDScript Test Case with Auto-Free Source: https://mikeschulze.github.io/gdUnit4/first_steps/getting-started An example of a GDScript test case using GdUnit4's 'auto_free' utility. This automatically handles the deallocation of the 'TestPerson' instance at the end of the test, simplifying memory management. ```gdscript func test_full_name() -> void: var person :TestPerson = auto_free(TestPerson.new("King", "Arthur")) assert_str(person.full_name()).is_equal("King Arthur") ``` -------------------------------- ### GdUnit4 Basic Test Example in C# Source: https://mikeschulze.github.io/gdUnit4/example This C# code demonstrates a basic unit test with GdUnit4. It uses the `[TestSuite]` and `[TestCase]` attributes to define the test class and method. The `Example` test method utilizes GdUnit4's assertion methods to verify properties of a string, such as its length and starting characters. This requires the GdUnit4 C# library. ```C# namespace Examples; using GdUnit4; using static GdUnit4.Assertions; [TestSuite] public class GdUnitExampleTest { [TestCase] public void Example() { AssertString("This is an example message") .HasLength(26) .StartsWith("This is an ex"); } } ``` -------------------------------- ### Install GdUnit4 C# Test Dependencies Source: https://mikeschulze.github.io/gdUnit4/csharp_project_setup/csharp-setup This code block lists the essential NuGet package references required for GdUnit4 C# testing. These packages include the .NET Test SDK, the GdUnit4 API, the GdUnit4 test adapter, and GdUnit4 analyzers, which are necessary for discovering and running C# tests within the Godot environment. ```xml none runtime; build; native; contentfiles; analyzers; buildtransitive ``` -------------------------------- ### GDScript Test Class Definition Source: https://mikeschulze.github.io/gdUnit4/first_steps/getting-started Defines a basic GDScript class 'TestPerson' to be used for testing. It includes an initializer and a 'full_name' method. This class serves as the subject under test. ```gdscript class_name TestPerson extends Node var _first_name :String var _last_name :String func _init(first_name :String, last_name :String): _first_name = first_name _last_name = last_name func full_name() -> String: return _first_name + " " + _last_name ``` -------------------------------- ### Example of Monitoring Signals - C# Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/signals A C# example demonstrating signal monitoring. It includes a custom emitter class, starting monitoring on emitters, asserting initial non-emission, emitting signals, and verifying their emission using the AssertSignal API. ```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); await AssertSignal(emitterA).IsNotEmitted(MyEmitter.SignalName.SignalB).WithTimeout(50); await AssertSignal(emitterB).IsNotEmitted(MyEmitter.SignalName.SignalA).WithTimeout(50); await AssertSignal(emitterB).IsNotEmitted(MyEmitter.SignalName.SignalB).WithTimeout(50); // emit signal `signal_a` on emitter_a emitterA.DoEmitSignalA(); await AssertSignal(emitterA).IsEmitted(MyEmitter.SignalName.SignalA).WithTimeout(50); ``` -------------------------------- ### GDScript Test Case with Assertion (Class Name) Source: https://mikeschulze.github.io/gdUnit4/first_steps/getting-started An example of a completed GDScript test case using GdUnit4. It instantiates the 'TestPerson' class directly by its class name and asserts the correctness of the 'full_name()' method's output. ```gdscript func test_full_name() -> void: var person := TestPerson.new("King", "Arthur") assert_str(person.full_name()).is_equal("King Arthur") ``` -------------------------------- ### GdScript TestSuite Setup with 'before' Hook Source: https://mikeschulze.github.io/gdUnit4/testing/hooks Demonstrates setting up test data using the 'before' function in a GdScript GdUnitTestSuite. This function is executed once at the start of the TestSuite run. It initializes a Node and assigns it to a member variable. ```gdscript class_name GdUnitExampleTest extends GdUnitTestSuite var _test_data :Node # create some test data here func before(): _test_data = Node.new() ``` -------------------------------- ### Verify String Length and Content with GdUnit4 Source: https://mikeschulze.github.io/gdUnit4/tutorials/tutorial_basics This example demonstrates how to test a string for its expected length and content using GdUnit4. It is useful for verifying function outputs like text formatting or input validation. Modify the message, expected length, and content to suit your needs. GdUnit4 compares actual and expected values, reporting discrepancies. ```gdscript extends GdUnitTestSuite func test_example(): # Verify the given string by using `assert_str` assert_str("This is a example message")\ # We expect a lenght equal 25 characters .has_length(25) # The message must start wiht `This is a ex` .starts_with("This is a ex") ``` ```csharp [TestCase] public Example2() // Verify the given string by using `AssertString` AssertString("This is a example message") // We expect a lenght equal 25 characters .HasLength(25) // The message must start wiht `This is a ex` .StartsWith("This is a ex"); ``` -------------------------------- ### GdUnit4 Basic Test Example in GDScript Source: https://mikeschulze.github.io/gdUnit4/example This GDScript code defines a basic unit test using GdUnit4. It extends the `GdUnitTestSuite` class and includes a test method `test_example` that performs string assertions on a message, checking its length and prefix. No external dependencies are required beyond GdUnit4 itself. ```GDScript extends GdUnitTestSuite func test_example(): assert_str("This is an example message")\ .has_length(26) .starts_with("This is an ex") ``` -------------------------------- ### GDScript Test Case with Manual Memory Free Source: https://mikeschulze.github.io/gdUnit4/first_steps/getting-started Demonstrates completing a GDScript test by explicitly freeing the created object after the assertion. This prevents memory leaks by ensuring the 'TestPerson' instance is deallocated. ```gdscript func test_full_name() -> void: var person := TestPerson.new("King", "Arthur") assert_str(person.full_name()).is_equal("King Arthur") person.free() ``` -------------------------------- ### Load Scene Runner - C# Example Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/touchscreen Loads a scene runner for testing purposes in C#. It takes the path to the scene file as an argument. ```C# ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); ``` -------------------------------- ### C# TestSuite Setup with '[Before]' Attribute Source: https://mikeschulze.github.io/gdUnit4/testing/hooks Illustrates setting up test data using the '[Before]' attribute in a C# GdUnit4 TestSuite. This method is executed once before the TestSuite begins, preparing test data for use in test cases. It initializes a Godot.Node. ```csharp using GdUnit4; using static GdUnit4.Assertions; namespace ExampleProject.Tests { [TestSuite] public class ExampleTest { private Godot.Node _test_data; [Before] public void Setup() { // create some test data here _test_data = new Godot.Node(); } } } ``` -------------------------------- ### Example of Monitoring Signals - GdScript Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/signals An example demonstrating the usage of monitor_signals in GdScript. It shows how to monitor signals from two emitter objects, assert initial non-emission, emit signals, and verify their emission with specific arguments. ```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 var emitter_a := monitor_signals(MyEmitter.new()) var emitter_b := monitor_signals(MyEmitter.new()) # verify the signals are not emitted initial await assert_signal(emitter_a).wait_until(50).is_not_emitted('my_signal_a') await assert_signal(emitter_a).wait_until(50).is_not_emitted('my_signal_b') await assert_signal(emitter_b).wait_until(50).is_not_emitted('my_signal_a') await assert_signal(emitter_b).wait_until(50).is_not_emitted('my_signal_b') # emit signal `my_signal_a` on emitter_a emitter_a.do_emit_a() await assert_signal(emitter_a).is_emitted('my_signal_a') # emit signal `my_signal_b` on emitter_a emitter_a.do_emit_b() await assert_signal(emitter_a).is_emitted('my_signal_b', ["foo"]) # verify emitter_b still has nothing emitted await assert_signal(emitter_b).wait_until(50).is_not_emitted('my_signal_a') await assert_signal(emitter_b).wait_until(50).is_not_emitted('my_signal_b') # now verify emitter b emitter_b.do_emit_a() await assert_signal(emitter_b).wait_until(50).is_emitted('my_signal_a') ``` -------------------------------- ### Start Signal Monitoring - C# Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/signals Provides the C# interface for starting signal monitoring. This method is typically called implicitly when signal assertions are first used, or explicitly using StartMonitoring to record all emitted signals. ```csharp /// /// Starts the monitoring of emitted signals during the test runtime. /// It should be called first if you want to collect all emitted signals after the emitter has been created. /// /// public ISignalAssert StartMonitoring(); ``` -------------------------------- ### C# TestSuite Setup with 'AutoFree' in '[Before]' Method Source: https://mikeschulze.github.io/gdUnit4/testing/hooks Demonstrates using 'AutoFree()' in a C# '[Before]' method for automatic resource management. This ensures that the created Godot.Node is automatically freed after the TestSuite completes. ```csharp using GdUnit4; using static GdUnit4.Assertions; namespace ExampleProject.Tests { [TestSuite] public class ExampleTest { private Godot.Node _test_data; [Before] public void Setup() { // create some test data here _test_data = AutoFree(new Godot.Node()); } } } ``` -------------------------------- ### Load Scene Runner - GdScript Example Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/touchscreen Loads a scene runner for testing purposes in GdScript. It takes the path to the scene file as an argument. ```GdScript var runner := scene_runner("res://test_scene.tscn") ``` -------------------------------- ### GDScript Example Class Definition Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/mock Defines a simple GDScript class 'TestClass' that extends Node and has a 'message' function returning a string. This class serves as an example for mocking. ```gdscript class_name TestClass extends Node func message() -> String: return "a message" ``` -------------------------------- ### Configure Project File for GdUnit4 C# Testing Source: https://mikeschulze.github.io/gdUnit4/csharp_project_setup/csharp-setup This snippet shows the necessary modifications to a project's .csproj file to enable GdUnit4 C# testing. It includes setting the TargetFramework to net8.0 or net9.0, specifying the LangVersion to 12.0, enabling nullable reference types, ensuring local assemblies are copied, and adding required NuGet package references for GdUnit4 and .NET testing infrastructure. ```xml net8.0 12.0 enable true NU1605 none runtime; build; native; contentfiles; analyzers; buildtransitive ``` -------------------------------- ### Get Screen Touch Drag Position Example - GdScript Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/touchscreen Example of using get_screen_touch_drag_position in GdScript to retrieve and assert the drag position. ```GdScript var runner := scene_runner("res://test_scene.tscn") # Example usage var drag_position = runner.get_screen_touch_drag_position(0) assert_that(drag_position).is_equal(Vector2(683, 339)) ``` -------------------------------- ### GdScript Custom Fuzzer Example: List of Values Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/fuzzing Provides an example of a custom GdScript fuzzer (`TestFuzzer`) that generates random values from a predefined list. ```gdscript # A simple test fuzzer where a random value of a hard coded set of values is provided class TestFuzzer extends Fuzzer: var _data := [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] func next_value(): return _data[randi_range(0, _data.size())] ``` -------------------------------- ### Simulate Key Press and Wait for Input (GdScript) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/sync_inputs This GdScript example demonstrates simulating a key press combination (Ctrl+C) using `simulate_key_pressed` and then ensuring all input events are processed before proceeding with `await_input_processed`. It initializes a `scene_runner` to manage the test scene. ```GdScript 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() ``` -------------------------------- ### Set GODOT_BIN Environment Variable on Windows Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/cmd This command sets the GODOT_BIN environment variable on Windows 10/11. This variable is required by the GdUnit tool to locate the Godot executable. Users need to replace the example path with their actual Godot installation path. ```batch setx GODOT_BIN D:\\develop\\Godot.exe ``` -------------------------------- ### RETURN_DEEP_STUB Mock Mode Example in GDScript (WIP) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/mock Shows an example of the RETURN_DEEP_STUB working mode in GDScript, noting that it is a work in progress. This mode aims to return default values for built-in types and fully mocked objects for object types, enabling chained mock calls. The example demonstrates returning default values and mocked object values. ```gdscript # 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() ``` -------------------------------- ### C# Invoke Method Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/accessors This section details the `Invoke` method in C#, explaining its parameters and providing an example. ```APIDOC ## C# Invoke Method ### Description Invokes the method by the given name and arguments. It returns the result of the invoked method. ### Method C# method ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Invokes the function `start_color_cycle` runner.Invoke("start_color_cycle"); ``` ### Response #### Success Response (200) - **return** (object) - The return value of the invoked method. #### Response Example ```json { "result": "function_return_value" } ``` #### Error Response - **MissingMethodException**: Thrown if the specified method is not found. ``` -------------------------------- ### Configure VS Code Test Explorer Path Source: https://mikeschulze.github.io/gdUnit4/csharp_project_setup/vstest-adapter This configuration snippet for Visual Studio Code allows you to specify the path to your `.runsettings` file, enabling the test explorer to discover and run your GDUnit4 tests. Ensure you have the C# Dev Kit extension installed and are using a compatible version. ```json { "dotnet.unitTests.runSettingsPath": "./test/.runsettings" } ``` -------------------------------- ### Simulate Screen Touch Drag Drop (GdScript, C#) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/touchscreen Simulates a complete drag and drop event from a starting position to a drop position. It requires the touch index, start position, drop position, duration, and transition type. This is best for testing complex drag-and-drop sequences with defined start and end points. ```gdscript ## Simulates a complete drag and drop event from one position to another. ## [member index] : The touch index in the case of a multi-touch event. ## [member position] : The drag start position, indicating the drag position. ## [member drop_position] : The drop position, indicating the drop position. ## [member time] : The time to move to the final position in seconds (default is 1 second). ## [member trans_type] : Sets the type of transition used (default is TRANS_LINEAR). func simulate_screen_touch_drag_drop(index: int, position: Vector2, drop_position: Vector2, time: float = 1.0, trans_type: Tween.TransitionType = Tween.TRANS_LINEAR) -> GdUnitSceneRunner: var runner := scene_runner("res://test_scene.tscn") # Simulates a full drag and drop from position 50, 50 to 100, 50 await runner.simulate_screen_touch_drag_drop(0, Vector2(50, 50), Vector2(100,50)) ``` ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); ``` -------------------------------- ### Simulate Key Press and Wait for Input (C#) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/sync_inputs This C# example shows how to simulate pressing Ctrl+C using `SimulateKeyPress` and then awaiting input processing with `AwaitInputProcessed`. It utilizes `ISceneRunner` loaded from a scene file to manage input simulation. ```C# 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(); ``` -------------------------------- ### GDScript Mocking Node Functions Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/mock Provides an example of mocking a 'Node' object and overriding its 'get_child_count' and 'get_child' functions. It shows how to set specific return values for different calls and arguments. ```gdscript # Create a mock from class `Node` var mocked_node := mock(Node) as Node # It returns 0 by default mocked_node.get_child_count() # Override function `get_child_count` to return 10 do_return(10).on(mocked_node).get_child_count() # The next call of `get_child_count` will now return 10 mocked_node.get_child_count() # It returns 'null' by default var node = mocked_node.get_child(0) assert_object(node).is_null() # Override function `get_child` to return a mocked 'Camera' for child index 0 do_return(mock(Camera)).on(mocked_node).get_child(0) # And a mocked 'Area' for child index 1 do_return(mock(Area)).on(mocked_node).get_child(1) # It now returns the Camera node at index 0 var node0 = mocked_node.get_child(0) assert_object(node0).is_instanceof(Camera) # And the Area node at index 1 var node1 = mocked_node.get_child(1) assert_object(node1).is_instanceof(Area) ``` -------------------------------- ### GdScript TestSuite Setup with Auto-Free 'before' Hook Source: https://mikeschulze.github.io/gdUnit4/testing/hooks Shows how to use the 'auto_free()' utility within the 'before' function in GdScript to automatically manage the cleanup of created test data. The object is freed during the 'after' stage. ```gdscript class_name GdUnitExampleTest extends GdUnitTestSuite var _test_data :Node # create some test data here func before(): _test_data = auto_free(Node.new()) ``` -------------------------------- ### GdScript Fuzzer Example: Custom Seed Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/fuzzing Shows how to ensure reproducible results for random fuzzers by setting a specific seed value using the `fuzzer_seed` argument. ```gdscript # execute this test with a seed value of 123456 func test_fuzzer_inject_value(fuzzer := Fuzzers.rangei(-100000, 100000), fuzzer_seed=123456): ``` -------------------------------- ### Argument Matcher Verification in GDScript Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/mock Demonstrates using argument matchers in GDScript for flexible mock verification. The example uses `any_bool()` to verify that a function (`set_process`) was called a specific number of times with any boolean argument, simplifying tests when exact argument values are not critical. ```gdscript var mocked_node :Node = mock(Node) # Call the function with different arguments mocked_node.set_process(false) # Called 1 time mocked_node.set_process(true) # Called 1 time mocked_node.set_process(true) # Called 2 times # Verify that the function was called with any boolean value 3 times verify(mocked_node, 3).set_process(any_bool()) ``` -------------------------------- ### Set GODOT_BIN and Make Executable on MacOS/Linux Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/cmd Sets the GODOT_BIN environment variable and makes the runtest.sh script executable on MacOS and Linux. The GODOT_BIN path should be updated to the user's Godot installation location. This prepares the environment for running GdUnit tests on these systems. ```bash export GODOT_BIN=/Applications/Godot.app/Contents/MacOS/Godot chmod +x ./addons/gdUnit4/runtest.sh ``` -------------------------------- ### Example GdScript Test With Fail Fast Strategy Source: https://mikeschulze.github.io/gdUnit4/testing/first-test Shows a GdScript test case implementing a fail-fast strategy. After critical assertions, `if is_failure(): return` is used to halt execution if a preceding assertion fails, preventing further unnecessary checks and providing clearer failure reports. ```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() ``` -------------------------------- ### GdScript Fuzzer Example: Range Integer Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/fuzzing Demonstrates how to use the built-in `rangei` fuzzer to generate random integers within a specified range and assert the generated value. It also shows how to set custom iteration counts. ```gdscript func test_fuzzer_inject_value(fuzzer := Fuzzers.rangei(-23, 22), fuzzer_iterations = 100) assert_int(fuzzer.next_value()).is_between(-23, 22) # using multiple fuzzers in test are allowed func test_fuzzer_inject_value(fuzzer_a := Fuzzers.rangei(-23, 22), fuzzer_b := Fuzzers.rangei(0, 42), fuzzer_iterations := 100): assert_int(fuzzer_a.next_value()).is_between(-23, 22) assert_int(fuzzer_b.next_value()).is_between(-23, 22) ``` -------------------------------- ### GdScript TestSuite Teardown with 'after' Hook Source: https://mikeschulze.github.io/gdUnit4/testing/hooks Provides an example of a GdScript TestSuite's 'after' function, which is executed once at the end of the TestSuite run. This is typically used to release resources or clean up data initialized in the 'before' stage. ```gdscript class_name GdUnitExampleTest extends GdUnitTestSuite var _test_data :Node # create some test data here func before(): _test_data = Node.new() # Release test data here func after(): # If _test_data was not auto_free'd, it needs to be manually freed here. # For example: _test_data.queue_free() pass ``` -------------------------------- ### GDUnit4 Argument Matchers Example Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/spy This GDScript snippet introduces the concept of argument matchers in GDUnit4, specifically `any_bool()`. Argument matchers allow for more flexible verification of function calls by matching arguments based on their type or properties, rather than exact values. This is particularly helpful when dealing with dynamic or complex arguments in spy verifications. ```gdscript var spyed_node :Node = spy(Node.new()) # Example usage of any_bool() would typically follow here, # for instance: verify(spyed_node).some_function(any_bool()) ``` -------------------------------- ### AssertThat Assertion Example - C# Source: https://mikeschulze.github.io/gdUnit4/testing/assert-that Shows how to use the AssertThat assertion in C#, which automatically determines the type of the variable and switches to the equivalent assertion implementation. This is preferred in C# as variable types are always known, leading to efficient assertion selection. ```C# // auto type assertion public static IAssertBase AssertThat(); ``` ```C# AssertThat("This is a test message").is_equal("This is a test message"); AssertThat(23).IsGreater(20); ``` -------------------------------- ### Advanced Options Help (Unix/Linux) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/cmd Displays all available advanced options for the gdUnit command line tool. This is useful for discovering and utilizing the full range of customization features. ```bash # Displays help for advanced options ./addons/gdUnit4/runtest.sh --help-advanced ``` -------------------------------- ### Reset GDUnit4 Spy Interactions with reset() Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/spy This GDScript example demonstrates how to use the `reset()` method to clear all recorded function call data from a GDUnit4 spy. This is useful when reusing a spy across different test scenarios, allowing you to start with a clean slate. The example shows resetting interactions and then verifying that they have been removed before proceeding with new tests. ```gdscript var spyed_node :Node = spy(Node.new()) # First, we test by interacting with two functions spyed_node.is_a_parent_of(null) spyed_node.set_process(false) # Verify if the interactions were recorded; at this point, two interactions are recorded verify(spyed_node).is_a_parent_of(null) verify(spyed_node).set_process(false) # Now, we want to test a different scenario and we need to reset the current recorded interactions reset(spyed_node) # Verify that the previously recorded interactions have been removed verify_no_more_interactions(spyed_node) # Continue testing spyed_node.set_process(true) verify(spyed_node).set_process(true) verify_no_more_interactions(spyed_node) ``` -------------------------------- ### GdUnit Command Line Tool Usage and Options Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/cmd Overview of the GdUnit Command Line Tool's available commands and options. It details how to add directories or test suites for execution, specify ignored tests, continue test runs after failures, and use configuration files. ```bash 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] ``` -------------------------------- ### Load Latest Configuration and Run Tests (Windows) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/cmd Loads the latest GdUnitRunner.cfg configuration file and executes the configured tests. This is the Windows equivalent for running tests based on the latest configuration. ```bash # loads latest GdUnitRunner.cfg and runs the configured tests ./addons/gdUnit4/runtest -conf ``` -------------------------------- ### Load Specific Configuration and Run Tests (Unix/Linux) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/cmd Loads a specific test configuration file (e.g., test_config.cfg) and runs the tests defined in that configuration. This allows for running different sets of tests based on predefined configurations. ```bash # loads a specific test configuration and runs the configured tests (since v1.0.6) ./addons/gdUnit4/runtest.sh -conf ``` -------------------------------- ### Assert No Function Calls with GDUnit4 verify_no_interactions Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/spy This GDScript example shows how to use `verify_no_interactions()` to assert that a spy has not had any of its functions called. This is crucial for testing initial states or ensuring that certain actions do not trigger unexpected behavior. The example demonstrates that calling a function after `verify_no_interactions()` will cause the assertion to fail. ```gdscript var spyed_node := spy(Node.new()) as Node # Test that we have no initial interactions on this spy verify_no_interactions(spyed_node) # Interact by calling `get_name()` spyed_node.get_name() # Now this verification will fail because we have interacted on this spy by calling `get_name` verify_no_interactions(spyed_node) ``` -------------------------------- ### Configure RunSettings for GdUnit4 Test Execution Source: https://mikeschulze.github.io/gdUnit4/csharp_project_setup/vstest-adapter This XML configuration file defines settings for running tests with GdUnit4, including parallel execution, results directory, target frameworks, session timeout, and environment variables. It also specifies loggers for console, HTML, and TRX output, along with specific GdUnit4 parameters like display name format and standard output capture. ```xml 1 ./TestResults net8.0;net9.0 180000 true d:\\development\\Godot_v4.4.1-stable_mono_win64\\Godot_v4.4.1-stable_mono_win64.exe detailed test-result.html test-result.trx "--verbose" FullyQualifiedName true 20000 ``` -------------------------------- ### Get Mouse Position Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/mouse Retrieves the current mouse cursor position from the viewport. ```APIDOC ## GET /runner/get_mouse_position ### Description Gets the mouse cursor position from the current viewport. ### Method GET ### Endpoint /runner/get_mouse_position ### Parameters None ### Request Example None ### Response #### Success Response (200) - **position** (Vector2) - The mouse's position in the Viewport using the coordinate system of this Viewport. #### Response Example ```json { "position": { "x": 100, "y": 100 } } ``` ``` -------------------------------- ### Load Specific Configuration and Run Tests (Windows) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/cmd Loads a specified test configuration file and runs the associated tests. This functionality is available since version 1.0.6 and allows for flexible test execution management. ```bash # loads a specific test configuration and runs the configured tests (since v1.0.6) ./addons/gdUnit4/runtest -conf ``` -------------------------------- ### Load Latest Configuration and Run Tests (Unix/Linux) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/cmd Loads the latest GdUnitRunner.cfg configuration file and runs the tests defined within it. This is a convenient way to rerun previously defined test sets. ```bash # loads latest GdUnitRunner.cfg and runs the configured tests ./addons/gdUnit4/runtest.sh -conf ``` -------------------------------- ### GdScript Invoke Function Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/accessors This section details the `invoke` function in GdScript, explaining its parameters and providing an example. ```APIDOC ## GdScript invoke Function ### Description Runs the function specified by the given name in the scene and returns the result. ### Method GdScript function ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```gdscript var runner := scene_runner("res://test_scene.tscn") # Invokes the function `start_color_cycle` runner.invoke("start_color_cycle") ``` ### Response #### Success Response (200) - **return** (any) - The result of the invoked function. #### Response Example ```json { "result": "function_return_value" } ``` ``` -------------------------------- ### Instantiate a Spy on a Node Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/spy Shows the basic syntax for creating a spy on a new instance of a Node, marking it for auto-freeing. ```GDScript var spy:= spy(auto_free(Node.new())) ``` -------------------------------- ### GdScript Fuzzer Example: Custom Iterations Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/fuzzing Illustrates how to specify a custom number of iterations for a fuzzer test case using the `fuzzer_iterations` argument, overriding the default 1000 iterations. ```gdscript # execute this test 5000 times func test_fuzzer_inject_value(fuzzer := Fuzzers.rangei(-100000, 100000), fuzzer_iterations=5000): ``` -------------------------------- ### Simulate Action Release (GdScript, C#) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/actions Simulates the release of a previously pressed input action. This function is used to complete interactions started with 'simulate_action_press'. Ensure input processing is awaited. ```gdscript func simulate_action_release(action: String) -> GdUnitSceneRunner: # ... implementation details ... ``` ```csharp ISceneRunner SimulateActionRelease(string action); ``` -------------------------------- ### GDScript Mock Instance Creation Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/mock Shows how to create mocked instances of GDScript classes either by their 'class_name' or by their resource path. Mocked instances are automatically managed for memory. ```gdscript # 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") ``` -------------------------------- ### Run GdUnit4 Tests with GitHub Action Source: https://mikeschulze.github.io/gdUnit4/faq/ci This GitHub Action automates the execution of GdUnit4 unit tests within a Godot Engine 4.x environment. It allows configuration of the Godot version, GdUnit4 version, test paths, and report naming. The action is designed to be used in CI pipelines to ensure code quality. ```yaml name: ci-pr-example run-name: ${{ github.head_ref || github.ref_name }}-ci-pr-example on: pull_request: paths-ignore: - '**.yml' - '**.md' workflow_dispatch: concurrency: group: ci-pr-example${{ github.event.number }} cancel-in-progress: true jobs: unit-test: name: "CI Unit Test" runs-on: 'ubuntu-22.04' timeout-minutes: 10 # The overall timeout permissions: actions: write checks: write contents: write pull-requests: write statuses: write steps: # checkout your repository - uses: actions/checkout@v4 with: lfs: true # run tests by using the gdUnit4-action with Godot version 4.2.1 and the latest GdUnit4 release - uses: MikeSchulze/gdUnit4-action@v1.0.2 with: godot-version: '4.2.1' paths: | res://project/tests/ timeout: 5 report-name: test_report.xml ``` -------------------------------- ### Verify Integer Less Than or Equal To - GdScript and C# Source: https://mikeschulze.github.io/gdUnit4/testing/assert-integer These snippets demonstrate how to verify if an integer is less than or equal to a given value using GdUnit in GdScript and C#. The examples include both passing scenarios. ```gdscript func assert_int().is_less_equal() -> GdUnitIntAssert # this assertion succeeds assert_int(23).is_less_equal(42) assert_int(23).is_less_equal(23) ``` ```csharp INumberAssert AssertThat().IsLessEqual() // this assertion succeeds AssertThat(23).IsLessEqual(42); AssertThat(23).IsLessEqual(23); ``` -------------------------------- ### Deploy GdUnit4 Tests with GitLab CI Source: https://mikeschulze.github.io/gdUnit4/faq/ci This GitLab CI configuration automates the export of a Godot project and the execution of GdUnit4 tests. It utilizes a Docker image for the Godot CI environment and defines stages for export, tests, and deployment. Test results are reported in JUnit format. ```yaml image: barichello/godot-ci:4.0.0 cache: key: import-assets paths: - .import/ stages: - export - tests - deploy variables: EXPORT_NAME: $CI_PROJECT_NAME GIT_SUBMODULE_STRATEGY: recursive linux: stage: export script: - mkdir -v -p build/linux - godot -v --export "Linux/X11" build/linux/$EXPORT_NAME.x86_64 artifacts: name: $EXPORT_NAME-$CI_JOB_NAME paths: - build/linux gdunit4: stage: tests dependencies: - linux script: - export GODOT_BIN=/usr/local/bin/godot - ./runtest.sh -a ./test || if [ $? -eq 101 ]; then echo "warnings"; elif [ $? -eq 0 ]; then echo "success"; else exit 1; fi artifacts: when: always reports: junit: ./reports/report_1/results.xml ``` -------------------------------- ### Get Screen Touch Drag Position - C# Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/touchscreen Retrieves the current drag position of a touchscreen input by its index in C#. This is useful for verifying the location of touch events during drag operations. ```C# public Vector2 GetScreenTouchDragPosition(int index) { // Not yet implemented! return Vector2.Zero; } ``` -------------------------------- ### Get Screen Touch Drag Position - GdScript Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/scene_runner/touchscreen Retrieves the current drag position of a touchscreen input by its index in GdScript. Useful for verifying touch event locations during drag operations. ```GdScript ## Returns the actual position of the touchscreen drag position by given index. ## [member index] : The touch index in the case of a multi-touch event. func get_screen_touch_drag_position(index: int) -> Vector2: pass ``` -------------------------------- ### Run Test Suites from Multiple Directories (Linux/macOS) Source: https://mikeschulze.github.io/gdUnit4/advanced_testing/cmd Allows running test suites from multiple specified directories using the `runtest.sh` script on Linux or macOS. This is achieved by providing the `-a` option multiple times with different directory paths. ```bash ./addons/gdUnit4/runtest.sh -a /myProject/test/foo/bar1 -a /myProject/test/foo/bar3 ```