### C# Signal Monitoring Example Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/signals Demonstrates starting signal monitoring on emitter objects in C#, verifying initial monitoring status, and asserting non-emitted signals with a timeout. ```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); ``` -------------------------------- ### List Installed .NET SDKs Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/csharp_project_setup/csharp-setup Verify that you have .NET 8 or .NET 9 SDKs installed on your system. This command lists all installed SDK versions. ```bash dotnet --list-sdks 8.0.201 [C:\Program Files\dotnet\sdk] 9.0.100 [C:\Program Files\dotnet\sdk] ``` -------------------------------- ### GdScript Test Suite Setup and Teardown Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/test-case Demonstrates how to define setup (before_test) and teardown (after_test) hooks within a GdUnit test suite. ```gdscript extends GdUnitTestSuite func before_test(): # Setup test data here func after_test(): # Cleanup test data here func test_string_to_lower() -> void: assert_str("AbcD".to_lower()).is_equal("abcd") ``` -------------------------------- ### String starts with prefix - C# Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-string Verifies that the current string starts with the given prefix. This is useful for checking the beginning of a string. ```C# AssertThat("This is a String").StartsWith("This is"); // this assertion fails AssertThat("This is a String").StartsWith("a String"); ``` -------------------------------- ### GdScript Database Test Hook Example Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/hooks A GdScript example demonstrating a database test hook. It sets up a test database during startup and cleans it up during shutdown. ```gdscript class_name DatabaseTestHook extends GdUnitTestSessionHook var db_connection func _init(): super("DatabaseTestHook", "Manages test database lifecycle") func startup(session: GdUnitTestSession) -> GdUnitResult: session.send_message("Creating test database: %s" % test_db_name) # Connect to database server db_connection = DatabaseManager.connect_to_server({ "host": "localhost", "port": 5432, "user": "test_user", "password": "test_password" }) if not db_connection: return GdUnitResult.error("Failed to connect to database server") # Create test database if not db_connection.create_database("test_db_name"): return GdUnitResult.error("Failed to create test database") session.send_message("Test database ready") return GdUnitResult.success() func shutdown(session: GdUnitTestSession) -> GdUnitResult: session.send_message("Cleaning up test database") if db_connection: # Drop test database db_connection.drop_database("test_db_name") db_connection.disconnect() session.send_message("Database cleanup completed") return GdUnitResult.success() ``` -------------------------------- ### String starts with prefix Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-string Verifies that the current string starts with the given prefix. This is useful for checking the beginning of a string. ```GdScript assert_str("This is a String").starts_with("This is") # this assertion fails assert_str("This is a String").starts_with("a String") ``` -------------------------------- ### C# Test Case Setup Hook Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/hooks Use the `[BeforeTest]` attribute to designate a method that will execute before each test case, ensuring necessary setup is performed. ```csharp [TestSuite] public class ExampleTest { private Godot.Node _testInstance; [BeforeTest] public void SetupTest() { // Each test gets a fresh instance _testInstance = AutoFree(new Godot.Node()); _testInstance.Name = "TestNode"; } } ``` -------------------------------- ### Example of using create_temp_dir() to save game data in GdScript Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/tools This GdScript example demonstrates creating a temporary directory using create_temp_dir(), saving JSON data to a file within that directory, and asserting the file's existence. ```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() ``` -------------------------------- ### Example Test File Paths Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/first_steps/settings Illustrates the typical relationship between source files and their corresponding test files within a project structure. ```text res://project/src/folder_a/folder_b/my_class.gd res://project/test/folder_a/folder_b/my_class_test.gd ``` -------------------------------- ### C# AssertThat Examples Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-that Examples demonstrating the usage of AssertThat in C# for string equality and numeric comparison. The auto-typing feature selects the correct assertion. ```csharp AssertThat("This is a test message").is_equal("This is a test message"); AssertThat(23).IsGreater(20); ``` -------------------------------- ### GdScript extended example of auto_free() usage Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/tools An extended GdScript test suite example demonstrating the usage of auto_free() across different scopes (suite setup, test case setup, test) and showing object lifetime management. ```GdScript 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_b 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]) ``` -------------------------------- ### Complete GdUnit4 C# Project Configuration Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/csharp_project_setup/csharp-setup An example of a complete .csproj file demonstrating the necessary configurations for GdUnit4 C# testing, including target framework and dependencies. ```xml net9.0 13.0 enable true NU1605 none runtime; build; native; contentfiles; analyzers; buildtransitive ``` -------------------------------- ### Run Tests Using Specific Configuration Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/cmd Load a specific test configuration file and run the configured tests. Use this to manage different test setups. ```bash ./addons/gdUnit4/runtest.sh -conf ``` -------------------------------- ### GdScript Resource Cleanup Example Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/hooks Demonstrates using `before_test` to open a file and `after_test` to close it, ensuring resources are managed correctly. Timers are shown with `auto_free` for automatic cleanup. ```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 ``` -------------------------------- ### scene Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing//scene_runner/accessors Gets access to the current running scene. ```APIDOC ## scene ### Description Gets access to the current running scene. ### GdScript Signature ```gdscript func scene() -> SceneTree: ``` ### C# Signature ```csharp public SceneTree Scene { get; } ``` ### Returns * (SceneTree) - The current running scene. ### GdScript Example ```gdscript var runner := scene_runner("res://test_scene.tscn") var current_scene: SceneTree = runner.scene() ``` ### C# Example ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); SceneTree currentScene = runner.Scene; ``` ``` -------------------------------- ### GdScript AssertThat Examples Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-that Examples demonstrating the usage of AssertThat in GdScript for string equality and numeric comparison. Type-specific asserts are preferred for clarity. ```gdscript assert_that("This is a test message").is_equal("This is a test message") assert_that(23).is_greater(20) ``` -------------------------------- ### Run Tests Using Specific Configuration (Unix/Linux) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/cmd Load a specific test configuration file and run the configured tests on Unix/Linux systems. Use this to manage different test setups. ```bash ./addons/gdUnit4/runtest -conf ``` -------------------------------- ### Example Class Definition Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/mock Defines a simple GDScript class 'TestClass' that extends Node and has a 'message' method returning a string. ```gdscript class_name TestClass extends Node func message() -> String: return "a message" ``` -------------------------------- ### C# AwaitMethod Example Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/functions Waits for a function to return a value and asserts it equals 'black' within a 5000ms timeout. ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Waits until the function `color_cycle()` returns black or fails after an timeout of 5s await runner.AwaitMethod("color_cycle").IsEqual("black").WithTimeout(5000); ``` -------------------------------- ### Custom Fuzzer Implementation Example Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/fuzzing An example of a custom fuzzer implementation that extends the base `Fuzzer` class. This fuzzer provides a random value from a predefined set of prime numbers. ```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())] ``` -------------------------------- ### Mocking Node Methods and Arguments Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/mock Provides an example of mocking methods on a Node instance, including overriding 'get_child_count' to return a specific number and 'get_child' to return mocked instances of Camera and Area based on the argument index. ```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) ``` -------------------------------- ### Scene Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing//scene_runner/accessors Gets access to the current loaded and managed scene by the SceneRunner. ```APIDOC ## Scene ### Description Gets access to the current loaded and managed scene by the SceneRunner. The scene remains available for testing and interaction until the runner is disposed or the scene is explicitly freed. ### Method Node? Scene() ### Response #### Success Response - **Node?** - The node representing the current running scene, or null when the SceneRunner is disposed or the scene has been freed. ### Request Example ```gdscript ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); var currentScene = runner.Scene(); ``` ``` -------------------------------- ### GdScript Signal Monitoring Example Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/signals Demonstrates monitoring signals from two emitter objects, asserting initial non-emission, emitting signals, and verifying their emission. It also shows asserting non-emission on a separate emitter. ```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) ``` -------------------------------- ### Use a Spy to Track Function Calls Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/spy This example demonstrates how to spy on a custom class instance and verify that its 'message' function 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 C# Object for Extraction Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-array Defines a sample C# class 'TestObj' with properties that can be accessed via extractors. ```csharp // example object for extraction class TestObj : Godot.Reference { string _name; object _value; object _x; public TestObj(string name, object value, object x = null) { _name = name; _value = value; _x = x; } public string GetName() => _name; public object GetValue() => _value; public object GetX() => _x; } ``` -------------------------------- ### Assert Integer Is Zero Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is exactly zero. Examples are shown for GdScript and C#. ```GdScript # this assertion succeeds assert_int(0).is_zero() # this assertion fail because the value is not zero assert_int(1).is_zero() ``` ```C# // this assertion succeeds AssertThat(0).IsZero(); // this assertion fail because the value is not zero AssertThat(1).IsZero(); ``` -------------------------------- ### GdScript Test Case Setup Hook Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/hooks Implement the `before_test()` function within your TestSuite to initialize data or resources required before each individual test case begins. ```gdscript class_name GdUnitExampleTest extends GdUnitTestSuite var _test_instance :Node func before_test(): # Each test gets a fresh instance _test_instance = auto_free(Node.new()) _test_instance.name = "TestNode" ``` -------------------------------- ### GdScript await_func Example Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/functions Waits for a function in the scene to return a value and asserts it equals 'black' within 5000ms. ```gdscript var runner := scene_runner("res://test_scene.tscn") # Waits until the function `color_cycle()` returns black or fails after an timeout of 5s await runner.await_func("color_cycle").wait_until(5000).is_equal("black") ``` -------------------------------- ### GdScript await_func_on Example Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/functions Waits for a function on a specific source node to return a value and asserts it is false within 100ms. ```gdscript var runner := scene_runner("res://test_scene.tscn") # grab the colorRect instance from the scene var box1: ColorRect = runner.get_property("_box1") # call function `start_color_cycle` how is emit the signal box1.start_color_cycle() # Waits until the function `has_parent()` on source `door` returns false or fails after an timeout of 100ms await runner.await_func_on(box1, "panel_color_change", [box1, Color.RED]).wait_until(100).is_false() ``` -------------------------------- ### Verifying Signal Emission with Argument Matchers Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/argument_matchers Use `any_int()` and `any_string()` to assert that a signal is emitted with specific argument types. This example shows how to wait for a signal with any integer argument or a string name and an integer ID. ```gdscript # Waits until 'test_signal_counted' is emitted with any integer argument (variadic syntax since v6.1) await assert_signal(signal_emitter).is_emitted("test_signal_counted", any_int()) # Waits until 'item_added' is emitted with any String name and exactly item_id=42 await assert_signal(signal_emitter).is_emitted("item_added", any_string(), 42) ``` -------------------------------- ### Using rangei Fuzzer Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/fuzzing Example of using the `rangei` fuzzer to generate random integers within a specified range and asserting the result. This snippet also shows how to set a custom number of iterations. ```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) ``` -------------------------------- ### Assert Integer Less Than or Equal To Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is less than or equal to a specified value. Examples are shown for GdScript and C#. ```GdScript assert_int(23).is_less_equal(22) ``` ```GdScript // this assertion succeeds assert_int(23).is_less_equal(42); assert_int(23).is_less_equal(23); // this assertion fails because 23 is not less than or equal to 22 assert_int(23).is_less_equal(22); ``` -------------------------------- ### Simulate Scene Processing Over Frames (GdScript) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/sceneRunner Example of using the simulate_frames function in GdScript to process a scene over a specified number of frames at normal speed. Ensure the scene runner is initialized first. ```GdScript var runner := scene_runner("res://test_scene.tscn") # Simulate scene processing over 60 frames at normal speed await runner.simulate_frames(60) ``` -------------------------------- ### C# Vector Not Equal Assertion Examples Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-vector Examples of successful and failing vector not equal assertions in C#. The assertion fails if the vectors are equal. ```csharp // this assertion succeeds AssertThat(Vector2.One).IsNotEqual(new Vector2(1.2f, 1.000001f)); // should fail because is equal AssertThat(Vector2.One).IsNotEqual(Vector2.One); ``` -------------------------------- ### GdScript Vector Not Equal Assertion Examples Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-vector Examples of successful and failing vector not equal assertions in GdScript. The assertion fails if the vectors are identical. ```gdscript # this assertion succeeds assert_vector(Vector2(1.1, 1.2)).is_not_equal(Vector2(1.1, 1.3)) # this assertion fails because both vectors are equal assert_vector(Vector2(1.1, 1.2)).is_not_equal(Vector2(1.1, 1.2)) ``` -------------------------------- ### Error Handling in Hook Startup Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/hooks Demonstrates proper error handling within a hook's startup method. It checks for initialization and configuration success, returning specific error results if failures occur. ```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() ``` -------------------------------- ### Run Tests Using Latest Configuration (Unix/Linux) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/cmd Load the latest GdUnitRunner.cfg configuration and run the configured tests on Unix/Linux systems. This is convenient for repeating the last test session. ```bash ./addons/gdUnit4/runtest -conf ``` -------------------------------- ### C# Vector Equality Assertion Examples Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-vector Examples of successful and failing vector equality assertions in C#. The assertion fails if the vectors are not exactly equal. ```csharp // this assertion succeeds AssertThat(Vector2.One).IsEqual(Vector2.One); // should fail because is NOT equal AssertThat(Vector2.One).IsEqual(new Vector2(1.2f, 1.000001f)); ``` -------------------------------- ### Simulate Enter Key Release (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/keys Simulates the Enter key being released. Use `await runner.AwaitInputProcessed()` to ensure completion. ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Simulate the enter key is released runner.SimulateKeyRelease(KeyList.Enter); await runner.AwaitInputProcessed(); ``` -------------------------------- ### GdScript Vector Equality Assertion Examples Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-vector Examples demonstrating successful and failing vector equality assertions in GdScript. The assertion fails if any component of the vector is not equal. ```gdscript # this assertion succeeds assert_vector(Vector2(1.1, 1.2)).is_equal(Vector2(1.1, 1.2)) # this assertion fails because part y of the vector 1.2 are not equal to 1.3 assert_vector(Vector2(1.1, 1.2)).is_equal(Vector2(1.1, 1.3)) ``` -------------------------------- ### Run Tests Using Latest Configuration Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/cmd Load the latest GdUnitRunner.cfg configuration and run the configured tests. This is convenient for repeating the last test session. ```bash ./addons/gdUnit4/runtest.sh -conf ``` -------------------------------- ### GdScript Vector Less Than Assertion Examples Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-vector Examples demonstrating successful vector less than assertions in GdScript. The assertion checks if the current vector is component-wise less than the expected vector. ```gdscript # this assertion succeeds assert_vector(Vector2.ZERO.is_less(Vector2.ONE) assert_vector(Vector2(1.1, 1.2)).is_less(Vector2(1.1, 1.3)) ``` -------------------------------- ### GdUnit Command Line Tool Help Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/cmd Displays the help message for the GdUnit command-line tool, outlining available commands and options. ```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] ``` -------------------------------- ### C# Vector Approximate Equality Assertion Examples Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-vector Examples of successful and failing approximate equality assertions in C#. The assertion checks if the vector components are within the specified approximation range. ```csharp // this assertion succeeds AssertVec2(Vector2.One).IsEqualApprox(Vector2.One, new Vector2(0.004f, 0.004f)); // should fail because is NOT equal approximated AssertVec2(new Vector2(1.005f, 1f)).IsEqualApprox(Vector2.One, new Vector2(0.004f, 0.004f)); ``` -------------------------------- ### GdScript Vector Approximate Equality Assertion Examples Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-vector Examples of successful and failing approximate equality assertions in GdScript. The assertion checks if the vector components are within the specified approximation range. ```gdscript # this assertion succeeds assert_vector(Vector2(0.996, 0.996)).is_equal_approx(Vector2.ONE, Vector2(0.004, 0.004)) # this will fail because the vector is out of approximated range assert_vector(Vector2(1.005, 1)).is_equal_approx(Vector2.ONE, Vector2(0.004, 0.004)) ``` -------------------------------- ### Simulate Complete Drag and Drop (GdScript) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/touchscreen Simulates a complete drag and drop event from a start position to an end position. Ideal for testing complex drag-and-drop scenarios with defined start and end points. ```GdScript 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: ``` ```GdScript 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)) ``` -------------------------------- ### Load Scene with Scene Runner (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/sceneRunner Loads a scene to be tested using the Scene Runner in C#. This is the initial step to begin scene simulation. ```C# ISceneRunner runner = ISceneRunner.Load("res://my_scene.tscn"); ``` -------------------------------- ### Mocking by Class Name or Resource Path Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/mock Shows how to create mocked instances of a class using either its 'class_name' or its full resource path if 'class_name' is not defined. ```gdscript # Example class class_name TestClass extends Node ... ``` ```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") ``` -------------------------------- ### Get Mouse Position (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/mouse Retrieves the current mouse cursor position within the viewport. ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // gets the current mouse position var mousePosition = runner.GetMousePosition(); ``` -------------------------------- ### Simulate Enter Key Release (GdScript) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/keys Simulates the Enter key being released. Use `await runner.await_input_processed()` to ensure completion. ```gdscript var runner := scene_runner("res://test_scene.tscn") # Simulate the enter key is released runner.simulate_key_release(KEY_ENTER) await runner.await_input_processed() ``` -------------------------------- ### Simulate Enter Key Press (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/keys Simulates the Enter key being pressed. Use `await runner.AwaitInputProcessed()` to ensure completion. ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Simulate the enter key is pressed runner.SimulateKeyPress(KeyList.Enter); await runner.AwaitInputProcessed(); ``` -------------------------------- ### Get Mouse Position (GdScript) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/mouse Retrieves the current mouse cursor position within the viewport. ```gdscript var runner := scene_runner("res://test_scene.tscn") # gets the current mouse position var mouse_position := runner.get_mouse_position() ``` -------------------------------- ### Assert Integer Is Not Zero Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is not equal to zero. Examples are shown for GdScript and C#. ```GdScript # this assertion succeeds assert_int(1).is_not_zero() # this assertion fail because the value is zero assert_int(0).is_not_zero() ``` ```C# // this assertion succeeds AssertThat(1).IsNotZero(); // this assertion fail because the value is zero AssertThat(0).IsNotZero(); ``` -------------------------------- ### Assert Integer Is Negative Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is a negative number. Examples are shown for GdScript and C#. ```GdScript # this assertion succeeds assert_int(-13).is_negative() # this assertion fail because the value '13' is positive assert_int(13).is_negative() ``` ```C# // this assertion succeeds AssertThat(-13).IsNegative(); // this assertion fail because the value '13' is positive AssertThat(13).IsNegative(); ``` -------------------------------- ### Verify Resource is a File Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-file Use `is_file()` to check if a resource exists and is readable as a file. It fails if the path points to a directory or a non-existent resource. ```GdScript func assert_file().is_file() -> GdUnitFileAssert ``` ```GdScript # this assertion succeeds if the file exists and can be opened assert_file("res://test.gd").is_file() # this assertion fails if the file doesn't exist or can't be opened assert_file("res://nonexistent.gd").is_file() assert_file("res://some_directory/").is_file() ``` -------------------------------- ### Assert Integer Is Odd Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is an odd number. Examples are shown for GdScript and C#. ```GdScript # this assertion succeeds assert_int(13).is_odd() # this assertion fail because the value '12' is even assert_int(12).is_odd() ``` ```C# // this assertion succeeds AssertThat(13).IsOdd(); // this assertion fail because the value '12' is even AssertThat(12).IsOdd(); ``` -------------------------------- ### Assert Integer Is Even Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is an even number. Examples are shown for GdScript and C#. ```GdScript # this assertion succeeds assert_int(12).is_even() # this assertion fail because the value '13' is not even assert_int(13).is_even() ``` ```C# // this assertion succeeds AssertThat(12).IsEven(); // this assertion fail because the value '13' is not even AssertThat(13).IsEven(); ``` -------------------------------- ### Simulate Ctrl+Alt+C Key Release (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/keys Simulates the Ctrl+Alt+C key combination being released. Use `await runner.AwaitInputProcessed()` to ensure completion. ```csharp // Simulates multi key combination ctrl+alt+C is released runner.SimulateKeyRelease(KeyList.Ctrl); runner.SimulateKeyRelease(KeyList.Alt); runner.SimulateKeyRelease(KeyList.C); await runner.AwaitInputProcessed(); ``` -------------------------------- ### Simulate Action Pressed (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/actions Simulates a full action press-and-release interaction. Use await runner.AwaitInputProcessed() to ensure the simulation is complete. ```csharp ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Simulate the UP key is pressed by using the input action "ui_up" runner.SimulateActionPressed("ui_up"); await runner.AwaitInputProcessed(); ``` -------------------------------- ### Get Current Scene Instance (GdScript) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing//scene_runner/accessors Retrieves the root node of the currently loaded and managed scene. ```gdscript ## 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: ``` Here is an example of how to use scene(): ``` var runner := scene_runner("res://test_scene.tscn") # Gets access to the scene instance var my_scene := runner.scene() ``` ``` -------------------------------- ### Simulate Ctrl+C Key Release (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/keys Simulates the Ctrl+C key combination being released. Use `await runner.AwaitInputProcessed()` to ensure completion. ```csharp // Simulates key combination ctrl+C is releasedrunner.SimulateKeyRelease(KeyList.Ctrl); runner.SimulateKeyRelease(KeyList.C); await runner.AwaitInputProcessed(); ``` -------------------------------- ### Simulate Action Release (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/actions Completes a key interaction by releasing the action. Use await runner.AwaitInputProcessed() to ensure the simulation is complete. ```csharp /// /// Simulates that an action has been released. /// /// The name of the action, e.g., "ui_up". /// The SceneRunner instance. ISceneRunner SimulateActionRelease(string action); ``` -------------------------------- ### Assert Integer Is In Set Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is present within a given set of values. This example is for GdScript. ```GdScript func assert_int().is_in( :Array) -> GdUnitIntAssert ``` -------------------------------- ### Initialize Scene Runner (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/touchscreen Initializes the scene runner in C# for simulating touchscreen events. This is a prerequisite for using any of the simulation methods. ```C# ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); ``` -------------------------------- ### Verify Resource Exists Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-file Use `exists()` to confirm that a resource is present in the file system. This assertion fails if the specified path does not exist. ```GdScript func assert_file().exists() -> GdUnitFileAssert ``` ```GdScript # this assertion succeeds if the file exists assert_file("res://test.gd").exists() # this assertion fails if the file doesn't exist assert_file("res://nonexistent.gd").exists() ``` -------------------------------- ### Assert Integer Greater Than Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is strictly greater than a specified value. Examples are shown for GdScript and C#. ```GdScript assert_int(23).is_greater(20) assert_int(23).is_greater(22) // this assertion fails because 23 is not greater than 23 assert_int(23).is_greater(23) ``` ```C# // this assertion succeeds AssertThat(23).IsGreater(20); AssertThat(23).IsGreater(22); // this assertion fails because 23 is not greater than 23 AssertThat(23).IsGreater(23); ``` -------------------------------- ### Simulate Full Key Press-and-Release (GdScript) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/keys Use simulate_key_pressed to simulate a complete key press and release action. Ensure input events are processed by awaiting runner.await_input_processed(). ```gdscript func simulate_key_pressed(key_code: int, shift := false, control := false) -> GdUnitSceneRunner: ``` ```gdscript var runner := scene_runner("res://test_scene.tscn") # Simulate the enter key is pressed runner.simulate_key_pressed(KEY_ENTER) await runner.await_input_processed() # Simulates key combination ctrl+C is pressedrunner.simulate_key_press(KEY_CTRL) runner.simulate_key_pressed(KEY_C) await runner.await_input_processed() ``` -------------------------------- ### Simulate Ctrl+Alt+C Key Release (GdScript) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/keys Simulates the Ctrl+Alt+C key combination being released. Use `await runner.await_input_processed()` to ensure completion. ```gdscript # Simulates multi key combination ctrl+alt+C is released runner.simulate_key_release(KEY_CTRL) runner.simulate_key_release(KEY_ALT) runner.simulate_key_release(KEY_C) await runner.await_input_processed() ``` -------------------------------- ### Simulate Ctrl+C Key Release (GdScript) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/keys Simulates the Ctrl+C key combination being released. Use `await runner.await_input_processed()` to ensure completion. ```gdscript # Simulates key combination ctrl+C is releasedrunner.simulate_key_release(KEY_CTRL) runner.simulate_key_release(KEY_C) await runner.await_input_processed() ``` -------------------------------- ### Assert Integer Is Not Negative Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is not a negative number (i.e., zero or positive). Examples are shown for GdScript and C#. ```GdScript # this assertion succeeds assert_int(13).is_not_negative() # this assertion fail because the value '-13' is negative assert_int(-13).is_not_negative() ``` ```C# // this assertion succeeds AssertThat(13).IsNotNegative(); // this assertion fail because the value '-13' is negative AssertThat(-13).IsNotNegative(); ``` -------------------------------- ### Assert Integer Greater Than or Equal To Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/assert-integer Use this to verify if an integer is greater than or equal to a specified value. Examples are shown for GdScript and C#. ```GdScript assert_int(23).is_greater_equal(20) assert_int(23).is_greater_equal(23) # this assertion fails because 23 is not greater than 23 assert_int(23).is_greater_equal(24) ``` ```C# AssertThat(23).IsGreaterEqual(20) AssertThat(23).IsGreaterEqual(23) // this assertion fails because 23 is not greater than 23 AssertThat(23).IsGreaterEqual(24) ``` -------------------------------- ### Simulate Action Pressed (GdScript) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/actions Simulates a full action press-and-release interaction. Use await runner.await_input_processed() to ensure the simulation is complete. ```gdscript var runner := scene_runner("res://test_scene.tscn") # Simulate the UP key is pressed by using the input action "ui_up" runner.simulate_action_pressed("ui_up") await runner.await_input_processed() ``` -------------------------------- ### Basic Spy Interaction and Verification Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/spy This snippet demonstrates the basic usage of spies to record and verify function calls. It shows how to spy on a node, call its methods, and then verify those calls. ```gdscript var spyed_node = spy(Node.new()) spyed_node.is_a_parent_of(null) spyed_node.set_process(false) verify(spyed_node).is_a_parent_of(null) verify(spyed_node).set_process(false) ``` -------------------------------- ### Get Scene Access in GdScript Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing//scene_runner/accessors Provides access to the current running scene object. Use when direct scene manipulation is needed. ```gdscript # Gets access to the current running scene var scene = runner.scene ``` -------------------------------- ### Complete First Test using Resource Path Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/first_steps/getting-started Completes the 'test_full_name' test by loading the 'TestPerson' script using its resource path and asserting the expected full name. ```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") ``` -------------------------------- ### Simulate Frames and Test Scene Behavior (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/sceneRunner Tests scene behavior by simulating frames, invoking functions, and asserting property changes. Requires the scene runner to be initialized and the scene node to be accessible. ```C# [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); } ``` -------------------------------- ### Simulate Ctrl+Alt+C Key Press (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/scene_runner/keys Simulates the Ctrl+Alt+C key combination being pressed. Use `await runner.AwaitInputProcessed()` to ensure completion. ```csharp // Simulates multi key combination ctrl+alt+C is pressed runner.SimulateKeyPress(KeyList.Ctrl); runner.SimulateKeyPress(KeyList.Alt); runner.SimulateKeyPress(KeyList.C); await runner.AwaitInputProcessed(); ``` -------------------------------- ### Get Scene Access in C# Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing//scene_runner/accessors Provides access to the current running scene object. Use when direct scene manipulation is needed in C#. ```csharp // Gets access to the current running scene var scene = runner.Scene; ``` -------------------------------- ### Get Property Value in GdScript Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing//scene_runner/accessors Retrieves the current value of a specified property from the scene. Use when you need to inspect a node's state. ```gdscript var runner := scene_runner("res://test_scene.tscn") # Returns the current property `_door_color` from the scene var color: ColorRect = runner.get_property("_door_color") ``` -------------------------------- ### Load and Simulate Frames (C#) Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/advanced_testing/sceneRunner Loads a scene and simulates its processing for a given number of frames. The default deltaPeerFrame is used if not specified. ```C# ISceneRunner runner = ISceneRunner.Load("res://test_scene.tscn"); // Simulate scene processing over 60 frames at normal speed await runner.SimulateFrames(60); // Simulate scene processing over 60 frames with a delay of 100ms between each frame await runner.SimulateFrames(60, 100); ``` -------------------------------- ### GdScript TestSuite with Hooks Source: https://godot-gdunit-labs.github.io/gdUnit4/latest/testing/test-suite Defines a GdUnit TestSuite in GdScript with suite-level setup and teardown hooks, and two test cases for string case conversion. ```GdScript extends GdUnitTestSuite func before() -> void: # Setup suite-level shared resources, expensive setup func after() -> void: # Cleanup suite-level shared resources, expensive setup func test_string_to_lower() -> void: assert_str("AbcD".to_lower()).is_equal("abcd") func test_string_to_upper() -> void: assert_str("AbcD".to_upper()).is_equal("ABCD") ```