Testing and simulation

How to check that a behavior tree decides what you meant before it reaches a game: full evaluation and step-through, forcing what each leaf returns, deterministic ticks, and golden traces that catch a change in behavior.

A gate guard should challenge a stranger, let them through when they give the password and raise the alarm when they do not. Imagine a change that swaps two children in the wrong place: the guard now raises the alarm for every friend who answers correctly. Nothing crashes and nothing logs an error. The tree still validates. You find out when a player reports it, or never.

A behavior tree is a program that makes decisions, and like any program it needs tests. The useful question is not “does this tree run?” but “given these facts about the world, which leaves run, and what does the tree return?” This page answers that question four ways: by simulating the tree on its own, by forcing what each leaf returns, by making every run repeatable, and by keeping a recorded run to compare against after each change.

Full evaluation versus step-through

A simulation runs a tree outside the game: no level, no characters, no physics. Each leaf (an action or a condition, from Building blocks) does no real work; it just returns a status that you choose or that the simulator picks for you. What you see is the decision the tree makes: the order its nodes are ticked in and what each one returns. That ordered list is called the trace.

There are two ways to run a simulation:

  • A full evaluation runs the whole traversal at once. You set the status of each leaf before the run starts (or accept a default), and you get the full trace back. It is fast and you can repeat it, so it suits tests.
  • A step-through pauses at each leaf and asks you for its status (Success, Failure or Running); the sequences and selectors above it work out their own results from your answers. It suits exploring: “and if the stranger says nothing, what then?”

Explore with step-through until you understand a behavior, then turn what you learned into full evaluations you can run again.

Forcing what a leaf returns

In a test, you replace each leaf’s real work with a fixed answer. You force stranger_at_gate to return Success instead of checking a trigger volume, and gave_password to return Failure instead of running dialogue. This is the same idea as a stub or mock in unit testing. It lets you test the tree’s logic on its own: if the alarm fires, the tree decided to fire it, and not a physics glitch or a timing problem.

This works because a tree only sees what its leaves return. A condition that returns Failure looks the same to its parent whether no stranger is there or the sensor is broken. So one forced status per leaf describes a whole situation, and a handful of situations covers the decisions a tree makes.

Deterministic ticks

A test that passes on one run and fails on the next teaches nothing. A tree run is deterministic when the same tree, given the same leaf answers, always produces the same trace. Three things in a game break this, and a test must control each one:

  1. Time. A cooldown or timeout that reads the real clock behaves differently on a slow machine. Give the node a clock the test controls, and move it forward by a fixed step on each tick.
  2. Chance. A node that picks a child at random, or a 30% chance to dodge, must use a random generator the test seeds, so the “random” choices are the same on every run.
  3. The tick itself. In the game, the engine ticks the tree once a frame. In a test, the test calls tick() itself, a fixed number of times, so tick 3 is always tick 3.

BeeTreeCraft’s simulator has no clock and no randomness, so the same tree with the same overrides always prints the same trace.

A tree you can run

version: "1.0"
metadata:
  name: gate-guard
  description: "Challenges anyone at the gate, raises the alarm when they do not answer, and patrols otherwise"
  tags: [testing, simulation]
tree:
  type: selector
  name: guard_root
  children:
    - type: sequence
      name: challenge_stranger
      children:
        - {type: condition, name: stranger_at_gate, node: StrangerAtGate}
        - type: selector
          name: answer_or_alarm
          children:
            - {type: condition, name: gave_password, node: GavePassword}
            - {type: action, name: raise_alarm, node: RaiseAlarm}
    - {type: action, name: patrol, node: Patrol}

Save it as gate-guard.beetree.yaml. beetree simulate runs a full evaluation in which every leaf succeeds unless --override forces a different answer. Each command below tests one situation:

beetree simulate gate-guard.beetree.yaml --override gave_password=SUCCESS
beetree simulate gate-guard.beetree.yaml --override gave_password=FAILURE
beetree simulate gate-guard.beetree.yaml --override stranger_at_gate=FAILURE --override patrol=RUNNING
  1. A friend at the gate. gave_password succeeds, so answer_or_alarm succeeds without ticking raise_alarm, and patrol is never reached. The trace has no alarm in it.
  2. A stranger without the password. gave_password fails, so the selector tries its next child, raise_alarm. The trace shows gave_password → FAILURE and then raise_alarm → SUCCESS.
  3. Nobody at the gate. stranger_at_gate fails, so the whole challenge fails and the root selector moves on to patrol, which is still walking its route (Running). The tree returns Running.

