extends SceneTree ## Smoke test for the ScriptBehavior DSL + ScriptInterpreterNode. ## ## Run with: ## godot --headless --path . --script res://scripts/smoke_test_script_behavior.gd ## ## Covers, in order: ## 1. Parsing/validation: a well-formed behavior parses cleanly; malformed ## or unsafe rules (unknown verb, unknown trigger, non-scalar ## arguments meant to smuggle something unsafe, unknown condition ## type/op) are rejected at parse time and never make it into ## `rules` -- never partially applied. ## 2. A behavior mixing one bad rule with one good rule in the same file: ## the good rule still parses and still executes; the bad rule is ## dropped, not silently run. ## 3. The real demo wired into scenes/worlds/test_level.tscn ## ("ScriptedChest"): loading scenes/game.tscn actually gets a ## ScriptInterpreterNode with the demo behavior loaded, a Player with ## a real Inventory, and pressing the real "interact" action while in ## range actually runs give_item / play_sound / rotate -- proven by ## observing the Inventory's item count change and the interpreter's ## verb_executed signal, not by calling private methods directly. const ScriptBehaviorClass := preload("res://scripts/scripting/script_behavior.gd") const ScriptInterpreterNodeClass := preload("res://scripts/scripting/script_interpreter.gd") const PlayerInventoryClass := preload("res://scripts/scripting/player_inventory.gd") const DynamicObjectNodeClass := preload("res://scripts/dynamic_object_node.gd") var passed := 0 var failed := 0 func _initialize() -> void: _run() func _run() -> void: await process_frame _test_valid_behavior_parses() _test_malformed_rules_are_rejected() _test_mixed_good_and_bad_rules() await _test_on_timer_trigger() _test_condition_gating() await _test_remaining_verbs() await _test_wired_demo_in_game_scene() print("\n=== SMOKE RESULT: %d/%d passed ===" % [passed, passed + failed]) quit(0 if failed == 0 else 1) # --------------------------------------------------------------------------- # 1. A well-formed behavior parses cleanly. # --------------------------------------------------------------------------- func _test_valid_behavior_parses() -> void: print("--- valid behavior parses cleanly ---") var data := { "rules": [ { "trigger": {"type": "on_interact"}, "conditions": [], "actions": [ {"verb": "give_item", "item_id": "gold_coin", "count": 3}, {"verb": "play_sound", "sound_id": "chime"}, ], } ] } var behavior: ScriptBehaviorClass = ScriptBehaviorClass.load_from_dict(data) _check("valid behavior has exactly one rule", behavior.rules.size() == 1) _check("valid behavior has no rejected rules", behavior.rejected_rules.is_empty()) # --------------------------------------------------------------------------- # 2. Malformed / unsafe rules never make it into `rules`. # --------------------------------------------------------------------------- func _test_malformed_rules_are_rejected() -> void: print("--- malformed/unsafe rules are safely rejected, not executed ---") # Unknown verb -- e.g. an attempt to invoke something outside the # whitelist entirely. _expect_rejected("unknown verb", { "rules": [{ "trigger": {"type": "on_interact"}, "conditions": [], "actions": [{"verb": "os_execute", "command": "rm -rf /"}], }] }) # Unknown trigger type. _expect_rejected("unknown trigger type", { "rules": [{ "trigger": {"type": "on_explode"}, "conditions": [], "actions": [{"verb": "give_item", "item_id": "x", "count": 1}], }] }) # on_timer with a missing/invalid interval. _expect_rejected("on_timer missing interval", { "rules": [{ "trigger": {"type": "on_timer"}, "conditions": [], "actions": [{"verb": "give_item", "item_id": "x", "count": 1}], }] }) # Attempt to smuggle a non-scalar (a nested object, the shape an # engine-reaching payload would need) as an item_id. _expect_rejected("non-scalar item_id", { "rules": [{ "trigger": {"type": "on_interact"}, "conditions": [], "actions": [{"verb": "give_item", "item_id": {"call": "OS.execute"}, "count": 1}], }] }) # Negative/absurd count. _expect_rejected("out-of-range count", { "rules": [{ "trigger": {"type": "on_interact"}, "conditions": [], "actions": [{"verb": "give_item", "item_id": "x", "count": -5}], }] }) # Invalid target (not "self"/"player"). _expect_rejected("invalid move target", { "rules": [{ "trigger": {"type": "on_interact"}, "conditions": [], "actions": [{"verb": "move", "target": "world_root", "offset": [0, 1, 0]}], }] }) # Unknown condition type/op. _expect_rejected("unknown condition type", { "rules": [{ "trigger": {"type": "on_interact"}, "conditions": [{"type": "player_health", "op": "==", "value": 100}], "actions": [{"verb": "give_item", "item_id": "x", "count": 1}], }] }) _expect_rejected("unknown condition op", { "rules": [{ "trigger": {"type": "on_interact"}, "conditions": [{"type": "item_count", "item_id": "x", "op": "~=", "value": 1}], "actions": [{"verb": "give_item", "item_id": "x", "count": 1}], }] }) # Missing actions entirely. _expect_rejected("empty actions array", { "rules": [{"trigger": {"type": "on_interact"}, "conditions": [], "actions": []}] }) # No "rules" key at all. _expect_rejected("missing top-level rules key", {"not_rules": []}) func _expect_rejected(label: String, data: Dictionary) -> void: var behavior: ScriptBehaviorClass = ScriptBehaviorClass.load_from_dict(data) _check("%s -> zero rules parsed" % label, behavior.rules.is_empty()) _check("%s -> rejection reason recorded" % label, not behavior.rejected_rules.is_empty()) # --------------------------------------------------------------------------- # 2b. A bad rule alongside a good rule in the SAME behavior: the good one # still parses and still runs; the bad one is dropped, not run "best # effort" and not blocking the good rule either. # --------------------------------------------------------------------------- func _test_mixed_good_and_bad_rules() -> void: print("--- one bad rule does not block or corrupt a sibling good rule ---") var data := { "rules": [ { # Bad: unknown verb, should be dropped silently. "trigger": {"type": "on_interact"}, "conditions": [], "actions": [{"verb": "eval", "code": "OS.execute('id', [])"}], }, { # Good: should parse and, when fired, actually run. "trigger": {"type": "on_interact"}, "conditions": [], "actions": [{"verb": "give_item", "item_id": "mixed_test_item", "count": 2}], }, ] } var behavior: ScriptBehaviorClass = ScriptBehaviorClass.load_from_dict(data) _check("mixed behavior kept only the good rule", behavior.rules.size() == 1) _check("mixed behavior recorded the bad rule's rejection", not behavior.rejected_rules.is_empty()) var interpreter := ScriptInterpreterNodeClass.new() interpreter.set_behavior(behavior) root.add_child(interpreter) var fake_player := Node3D.new() fake_player.name = "FakePlayer" var inv := PlayerInventoryClass.new() inv.name = "Inventory" fake_player.add_child(inv) root.add_child(fake_player) interpreter.fire("on_interact", fake_player) _check("the surviving good rule actually executed", inv.get_count("mixed_test_item") == 2) interpreter.queue_free() fake_player.queue_free() # --------------------------------------------------------------------------- # 3b. on_timer actually fires on its own, with no player/interact/touch # involved at all -- driven purely by a real Timer node ticking down. # --------------------------------------------------------------------------- func _test_on_timer_trigger() -> void: print("--- on_timer fires repeatedly on its own ---") var data := { "rules": [{ "trigger": {"type": "on_timer", "interval": 0.05}, "conditions": [], "actions": [{"verb": "set_timer", "name": "ticked", "seconds": 60}], }] } var behavior: ScriptBehaviorClass = ScriptBehaviorClass.load_from_dict(data) _check("on_timer behavior parsed", behavior.rules.size() == 1) var interpreter := ScriptInterpreterNodeClass.new() interpreter.set_behavior(behavior) root.add_child(interpreter) # A plain int captured by a lambda is captured by value in GDScript # closures (the outer variable never sees the mutation) -- an Array's # *reference* is what gets captured, so appends are visible outside. var fire_log: Array = [] interpreter.verb_executed.connect(func(_verb, _args): fire_log.append(true)) for i in 30: await physics_frame _check("on_timer fired at least once with no trigger source but time", fire_log.size() >= 1) interpreter.queue_free() # --------------------------------------------------------------------------- # 4. Conditions actually gate execution (not just parse). # --------------------------------------------------------------------------- func _test_condition_gating() -> void: print("--- conditions gate whether an action runs ---") var data := { "rules": [{ "trigger": {"type": "on_interact"}, "conditions": [{"type": "item_count", "item_id": "key", "op": ">=", "value": 1}], "actions": [{"verb": "give_item", "item_id": "treasure", "count": 1}], }] } var behavior: ScriptBehaviorClass = ScriptBehaviorClass.load_from_dict(data) _check("conditioned behavior parsed", behavior.rules.size() == 1) var interpreter := ScriptInterpreterNodeClass.new() interpreter.set_behavior(behavior) root.add_child(interpreter) var fake_player := Node3D.new() var inv := PlayerInventoryClass.new() inv.name = "Inventory" fake_player.add_child(inv) root.add_child(fake_player) interpreter.fire("on_interact", fake_player) _check("condition not met -> action did not run", inv.get_count("treasure") == 0) inv.give_item("key", 1) interpreter.fire("on_interact", fake_player) _check("condition met -> action ran", inv.get_count("treasure") == 1) interpreter.queue_free() fake_player.queue_free() # --------------------------------------------------------------------------- # 2c. The remaining three verbs (move, spawn_from_catalog, set_timer) plus # the timer_active condition -- not exercised by the wired chest demo # (which only needs give_item/play_sound/rotate), so each gets a direct # check here that it actually does something real. # --------------------------------------------------------------------------- func _test_remaining_verbs() -> void: print("--- move / spawn_from_catalog / set_timer + timer_active condition ---") var data := { "rules": [ { # Only grants the item while the "cooldown" timer is NOT # active -- proves timer_active is actually read back. "trigger": {"type": "on_interact"}, "conditions": [{"type": "timer_active", "name": "cooldown", "op": "==", "value": false}], "actions": [{"verb": "give_item", "item_id": "cooldown_test_item", "count": 1}], }, { "trigger": {"type": "on_interact"}, "conditions": [], "actions": [ {"verb": "set_timer", "name": "cooldown", "seconds": 10}, {"verb": "move", "target": "self", "offset": [0, 0, -2], "duration": 0.2}, {"verb": "spawn_from_catalog", "catalog_id": "small_crate", "position": [5, 0, 5]}, ], }, ] } var behavior: ScriptBehaviorClass = ScriptBehaviorClass.load_from_dict(data) _check("remaining-verbs behavior parsed with no rejections", behavior.rejected_rules.is_empty()) var interpreter := ScriptInterpreterNodeClass.new() interpreter.set_behavior(behavior) root.add_child(interpreter) var start_position: Vector3 = interpreter.position var fake_player := Node3D.new() var inv := PlayerInventoryClass.new() inv.name = "Inventory" fake_player.add_child(inv) root.add_child(fake_player) # First trigger: cooldown isn't active yet -> item granted, then the # second rule starts the cooldown timer and moves/spawns. interpreter.fire("on_interact", fake_player) _check("give_item ran while timer_active was false", inv.get_count("cooldown_test_item") == 1) # Second trigger, same frame: set_timer's effect must already be # visible to a condition evaluated afterward -- this is the whole # point of the timer_active/timer_remaining state store existing. interpreter.fire("on_interact", fake_player) _check("give_item did NOT run again once the cooldown timer was active", inv.get_count("cooldown_test_item") == 1) # move() animates over a real Tween, not a teleport -- wait it out. for i in 20: await physics_frame var moved: Vector3 = interpreter.position _check("move actually relocated the object (not instantly, via a Tween)", moved.distance_to(start_position + Vector3(0, 0, -2)) < 0.05) # spawn_from_catalog should have added a real DynamicObjectNode sibling. var spawned: Node = null for child in root.get_children(): if child is DynamicObjectNodeClass and (child as Node).name.begins_with("spawned_"): spawned = child _check("spawn_from_catalog actually added a DynamicObjectNode to the tree", spawned != null) if spawned != null: var dyn := spawned as DynamicObjectNodeClass _check("spawned object resolved asset_id via the trusted catalog (not the raw data)", dyn.world_object != null and dyn.world_object.asset_id == "props/crate_small.glb") _check("spawned object placed at the requested position", dyn.position.distance_to(Vector3(5, 0, 5)) < 0.01) spawned.queue_free() interpreter.queue_free() fake_player.queue_free() # --------------------------------------------------------------------------- # 3. The real demo wired into the actual playable scene. # --------------------------------------------------------------------------- func _test_wired_demo_in_game_scene() -> void: print("--- real demo: ScriptedChest in scenes/worlds/test_level.tscn via scenes/game.tscn ---") var packed: PackedScene = load("res://scenes/game.tscn") var result := change_scene_to_packed(packed) if not _check("game scene loaded", result == OK): return await scene_changed var game: Node3D = current_scene as Node3D var player: Node = game.get_node_or_null("Player") if not _check("Player exists in loaded scene", player is CharacterBody3D): return var inventory: Node = player.get_node_or_null("Inventory") if not _check("Player has a real Inventory node", inventory is PlayerInventoryClass): return var chest: Node = game.get_node_or_null("Level/ScriptedChest") if not _check("ScriptedChest exists in the level", chest != null): return if not _check("ScriptedChest has the ScriptInterpreterNode script", chest is ScriptInterpreterNodeClass): return var interpreter: ScriptInterpreterNodeClass = chest as ScriptInterpreterNodeClass # Let _ready() load the behavior and build its Area3D/timers. await process_frame _check("ScriptedChest's behavior loaded from disk", interpreter.behavior != null) if interpreter.behavior != null: _check("demo_chest.json parsed with no rejected rules", interpreter.behavior.rejected_rules.is_empty()) var executed_verbs: Array[String] = [] interpreter.verb_executed.connect(func(verb, _args): executed_verbs.append(verb)) # Let physics settle: the player falls onto the ground and the # ScriptedChest's trigger Area3D needs a few physics frames to notice # the overlap before the interact key check has anyone "in range". for i in 60: await physics_frame var before_count: int = (inventory as PlayerInventoryClass).get_count("gold_coin") var before_rot_y: float = interpreter.rotation_degrees.y # A real input event, exactly like a player pressing E -- not a direct # call into the interpreter's action methods. var interact_event := InputEventKey.new() interact_event.keycode = KEY_E interact_event.physical_keycode = KEY_E interact_event.pressed = true Input.parse_input_event(interact_event) for i in 10: await process_frame var after_count: int = (inventory as PlayerInventoryClass).get_count("gold_coin") _check("pressing 'interact' near the chest granted gold_coin via give_item", after_count == before_count + 3) _check("give_item actually executed (verb_executed signal)", executed_verbs.has("give_item")) _check("play_sound actually executed (verb_executed signal)", executed_verbs.has("play_sound")) _check("rotate actually executed (verb_executed signal)", executed_verbs.has("rotate")) # rotate animates over 0.4s via a real Tween -- wait it out, then check # the chest's rotation actually changed (not teleported instantly, but # not stuck at the start either). for i in 40: await physics_frame var after_rot_y: float = interpreter.rotation_degrees.y _check("rotate actually moved the chest's rotation", absf(wrapf(after_rot_y - before_rot_y - 90.0, -180.0, 180.0)) < 1.0) # Pressing interact again with the player out of a fresh area-entry # state should still work (rule has no conditions/limits) -- give_item # is cumulative, proving repeated real triggers keep working. var interact_event2 := InputEventKey.new() interact_event2.keycode = KEY_E interact_event2.physical_keycode = KEY_E interact_event2.pressed = true Input.parse_input_event(interact_event2) for i in 10: await process_frame var final_count: int = (inventory as PlayerInventoryClass).get_count("gold_coin") _check("a second real interact press granted gold_coin again", final_count == after_count + 3) # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- func _check(description: String, condition: bool) -> bool: if condition: print(" PASS: ", description) passed += 1 else: printerr(" FAIL: ", description) failed += 1 return condition