### Connect to Test Start Signal Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Global-Lifecycle-Hooks.md Connect to the `start_test` signal in a pre-run hook to execute setup logic before every test. ```gdscript extends GutHookScript func run(): gut.start_test.connect(_on_test_started) func _on_test_started(test_name): # setup logic run before every test in every test script goes here ``` -------------------------------- ### GutTest Simple Example Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Demonstrates the basic structure of a GutTest script, including setup, teardown, and test methods. Use this as a template for your own test files. ```gdscript extends GutTest func before_all(): gut.p("before_all called" func before_each(): gut.p("before_each called") func after_each(): gut.p("after_each called") func after_all(): gut.p("after_all called") func test_assert_eq_letters(): assert_eq("asdf", "asdf", "Should pass") func test_assert_eq_number_not_equal(): assert_eq(1, 2, "Should fail. 1 != 2") ``` -------------------------------- ### GUT Pre/Post Run Hook Script Example Source: https://context7.com/bitwes/gut/llms.txt Hook scripts extend `GutHookScript` and implement the `run()` method to execute setup or teardown logic before or after tests. This example shows muting audio, setting global flags, registering inner classes, and aborting the run if fixtures are missing. ```gdscript # res://test/hooks/pre_run.gd extends GutHookScript var SomeScript = load('res://scripts/some_script.gd') func run(): # Mute audio during tests AudioServer.set_bus_volume_db(0, -INF) # Set global flags to prevent file I/O during tests GlobalConfig.testing_mode = true # Register inner classes for all tests - avoids repeating in each test register_inner_classes(SomeScript) # Abort the run if environment is not ready if not FileAccess.file_exists("res://test/fixtures/data.json"): gut.p("ERROR: Test fixtures missing!") abort() ``` -------------------------------- ### Basic GutControl Setup in a Scene Script Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Running-On-Devices.md This script demonstrates the minimal setup required to load a GUT configuration file and initialize GutControl within a game scene. Ensure your `.gutconfig.json` is exported with your game resources. ```gdscript # ------------------------------------------------------------------------------ # This is an example of using the GutControl (res://addons/gut/gui/GutContro.tscn) # to execute tests in a deployed game. # # Setup: # Create a scene. # Add a GutControl to your scene, name it GutControl. # Add this script to your scene. # Run it. # ------------------------------------------------------------------------------ extends Node2D @onready var _gut_control = $GutControl # Holds a reference to the current test script object being run. Set in # signal callbacks. var _current_script_object = null # Holds the name of the current test being run. Set in signal callbacks. var _current_test_name = null func _ready(): ssimple_setup() # complex_setup() func simple_setup(): # You must load a gut config file to use this control. Here we are loading # the default config file used by the command line. You can use any config # file you have created. Use the "save as" button in the Settings subpanel # to create a config file, or write your own. # # Some settings may not work. For example, the exit flags do not have any # effect. # # Settings are not saved, so any changes will be lost. The idea is that you # want to deploy the settings and users should not be able to save them. If # you want to save changes, you can call: # _gut_control.get_config().write_options(path). # Note that you cannot to write to res:// on mobile platforms, so you will # have to juggle the initial loading from res:// or user:// and save to # user://. _gut_control.load_config_file('res://.gutconfig.json') # That's it. Just get a reference to the control you added to the scene and # give it a config. The rest of the stuff in this script optional. func complex_setup(): # See simple setup _gut_control.load_config_file('res://.gutconfig.json') # Returns a gut_config.gd instance. var config = _gut_control.get_config() # Override specific values for the purposes of this scene. You can see all # the options available in the default_options dictionary in gut_config.gd. # Changing settings AFTER _ready will not have any effect. config.options.should_exit = false config.options.should_exit_on_success = false config.options.compact_mode = false # Note that if you are exporting xml results you may want to set the path to # a file in user:// instead of an absolute path. Your game may not have # permissions to save files elsewhere when running on a mobile device. config.options.junit_xml_file = 'user://deployed_results.xml' # Some actions cannot be done until after _ready has finished in all objects _post_ready_setup.call_deferred() # If you would like to connect to signals provided by gut.gd then you must do # so after _ready. This is an example of getting a reference to gut and all # of the signals it provides. func _post_ready_setup(): var gut = _gut_control.get_gut() gut.start_run.connect(_on_gut_run_start) gut.start_script.connect(_on_gut_start_script) gut.end_script.connect(_on_gut_end_script) gut.start_test.connect(_on_gut_start_test) gut.end_test.connect(_on_gut_end_test) gut.end_run.connect(_on_gut_run_end) # ----------------------- # Events # ----------------------- func _on_gut_run_start(): print('Starting tests') # This signal passes a TestCollector.gd/TestScript instance func _on_gut_start_script(script_obj): print(script_obj.get_full_name(), ' has ', script_obj.tests.size(), ' tests') _current_script_object = script_obj func _on_gut_end_script(): var pass_count = 0 for test in _current_script_object.tests: if(test.did_pass()): pass_count += 1 print(pass_count, '/', _current_script_object.tests.size(), " passed\n") _current_script_object = null func _on_gut_start_test(test_name): _current_test_name = test_name print(' ', test_name) func _on_gut_end_test(): # get_test_named returns a TestCollector.gd/Test instance for the name # passed in. var test_object = _current_script_object.get_test_named(_current_test_name) var status = "failed" if(test_object.did_pass()): status = "passed" elif(test_object.pending): status = "pending" print(' ', status) _current_test_name = null func _on_gut_run_end(): print('Tests Done') ``` -------------------------------- ### GDScript Test Setup and Assertion Source: https://github.com/bitwes/gut/blob/main/test/resources/parsing_and_loading_samples/test_bad_extension.txt This snippet shows a basic test setup using GUT, including a `before_each` method and a test case with an `assert_eq` that is designed to fail. ```gdscript extends "res://addons/gut/test.gd" func before_each(): gut.p("ran before_each", 2) func test_assert_eq_number_not_equal(): assert_eq(1, 2, "Should fail. 1 != 2") ``` -------------------------------- ### Setup and Teardown Methods in GUT Tests Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Quick-Start.md Utilize setup and teardown methods like `before_all`, `before_each`, `after_each`, and `after_all` to manage test execution context. These methods run at specific points during the test suite's lifecycle. ```gdscript extends GutTest func before_all(): gut.p("Runs once before all tests") func before_each(): gut.p("Runs before each test.") func after_each(): gut.p("Runs after each test.") func after_all(): gut.p("Runs once after all tests") func test_assert_eq_number_not_equal(): assert_eq(1, 2, "Should fail. 1 != 2") func test_assert_eq_number_equal(): assert_eq('asdf', 'asdf', "Should pass") ``` -------------------------------- ### before_all Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Setup method that runs once before all tests in the suite. ```APIDOC ## before_all ### Description Setup method that runs once before all tests in the suite. ### Method Variant.before_all ### Parameters None. ``` -------------------------------- ### before_each Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Setup method that runs before each test case. ```APIDOC ## before_each ### Description Setup method that runs before each test case. ### Method Variant.before_each ### Parameters None. ``` -------------------------------- ### Example Pre-Run Hook Script Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Global-Lifecycle-Hooks.md Connects to various GUT lifecycle signals to log test and script execution details. This example demonstrates how to access information about the current test script and test method. ```gdscript extends GutHookScript const NO_TEST := "__NO_TEST__" var _current_test_script_object = null var _current_collected_script = null var _current_test_name := NO_TEST func run(): gut.start_run.connect(_on_run_started) gut.start_script.connect(_on_script_started) gut.start_test.connect(_on_test_started) gut.end_test.connect(_on_test_ended) gut.end_script.connect(_on_script_ended) gut.end_run.connect(_on_run_ended) # Do pre-run stuff here # This might be redundant, and it might have already been emitted by the time # this hook is called. I wanted it in here for illustration purposes. func _on_run_started(): pass # This is passed an instance of res://addons/gut/collected_script.gd. It is not # the instance of the script that will be run. You can get to the script object # using `load_script`, but you can't get to the actual instance that will be # run. func _on_script_started(collected_script): _current_collected_script = collected_script # The GutTest script, not the instance. _current_test_script_object = collected_script.load_script() # _current_collected_script.get_full_name() returns the path of the file # that contains the test # This is just the name of the test method being ran. func _on_test_started(test_name): _current_test_name = test_name func _on_test_ended(): # example of inspecing the test that ended if you wanted to. var failed = _current_collected_script.get_test_named(_current_test_name).is_failing() if (failed): print(_current_test_name + " failed") else: print(_current_test_name + " passed") _current_test_name = NO_TEST func _on_script_ended(): #example of inspecing the script that ended if you wanted to if(!_current_collected_script.was_skipped): if(_current_collected_script.get_fail_count() > 0): print("The script ", _current_collected_script.get_full_name(), " failed") else: print("The script ", _current_collected_script.get_full_name(), " passed") _current_collected_script = null _current_test_script_object = null # I'm not sure if this is called before or after the post-run hook. This can't ``` -------------------------------- ### Get Help Text for All Options Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Returns a string containing the help text for all defined command-line options. ```gdscript func get_help() -> String: # ... implementation details ... pass ``` -------------------------------- ### Basic GutTest Script Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Creating-Tests.md A sample GutTest script demonstrating setup, teardown, and various assertion types. Place this in `res://test/unit/test_example.gd` to run. ```gdscript extends GutTest func before_each(): gut.p("ran setup", 2) func after_each(): gut.p("ran teardown", 2) func before_all(): gut.p("ran run setup", 2) func after_all(): gut.p("ran run teardown", 2) func test_assert_eq_number_not_equal(): assert_eq(1, 2, "Should fail. 1 != 2") func test_assert_eq_number_equal(): assert_eq('asdf', 'asdf', "Should pass") func test_assert_true_with_true(): assert_true(true, "Should pass, true is true") func test_assert_true_with_false(): assert_true(false, "Should fail") func test_something_else(): assert_true(false, "didn't work") ``` -------------------------------- ### Example of Orphans in a GUT Test Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Memory-Management.md This example demonstrates how GUT reports orphaned nodes within a test case. It shows the structure of the orphan report, including the number of orphans and their types. ```gdscript * test_this_makes_two_orphans 2 Orphans * test_two_one: * test_two_two: * test_with_a_scene_orphan 104 Orphans * main:(main.gd) + 27 * GutRunner:(GutRunner.gd) + 75 ``` -------------------------------- ### Inner Test Classes Example Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Creating-Tests.md Organize tests into inner classes that extend GutTest. Each inner class can have its own setup and teardown methods. ```gdscript extends GutTest class TestFeatureA: extends GutTest var Obj = load('res://scripts/object.gd') var _obj = null func before_each(): _obj = Obj.new() func test_something(): assert_true(_obj.is_something_cool(), 'Should be cool.') class TestFeatureB: extends GutTest var Obj = load('res://scripts/object.gd') var _obj = null func before_each(): _obj = Obj.new() func test_foobar(): assert_eq(_obj.foo(), 'bar', 'Foo should return bar') ``` -------------------------------- ### Assert Between Examples Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Examples demonstrating the usage of assert_between for checking if a value falls within a specified range (exclusive). ```default assert_between('a', 'b', 'c') assert_between(1, 5, 10) ``` -------------------------------- ### assert_string_starts_with Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Asserts that a string starts with a specific prefix. Takes the main string, the prefix, and an optional case-matching flag. ```APIDOC ## assert_string_starts_with ### Description Asserts that a string begins with a specified prefix. This method supports case-sensitive and case-insensitive comparisons. ### Method Signature `assert_string_starts_with(text, search, match_case = true)` ### Parameters - **text** (string) - The string to check. - **search** (string) - The prefix to look for at the beginning of the string. - **match_case** (boolean, optional, default: true) - If true, the comparison is case-sensitive. ``` -------------------------------- ### GUT Configuration File Example Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Command-Line.md A sample JSON configuration file for GUT, specifying directories, test prefixes, suffixes, and other execution options. This file is loaded by default at res://.gutconfig.json or can be specified with the -gconfig option. ```json { "dirs":["res://test/unit/","res://test/integration/"], "double_strategy":"partial", "ignore_pause":false, "include_subdirs":true, "inner_class":"", "log_level":3, "opacity":100, "prefix":"test_", "selected":"", "should_exit":true, "should_maximize":true, "suffix":".gd", "tests":[], "unit_test_name":"" } ``` -------------------------------- ### Simulate Object Processing Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Simulate.md This example demonstrates how to use `gut.simulate` to run `_process` and `_physics_process` methods on a tree of objects. It shows how to set up objects with these methods and then assert their state after simulation. ```gdscript extends Node2D var a_number = 1 func _process(delta): a_number += 1 ``` ```gdscript extends Node2D var another_number = 1 func _physics_process(delta): another_number += 1 ``` ```gdscript var MyObject = load('res://scripts/my_object.gd') var AnotherObject = load('res://scripts/another_object') ``` ```gdscript # Given that SomeCoolObj has a _process method that increments a_number by 1 # each time _process is called, and that the number starts at 0, this test # should pass func test_does_something_each_loop(): var my_obj = MyObject.new() add_child_autofree(my_obj) gut.simulate(my_obj, 20, .1) assert_eq(my_obj.a_number, 20, 'Since a_number is incremented in _process, it should be 20 now') ``` ```gdscript # Let us also assume that AnotherObj acts exactly the same way as # but has SomeCoolObj but has a _physics_process method instead of # _process. In that case, this test will pass too since all child objects # have the _process or _physics_process method called. func test_does_something_each_loop(): var my_obj = MyObject.new() var other_obj = AnotherObj.new() add_child_autofree(my_obj) my_obj.add_child(other_obj) gut.simulate(my_obj, 20, .1) assert_eq(my_obj.a_number, 20, 'Since a_number is incremented in _process, \ it should be 20 now') assert_eq(other_obj.another_number, 20, 'Since other_obj is a child of my_obj \ and another_number is incremented in \ _physics_process then it should be 20 now') ``` -------------------------------- ### Assert Equality Example Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Demonstrates how to use assert_eq to check if two values are equal. This is useful for verifying expected outcomes in tests. It also shows variable initialization. ```gdscript var one = 1 var node1 = Node.new() var node2 = node1 ``` -------------------------------- ### Basic Node Creation in GUT Test Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Memory-Management.md This snippet shows a basic test setup where a new node is created. It's intended to be used with `autofree` for automatic cleanup. ```gdscript func test_something(): var my_node = Node.new() assert_not_null(my_node) ``` -------------------------------- ### Common Error: Resource Loading Failure Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Command-Line.md An example of a common error encountered when there is a space in the command-line arguments, specifically after an option like -gselect. ```text ERROR: No loader found for resource: res://samples3 At: core\io\resource_loader.cpp:209 ERROR: Failed loading scene: res://samples3 At: main\main.cpp:1260 ``` -------------------------------- ### InputSender Setup and Cleanup Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Mocking-Input.md Initialize InputSender at the class level and use after_each to release all inputs and clear the sender. This prevents input state leakage between tests. ```gdscript extends GutTest # When sending events to Input the InputSender instance should be defined at # the class level so that you can easily clear it between tests in after_each. var _sender = InputSender.new(Input) # IMPORTANT: When using Input as the receiver of events you should always # release_all and clear the InputSender so that any # actions/keys/buttons that are not released in a test are released # before the next test runs. "down" events will not be sent by # Input if the action/button/etc is currently "down". func after_each(): _sender.release_all() _sender.clear() ``` -------------------------------- ### GUT Configuration File (.gutconfig.json) Source: https://context7.com/bitwes/gut/llms.txt Configure GUT behavior using a JSON file at `res://.gutconfig.json`. Command-line flags override these settings. This example shows directory configuration, double strategy, and logging level. ```json { "dirs": ["res://test/unit/", "res://test/integration/"], "double_strategy": "SCRIPT_ONLY", "ignore_pause": false, "include_subdirs": true, "inner_class": "", "log_level": 1, "opacity": 100, "prefix": "test_", "should_exit": true, "should_maximize": false, "suffix": ".gd", "tests": [], "unit_test_name": "", "junit_xml_file": "user://results.xml", "junit_xml_timestamp": false, "failure_error_types": ["engine", "gut", "push_error"] } ``` -------------------------------- ### Assert String Starts With Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Use assert_string_starts_with to verify if a string begins with a specified substring. A case-insensitive check can be performed by setting match_case to false. ```gdscript # Passing assert_string_starts_with('abc 123', 'a') assert_string_starts_with('abc 123', 'ABC', false) assert_string_starts_with('abc 123', 'abc 123') ``` ```gdscript ## Failing assert_string_starts_with('abc 123', 'z') assert_string_starts_with('abc 123', 'ABC') assert_string_starts_with('abc 123', 'abc 1234') ``` -------------------------------- ### Basic GUT Test Script Structure Source: https://context7.com/bitwes/gut/llms.txt Create test scripts by extending `GutTest` and prefixing test methods with `test_`. Lifecycle hooks like `before_each` and `after_each` can be used for setup and teardown. Use `pending` for unimplemented tests. ```gdscript # res://test/unit/test_my_class.gd extends GutTest var MyClass = load('res://scripts/my_class.gd') var _subject = null func before_each(): _subject = MyClass.new() func after_each(): _subject.free() func test_initial_value_is_zero(): assert_eq(_subject.get_count(), 0, "Initial count should be 0") func test_increment_increases_count(): _subject.increment() assert_eq(_subject.get_count(), 1, "Count should be 1 after increment") func test_is_active_returns_true(): assert_true(_subject.is_active(), "Should be active by default") func test_name_is_not_empty(): assert_ne(_subject.get_name(), "", "Name should not be empty") func test_pending_feature(): pending("This feature is not implemented yet") ``` -------------------------------- ### Basic Parameterized Test Setup in GDScript Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Parameterized-Tests.md Define a test that runs multiple times with different parameter sets. Ensure the test has exactly one parameter defaulted to `use_parameters` with an array. ```gdscript extends GutTest class Foo: func add(p1, p2): return p1 + p2 # Define one array, with two arrays as the elements in the array. # This will cause the test to be called twice. The first # call will get [1, 2, 3] as the value of the parameter. # The second call will get ['a', 'b', 'c'] var foo_params = [[1, 2, 3], ['a', 'b', 'c']] # This test will add the first two elements in params together, # using Foo, and assert that they equal the third element in params. func test_foo(params=use_parameters(foo_params)): var foo = Foo.new() var result = foo.add(params[0], params[1]) assert_eq(result, params[2]) ``` -------------------------------- ### Load Double Tools Source: https://github.com/bitwes/gut/blob/main/addons/gut/double_templates/double_data_template.txt Loads the necessary tools for creating test doubles from the GUT framework. This should be called once during the setup of a test double. ```gdscript var __gutdbl = load('res://addons/gut/double_tools.gd').new(self) ``` -------------------------------- ### is_option Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Tests if a given argument is an existing option by checking if its string representation starts with the option name prefix. ```APIDOC ## is_option ### Description Test if something is an existing argument. If `str(arg)` begins with the [option_name_prefix](#class-addons-gut-cli-optparse-gd-property-option-name-prefix), it will considered true, otherwise it will be considered false. ### Method `is_option(arg)` ### Parameters * **arg** (any) - The argument to test. ### Returns * **bool** - True if the argument is an option, false otherwise. ``` -------------------------------- ### Build Docker Image for Documentation Source: https://github.com/bitwes/gut/blob/main/documentation/README.md Run this command from the `documentation` directory to build the Docker container for local documentation generation. This only needs to be done once if the container does not exist. ```bash docker-compose -f docker/compose.yml build ``` -------------------------------- ### Stubbing a Method in a Partial Double Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Partial-Doubles.md Demonstrates stubbing the `set_value` method to do nothing, bypassing its original implementation. The `get_value` method retains its original functionality because it was not stubbed. This example also shows how to assert that methods were called. ```gdscript var Foo = load('res://script.gd') func test_things(): var partial = partial_double(Foo).new() stub(partial, 'set_value').to_do_nothing() partial.set_value(20) # stubbed so implementation bypassed. # since set_value was stubbed, and get_value was not, and since # this is a partial stub, then the original functionality of # get_value will be executed and _value is returned. assert_eq(partial.get_value(), 10) # unstubbed partial methods can be spied on. assert_called(partial, 'get_value') # stubbed methods can be spied on as well assert_called(partial, 'set_value', [20]) ``` -------------------------------- ### Testing for Memory Leaks with free() Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Memory-Management.md This example demonstrates a common pattern for testing memory leaks. It creates an object, frees it explicitly using `free()`, and then asserts that no new orphans were created. ```gdscript # res://test/unit/test_foo.gd extends GutTest ... class TestLeaks: extends GutTest var Foo = load('res://foo.gd') func test_no_leaks(): var to_free = Foo.new() to_free.free() assert_not_new_orphans() ``` -------------------------------- ### Assert Not Between Examples Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Examples for assert_not_between, verifying that a value is outside a given range (exclusive). Includes passing and failing scenarios. ```default # Passing assert_not_between(1, 5, 10) assert_not_between('a', 'b', 'd') assert_not_between('d', 'b', 'd') assert_not_between(10, 0, 10) assert_not_between(-2, -2, 10) # Failing assert_not_between(5, 0, 10, 'Five shouldnt be between 0 and 10') assert_not_between(0.25, -2.0, 4.0) ``` -------------------------------- ### get_elapsed_msec Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Gets the number of milliseconds that have elapsed. ```APIDOC ## get_elapsed_msec ### Description Gets the number of milliseconds that have elapsed. ### Method int.get_elapsed_msec ### Parameters None. ``` -------------------------------- ### get_double_strategy Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Gets the current double strategy. ```APIDOC ## get_double_strategy ### Description Gets the current double strategy. ### Method Variant.get_double_strategy ### Parameters None. ``` -------------------------------- ### get_help Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Returns the help text for all defined command-line options. ```APIDOC ## get_help() -> String ### Description Returns the help text for all defined options. ### Returns * String - The help text for all options. ``` -------------------------------- ### Print Help Text for All Options Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Prints the generated help text for all defined command-line options to the console. ```gdscript func print_help() -> void: # ... implementation details ... pass ``` -------------------------------- ### get_elapsed_physics_frames Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Gets the number of physics frames that have elapsed. ```APIDOC ## get_elapsed_physics_frames ### Description Gets the number of physics frames that have elapsed. ### Method int.get_elapsed_physics_frames ### Parameters None. ``` -------------------------------- ### print_help Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Prints the help text for all defined command-line options to the console. ```APIDOC ## print_help() ### Description Prints out the help text for all defined options. ### Returns * None ``` -------------------------------- ### get_elapsed_idle_frames Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Gets the number of idle frames that have elapsed. ```APIDOC ## get_elapsed_idle_frames ### Description Gets the number of idle frames that have elapsed. ### Method int.get_elapsed_idle_frames ### Parameters None. ``` -------------------------------- ### Generate Documentation Locally Source: https://github.com/bitwes/gut/blob/main/documentation/README.md Execute this command from the `documentation` directory each time you need to regenerate the documentation locally. This command assumes the Docker image has already been built. ```bash docker-compose -f docker/compose.yml up ``` -------------------------------- ### Add Command-Line Options Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Use the `add` method to define command-line options with their types and descriptions. The help output will substitute '[default]' with the actual default value if included in the description. ```python add("--foo", false, "This will have the foo heading") add("--another_foo", 1.5, "This too.") add_heading("This is after foo") add("--bar", true, "You probably get it by now.") ``` -------------------------------- ### reset_start_times Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Resets the start times for all tracked operations. ```APIDOC ## reset_start_times ### Description Resets the start times for all tracked operations. ### Method N/A (Method call) ### Endpoint N/A ### Parameters None ### Request Example ```APIDOC GutTest.reset_start_times() ``` ### Response N/A ``` -------------------------------- ### get_call_count Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Gets the number of times a method has been called on an object. ```APIDOC ## get_call_count ### Description Gets the number of times a method has been called on an object. ### Method Variant.get_call_count ### Parameters #### Path Parameters - **object** (Variant) - The object to inspect. - **method_name** (Variant) - Optional. The name of the method. - **parameters** (Variant) - Optional. The parameters to match. ``` -------------------------------- ### get_elapsed_usec Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Returns the elapsed time in microseconds since the test started. ```APIDOC ## get_elapsed_usec ### Description Returns the elapsed time in microseconds since the test started. ### Method `get_elapsed_usec()` ### Returns - `int`: The elapsed time in microseconds. ``` -------------------------------- ### get_elapsed_sec Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Returns the elapsed time in seconds since the test started. ```APIDOC ## get_elapsed_sec ### Description Returns the elapsed time in seconds since the test started. ### Method `get_elapsed_sec()` ### Returns - `float`: The elapsed time in seconds. ``` -------------------------------- ### add Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Adds a command-line option with specified names, a default value, and a description. Returns the Option object on success or null on failure. ```APIDOC ## add ### Description Adds a command line option. If `op_names` is a String, this is set as the argument’s name. If `op_names` is an Array of Strings, all elements of the array will be aliases for the same argument and will be treated as such during parsing. `default` is the default value the option will be set to if it is not explicitly set during parsing. `desc` is a human readable text description of the option. If the option is successfully added, the Option object will be returned. If the option is not successfully added (e.g. a name collision with another option occurs), an error message will be printed and `null` will be returned. ### Method `add(op_names, default, desc: String)` ### Parameters * **op_names** (String | Array[String]) - The name(s) or aliases for the option. * **default** (any) - The default value for the option. * **desc** (String) - A human-readable description of the option. ### Returns * **Option** - The added Option object, or null if adding failed. ``` -------------------------------- ### before_all Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Virtual method. Run once before anything else in the test script is run. ```APIDOC ## before_all ### Description Virtual method. Run once before anything else in the test script is run. ### Method **before_all**() ``` -------------------------------- ### get_elapsed_process_frames Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Returns the number of process frames that have elapsed since the test started. ```APIDOC ## get_elapsed_process_frames ### Description Returns the number of process frames that have elapsed since the test started. ### Method `get_elapsed_process_frames()` ### Returns - `int`: The number of elapsed process frames. ``` -------------------------------- ### run() Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guthookscript.md Virtual method that will be called by GUT after instantiating this script. This is where you put all of your logic. ```APIDOC ## run() ### Description Virtual method that will be called by GUT after instantiating this script. This is where you put all of your logic. ### Method run ``` -------------------------------- ### Get Option Value or Null Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Retrieves the value of an option. Returns null if the option was not set. ```gdscript get_value_or_null("--name") ``` -------------------------------- ### Get Option Value Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Retrieves the value of an option. Returns the default value if the option was not set. ```gdscript get_value("--name") ``` -------------------------------- ### watch_signals Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Starts watching signals emitted by a given object. Useful for testing signal handling. ```APIDOC ## watch_signals ### Description Starts watching signals emitted by a given object. ### Parameters - **object** (Object) - The object whose signals to watch. ``` -------------------------------- ### Get Elapsed Microseconds Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Returns the number of microseconds elapsed since the test method began as an integer. ```gdscript get_elapsed_usec() ``` -------------------------------- ### Run Tests by Directory and Prefix Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Command-Line.md Load and run tests from a specified directory with a given prefix and suffix, selecting a specific test by name. The -gexit flag is omitted to allow for subsequent GUI test runs. ```bash godot -s addons/gut/gut_cmdln.gd -d --path "$PWD" -gdir=res://test/unit -gprefix=me_ -gsuffix=.res -gselect=only_me ``` -------------------------------- ### Get Elapsed Milliseconds Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Returns the number of milliseconds elapsed since the test method began as an integer. ```gdscript get_elapsed_msec() ``` -------------------------------- ### Get Elapsed Seconds Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Returns the number of seconds elapsed since the test method began as a float. ```gdscript get_elapsed_sec() ``` -------------------------------- ### parse Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Parses command-line arguments to set option values. Can parse provided arguments or the engine's startup arguments. ```APIDOC ## parse(cli_args: Variant = null) ### Description Parses a string for all options that have been set in this optparse. If `cli_args` is passed as a String, then it is parsed. Otherwise if `cli_args` is null, arguments passed to the Godot engine at startup are parsed. ### Parameters * **cli_args** (Variant, optional) - A string containing command-line arguments to parse, or null to parse engine startup arguments. Defaults to null. ``` -------------------------------- ### GUT Configuration for Hooks Source: https://context7.com/bitwes/gut/llms.txt This JSON snippet shows how to configure the paths for pre-run and post-run scripts in GUT. ```json { "pre_run_script": "res://test/hooks/pre_run.gd", "post_run_script": "res://test/hooks/post_run.gd" } ``` -------------------------------- ### Get Missing Required Options Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Returns an array of Option objects for all required options that were not found during parsing. ```gdscript get_missing_required_options() ``` -------------------------------- ### Reset Test Start Times Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Resets the time and frame tracking statistics for the current test method. ```gdscript reset_start_times() ``` -------------------------------- ### Mocking Database and User Service Calls Source: https://context7.com/bitwes/gut/llms.txt Demonstrates how to use `double()` to create test doubles for classes like Database and UserService. This allows for isolated testing of service logic by mocking dependencies. ```gdscript extends GutTest var Database = load('res://scripts/database.gd') var UserService = load('res://scripts/user_service.gd') func test_user_service_calls_database_save(): # Create doubles var db_double = double(Database).new() var service = UserService.new() service.database = db_double # Exercise service.create_user("Alice") # Spy assertions assert_called(db_double, "save", ["Alice"], "Database.save should be called with the user's name") assert_call_count(db_double, "save", 1, "Database.save called exactly once") ``` -------------------------------- ### Example `_on_run_ended` Hook Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Global-Lifecycle-Hooks.md This function serves as a post-run hook, similar to `after_every` hooks. It is called after a test run has concluded. ```gdscript func _on_run_ended(): pass # Do "after_every" things here. ``` -------------------------------- ### Class Using Time Singleton Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Doubling-Singletons.md This class demonstrates how to use the `Time` singleton for timing operations. It requires a reference to `Time` that can be injected. ```gdscript class_name UsesTime # Must have a reference to Engine Singleton that we can # inject our double into. var t := Time var _start_time = -1 func start(): _start_time = t.get_ticks_msec() func end(): var monday_extra = 0 if(t.get_date_dict_from_system().weekday == t.WEEKDAY_MONDAY): monday_extra = 10 return t.get_ticks_msec() - _start_time + monday_extra ``` -------------------------------- ### Assert Has Examples Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Demonstrates assert_has for checking if an object contains a specific element using its 'has' method. Works for arrays and hashes. ```default var an_array = [1, 2, 3, 'four', 'five'] var a_hash = { 'one':1, 'two':2, '3':'three'} # Passing assert_has(an_array, 'four') # PASS assert_has(an_array, 2) # PASS # the hash's has method checks indexes not values assert_has(a_hash, 'one') # PASS assert_has(a_hash, '3') # PASS ``` -------------------------------- ### Partial Doubling and Stubbing Methods Source: https://context7.com/bitwes/gut/llms.txt Shows how to create a partial double using `partial_double()` to override only specific methods while retaining original behavior for others. Also demonstrates stubbing built-in Godot nodes. ```gdscript func test_partial_double_retains_original_behavior(): var Foo = load('res://scripts/foo.gd') var partial = partial_double(Foo).new() # Only override one method; all others behave normally stub(partial.expensive_operation).to_return(42) assert_eq(partial.expensive_operation(), 42, "Stubbed method returns 42") # Other methods run their real implementation assert_called(partial, "expensive_operation") ``` ```gdscript func test_double_built_in_node(): var doubled_node = double(Node2D).new() stub(doubled_node, "get_position").to_return(Vector2(5, 10)) assert_eq(doubled_node.get_position(), Vector2(5, 10)) ``` -------------------------------- ### Get Elapsed Idle Frames Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Alias for wait_process_frames. Returns the number of idle frames elapsed since the test method began. ```gdscript get_elapsed_idle_frames() ``` -------------------------------- ### Generate and Print Help Message Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Generates and prints the help message for the configured options. The banner property can be set to add text before the usage and options. ```gdscript print_help() ``` -------------------------------- ### Get Missing Required Options Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_addons_gut_cli_optparse.md Retrieves an array of all required options that were not provided during parsing. This is useful for validating that all necessary arguments were supplied. ```gdscript func get_missing_required_options() -> Array: # ... implementation details ... pass ``` -------------------------------- ### action_up Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_gutinputfactory.md Creates an InputEventAction for an action being released. ```APIDOC ## action_up ### Description Creates an InputEventAction for an action being released. ### Method InputEventAction ### Parameters - **which** (string) - Description of the action name. - **strength** (float) - Optional. The strength of the action, defaults to 1.0. ``` -------------------------------- ### ParameterFactory.named_parameters: Insufficient Values Example Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Parameterized-Tests.md Illustrates `ParameterFactory.named_parameters` when the values array has fewer elements than specified names. Missing values are filled with null. ```gdscript # Example of not enough values. This returns: # [{a:1, b:null}, {a:'oops', b:null}, {a:'one', b:'two'}] ParameterFactory.named_parameters( ['a', 'b'], [ [1], 'oops', ['one', 'two'] ]) ``` -------------------------------- ### key_up Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_gutinputfactory.md Creates an InputEventKey for a key being released. ```APIDOC ## key_up ### Description Creates an InputEventKey for a key being released. ### Method InputEventKey ### Parameters - **which** (InputEventKey) - The key event details. ``` -------------------------------- ### ParameterFactory.named_parameters: Extra Values Example Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Parameterized-Tests.md Demonstrates the behavior of `ParameterFactory.named_parameters` when the values array contains more elements than specified names. Extra values are ignored. ```gdscript # Example of extra values. This returns: # [{a:1}, {a:3}] ParameterFactory.named_parameters( ['a'], [ [1, 2], [3, 4] ]) ``` -------------------------------- ### before_each Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Virtual method. Run before each test is executed ```APIDOC ## before_each ### Description Virtual method. Run before each test is executed ### Method **before_each**() ``` -------------------------------- ### should_skip_script Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Virtual Method. This is run after the script has been prepped for execution, but before before_all is executed. If you implement this method and return true or a String (the string is displayed in the log) then GUT will stop executing the script and mark it as risky. ```APIDOC ## should_skip_script ### Description Virtual Method. This is run after the script has been prepped for execution, but before before_all is executed. If you implement this method and return true or a String (the string is displayed in the log) then GUT will stop executing the script and mark it as risky. ### Method Variant **should_skip_script**() ### Example ```default func should_skip_script(): if DisplayServer.get_name() == "headless": return "Skip Input tests when running headless" ``` ### Example ```default func should_skip_script(): return EngineDebugger.is_active() ``` ``` -------------------------------- ### Wait Seconds with Await Source: https://github.com/bitwes/gut/blob/main/documentation/docs/class_ref/class_guttest.md Use with await to pause execution for a specified duration in seconds. An optional message can be provided to be printed when the await starts. ```gdscript func test_wait_seconds(): await wait_seconds(1.0, "Waiting for 1 second") ``` -------------------------------- ### Sample Version Data JSON Source: https://github.com/bitwes/gut/blob/main/documentation/internal/check_for_update.md This JSON structure represents the version data file used for checking updates. It includes information about asset library versions, available branches, and release compatibility with Godot versions. The `fetch_timestamp` field is added upon download. ```json { # The version in the Asset Library "asset_library": "9.6.0", # Branches that are available to be used. Used to provide info for # experimental/new versions of GUT that have not been released yet. "branches": { "main": { "godot_max": "9999", "godot_min": "4.6" } }, # This is added when the file is downloaded so we know when it was last # updated. Getting the timestamp for the file looked non-trival in Godot. # This does not exist in the local file. "fetch_timestamp": 1772560259.54128, # The GUT releases and the min/max versions of Godot they support. "releases": { "9.3.0": { "godot_max": "4.2.999", "godot_min": "4.2" }, "9.4.0": { "godot_max": "4.4.999", "godot_min": "4.3" }, "9.5.0": { "godot_max": "4.5.999", "godot_min": "4.5" }, "9.6.0": { "godot_max": "999", "godot_min": "4.6" } } } ``` -------------------------------- ### Godot 4 Property Accessor Syntax Source: https://github.com/bitwes/gut/blob/main/documentation/docs/New-For-Godot-4.md Use `get():` and `set(val):` for property accessors in Godot 4. This replaces the older `setget` keyword. ```gdscript var foo = 10: get(): return foo set(val): foo = val ``` -------------------------------- ### Run Gut Output Tests Source: https://github.com/bitwes/gut/blob/main/test/output_tests/readme.md Execute output tests using the Gut tool. Specify the configuration and directory for tests. ```bash gut -gconfig= -gdir test/output_tests ``` -------------------------------- ### Get Test Summary Totals Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Hooks.md Retrieves the total counts for pending, failing, tests, and scripts. This is useful for a quick overview of test execution status. ```gdscript gut.get_summary().get_totals() ``` -------------------------------- ### Stubbing Script-Level vs. Instance-Level Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Stubbing.md Illustrates how to stub methods at the script level (affecting all instances) versus the instance level (affecting only a specific instance). ```gdscript var DoubleThis = load('res://scripts/double_this.gd') var Doubled = double(DoubleThis) var inst = Doubled.new() # These two are equivalent, and stub returns_seven for any doubles of # DoubleThis to return 500. stub('res://scripts/double_this.gd', 'returns_seven').to_return(500) # or stub(DoubleThis, 'returns_seven').to_return(500) assert_eq(inst.returns_seven(), 500) # This will stub returns_seven on the passed in instance ONLY. # Any other instances will return 500 from the lines above. var stub_again = Doubled.new() stub(stub_again, 'returns_seven').to_return('words') assert_eq(stub_again.returns_seven(), 'words') assert_eq(inst.returns_seven, 500) ``` -------------------------------- ### Get Full Summary Object Source: https://github.com/bitwes/gut/blob/main/documentation/docs/Hooks.md Retrieves the GUT's summary object, which contains all data about the test run. This is useful for post-run analysis or reporting. ```gdscript # Returns GUT's summary.gd instance holding all the data about the run. gut.get_summary() ```