To explore instead, run beetree simulate gate-guard.beetree.yaml --step, which pauses at each leaf and waits for you to type s, f or r. In the web builder, paste the tree and open the Debug tab: Step through asks you for each leaf, and Run all answers every leaf with the rule you pick (every leaf succeeds, fails, is running, or the answers take turns).

Golden traces catch a change in behavior

A golden trace is a trace you have checked by hand and saved as the correct answer. After every change to the tree, you run the same situations again and compare. If the new trace differs from the saved one, either the behavior changed on purpose (read the difference and save the new trace) or you broke something (fix the tree). This is regression testing applied to behavior: the trace records what the tree decides, so a change in decisions shows up as a change in the text.

Because the simulator is deterministic, a golden trace is just a text file:

beetree simulate gate-guard.beetree.yaml --override gave_password=FAILURE > stranger-without-password.trace
# ... later, after editing the tree:
beetree simulate gate-guard.beetree.yaml --override gave_password=FAILURE | diff stranger-without-password.trace -

The trace goes to standard output and the “Next:” hint after it to standard error, so the saved file holds the trace alone. diff prints nothing and exits with 0 when the behavior is unchanged. Suppose someone swaps the two children of answer_or_alarm. The tree still validates, but the diff now shows raise_alarm → SUCCESS where gave_password → SUCCESS used to be: the guard no longer asks for the password and raises the alarm for every friend. Save one trace per situation, commit them next to the tree, and run the diffs in your pre-commit hook or CI.

A test also needs to fail when a node is renamed, rather than silently testing nothing. --override refuses a name that is not in the tree and lists the names that are, so a renamed leaf makes the test fail with a clear message instead of passing.

What the simulator shows today

  • beetree simulate runs one tick. A test that needs patrol to run for two ticks and then succeed is played as separate commands, one per tick, as on the Concurrency page. Running a tree for several ticks, with a list of statuses per leaf, is planned but not available yet.
  • The command exits with 0 whatever the root returns. Check the behavior by comparing the trace, as above, not by the exit code.
  • The trace is plain text for people to read. Its exact format may change between releases, so save new golden traces when you upgrade the CLI and read the difference once.

Engine code

In the game, the same idea becomes a unit test in the engine’s test framework. Three small pieces make a tree testable. A ScriptedLeaf stands in for a real leaf and returns the statuses you give it, one per tick, so you can say “Running, Running, then Success”. A Traced decorator wraps any node and writes what it returned to the trace. A comparison finds the first line where a run’s trace differs from the golden trace. Each sample builds on the Status type and tick() contract from Building blocks.

Agnostic

ScriptedLeaf(name, answers, trace):     // answers: one status per tick
    calls = 0
    tick():
        status = answers[min(calls, len(answers) - 1)]   // the last answer repeats
        calls += 1
        trace.append(name + " " + status)
        return status

Traced(name, child, trace):             // wraps any node, composites included
    tick():
        status = child.tick()
        trace.append(name + " " + status)
        return status

firstDifference(actual, golden):        // -1 when the run matches the golden trace
    for i in 0 .. max(len(actual), len(golden)) - 1:
        if i >= len(actual) or i >= len(golden) or actual[i] != golden[i]: return i
    return -1

Unity C#

public class ScriptedLeaf : Node
{
    readonly string name;
    readonly Status[] answers; // one per tick; the last one repeats
    readonly System.Collections.Generic.List<string> trace;
    int calls;

    public ScriptedLeaf(string name, System.Collections.Generic.List<string> trace, params Status[] answers)
    {
        this.name = name;
        this.trace = trace;
        this.answers = answers;
    }

    public override Status Tick()
    {
        var status = answers[System.Math.Min(calls, answers.Length - 1)];
        calls++;
        trace.Add(name + " " + status);
        return status;
    }
}

public class Traced : Node
{
    readonly string name;
    readonly Node child;
    readonly System.Collections.Generic.List<string> trace;

    public Traced(string name, Node child, System.Collections.Generic.List<string> trace)
    {
        this.name = name;
        this.child = child;
        this.trace = trace;
    }

    public override Status Tick()
    {
        var status = child.Tick();
        trace.Add(name + " " + status);
        return status;
    }
}

public static class GoldenTrace
{
    // The first line where the run differs from the golden trace, or -1 when they match.
    public static int FirstDifference(System.Collections.Generic.List<string> actual, string[] golden)
    {
        int lines = System.Math.Max(actual.Count, golden.Length);
        for (int i = 0; i < lines; i++)
            if (i >= actual.Count || i >= golden.Length || actual[i] != golden[i]) return i;
        return -1;
    }
}

GDScript

class ScriptedLeaf extends BTNode:
    var leaf_name: String
    var answers: Array[Status]   # one per tick; the last one repeats
    var trace: Array[String]
    var calls := 0

    func _init(n: String, a: Array[Status], t: Array[String]):
        leaf_name = n
        answers = a
        trace = t

    func tick() -> Status:
        var status: Status = answers[mini(calls, answers.size() - 1)]
        calls += 1
        trace.append("%s %s" % [leaf_name, Status.keys()[status]])
        return status

class Traced extends BTNode:
    var node_name: String
    var child: BTNode
    var trace: Array[String]

    func _init(n: String, c: BTNode, t: Array[String]):
        node_name = n
        child = c
        trace = t

    func tick() -> Status:
        var status := child.tick()
        trace.append("%s %s" % [node_name, Status.keys()[status]])
        return status

# The first line where the run differs from the golden trace, or -1 when they match.
static func first_difference(actual: Array[String], golden: Array[String]) -> int:
    for i in maxi(actual.size(), golden.size()):
        if i >= actual.size() or i >= golden.size() or actual[i] != golden[i]:
            return i
    return -1

Unreal C++

struct FTraceLine
{
    FString Node;
    EStatus Status = EStatus::Failure;
    bool operator==(const FTraceLine& Other) const { return Node == Other.Node && Status == Other.Status; }
};

class FScriptedLeaf : public FNode
{
public:
    FString Name;
    TArray<EStatus> Answers; // one per tick; the last one repeats
    TArray<FTraceLine>* Trace = nullptr;
    int32 Calls = 0;

    EStatus Tick() override
    {
        const int32 Index = Calls < Answers.Num() ? Calls : Answers.Num() - 1;
        const EStatus Status = Answers[Index];
        ++Calls;
        Trace->Add(FTraceLine{Name, Status});
        return Status;
    }
};

class FTraced : public FNode
{
public:
    FString Name;
    TSharedPtr<FNode> Child;
    TArray<FTraceLine>* Trace = nullptr;

    EStatus Tick() override
    {
        const EStatus Status = Child->Tick();
        Trace->Add(FTraceLine{Name, Status});
        return Status;
    }
};

// The first line where the run differs from the golden trace, or -1 when they match.
inline int32 FirstDifference(const TArray<FTraceLine>& Actual, const TArray<FTraceLine>& Golden)
{
    const int32 Lines = Actual.Num() > Golden.Num() ? Actual.Num() : Golden.Num();
    for (int32 i = 0; i < Lines; ++i)
    {
        if (i >= Actual.Num() || i >= Golden.Num() || !(Actual[i] == Golden[i])) return i;
    }
    return -1;
}

A test builds the guard from these pieces: a ScriptedLeaf for each of the four leaves, the composites from Building blocks, and a Traced around each composite. It ticks the root the number of times the situation needs and compares the trace with the golden one. Each engine runs these as ordinary unit tests: Unity’s Test Framework (NUnit) in edit mode, Unreal’s Automation tests, and a GDScript test addon such as GUT or GdUnit4 in Godot. None of them needs a scene, so they run in seconds on every commit.

Where it comes from

py_trees ships a StatusQueue behaviour that returns a scripted list of statuses, the same idea as ScriptedLeaf. BehaviorTree.CPP’s substitution rules replace real nodes with a built-in TestNode that returns a status you configure, so you can test a tree without the robot. Colledanchise and Natale compare how libraries run, log and halt trees in On the Implementation of Behavior Trees in Robotics (2021). More reading is on the Resources page.

Next, save a golden trace for each situation of a tree of your own, or open the Build hub, paste the gate guard into the builder and use Step through in the Debug tab to try a situation this page did not cover.