> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lokutor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Testing without the API

> Run a character's whole conversation in your tests with no key, no network, no microphone and no sound card: the mock server of the Godot and Unity SDKs, with a complete test for each

A talking character is ordinary code around a WebSocket, and can be tested like ordinary code. Both game SDKs come with a **mock server** that speaks the [agent protocol](https://docs.lokutor.com/guides/websocket-protocol.md) inside the test's own process: your test plays the part of Lokutor, says what the player said and what the character answers, and checks what your game did. It costs nothing and runs in CI.

| | Godot | Unity |
| :- | :- | :- |
| The server | [`tests/mock_server.gd`](https://github.com/lokutor-ai/lokutor-sdk/blob/main/godot/tests/mock_server.gd) (`LokutorMockServer`) | [`Tests~/CoreTests/MockServer.cs`](https://github.com/lokutor-ai/lokutor-sdk/blob/main/unity/Tests~/CoreTests/MockServer.cs) (`MockServer`) |
| Use it | Copy the file into your project | Copy the file into your test project |
| What the client sent | `session.text`, `last(type)`, `types()`, `audio` | `Text`, `Last(type)`, `Types()`, `Audio` |
| Say something | `send(message)`, `send_audio(pcm, generation)` | `Send(json)`, `Audio16(pcm, generation)` |
| Break things | `session.drop()`, `server.refuse = true` | `session.Drop()`, `server.Refuse = true` |
| REST answers | `http_status`, `http_body`, `http_requests` | `HttpStatus`, `HttpBody`, `HttpRequests` |

## What to point at it

| | Godot | Unity |
| :- | :- | :- |
| A conversation | `LokutorAgent.url` | `LokutorAgent.url`, or `SessionOptions.Url` without a scene |
| Written lines | `LokutorVoice.url` | `LokutorVoice.url` |
| The clients | `server_url` | `ServerUrl` |

Any non-empty string is a valid key for it. On a machine with no sound card set `simulate_audio_device = true` on a Godot LokutorAgent: the voice is consumed in real time without being played, so states and lip sync run as they would in the game. In Unity, test the conversation through `LokutorSession`, which is LokutorAgent without the engine, and read its `Playback` as a sound card would. Turn the microphone off, and give the character a voice to hear with `feed_microphone` / `FeedMicrophone` (`SendMicrophone` on the session) if the test is about that.

## A test

A player buys a sword: the agent is told about the action, the action runs, the character is told what happened, and it answers.

> [tab] Godot
>
> ```gdscript theme={null}
> extends SceneTree
> ## godot --headless --path . --script res://tests/shop_test.gd
>
> var server := LokutorMockServer.new()
> var sold: Array = []
> var failed := false
>
> func _initialize() -> void:
>     _run()
>
> func _run() -> void:
>     await process_frame
>     root.add_child(server)
>     server.start()
>
>     var agent := LokutorAgent.new()
>     agent.api_key = "test"
>     agent.url = server.url("/ws/agent")
>     agent.mic_mode = LokutorAgent.MicMode.OFF
>     agent.simulate_audio_device = true                # no sound card
>     agent.start_on_ready = false
>     agent.add_action("give_item", "Sell an item", _give_item, {"item": "Which item"})
>     root.add_child(agent)
>
>     # The agent connects and says who it is; `rates` is the last thing it sends.
>     agent.start_conversation()
>     while server.current() == null or server.current().last("rates") == null:
>         await process_frame
>     var lokutor := server.current()
>     check(lokutor.last("tools").data[0].function.name == "give_item", "the agent knows the action")
>     lokutor.send({"type": "status", "data": "connected", "session_id": "test"})
>
>     # The player asks for a sword, and the character calls the action.
>     lokutor.send({"type": "transcript", "role": "user", "data": "A sword, please."})
>     lokutor.send({"type": "status", "data": "thinking", "generation": 1})
>     lokutor.send({"type": "tool_call", "name": "give_item", "arguments": '{"item": "sword"}', "call_id": "1"})
>     while lokutor.last("tool_result") == null:
>         await process_frame
>     check(sold == ["sword"], "the game sold it")
>     check(lokutor.last("tool_result").data.result == "Gave the sword.", "and the character was told")
>
>     # It answers: text, mouth shapes, and half a second of voice.
>     var voice := PackedByteArray()
>     voice.resize(Lokutor.OUTPUT_RATE)                 # 16-bit samples: half a second of silence
>     lokutor.send({"type": "transcript", "role": "agent", "data": "There you go."})
>     lokutor.send({"type": "status", "data": "speaking", "generation": 1})
>     lokutor.send({"type": "visemes", "generation": 1, "data": [{"v": 10, "c": "aa", "t": 0.0, "d": 0.5}]})
>     lokutor.send_audio(voice, 1)
>     while agent.state != LokutorAgent.State.SPEAKING:
>         await process_frame
>     while agent.state != LokutorAgent.State.READY:
>         await process_frame
>     print("failed" if failed else "passed")
>     quit(1 if failed else 0)
>
> func check(ok: bool, what: String) -> void:
>     if not ok:
>         failed = true
>         printerr("FAILED: ", what)
>
> func _give_item(args: Dictionary) -> String:
>     sold.append(args.item)
>     return "Gave the %s." % args.item
> ```
>
> ```bash theme={null}
> godot --headless --path . --import
> godot --headless --path . --script res://tests/shop_test.gd
> ```

> [tab] Unity (plain C#)
>
> ```csharp theme={null}
> using System;
> using System.Collections.Generic;
> using System.Threading.Tasks;
> using Lokutor;
>
> static class ShopTest
> {
>     static async Task<int> Main()
>     {
>         using (var server = new MockServer())
>         {
>             var sold = new List<string>();
>             var shopkeeper = new LokutorSession(new SessionOptions { ApiKey = "test", Url = server.Url("/ws/agent"), Persona = "You run a shop." });
>             shopkeeper.AddAction("give_item", "Sell an item", args =>
>             {
>                 sold.Add(args.GetString("item"));
>                 return "Gave the " + args.GetString("item") + ".";
>             }, new ActionParam("item", "Which item"));
>
>             // The agent connects and says who it is; `rates` is the last thing it sends.
>             await shopkeeper.ConnectAsync();
>             await Until(shopkeeper, () => server.Current?.Last("rates") != null);
>             var lokutor = server.Current;
>             lokutor.Send("{\"type\":\"status\",\"data\":\"connected\",\"session_id\":\"test\"}");
>
>             // The player asks for a sword, and the character calls the action.
>             lokutor.Send("{\"type\":\"transcript\",\"role\":\"user\",\"data\":\"A sword, please.\"}");
>             lokutor.Send("{\"type\":\"status\",\"data\":\"thinking\",\"generation\":1}");
>             lokutor.Send("{\"type\":\"tool_call\",\"name\":\"give_item\",\"arguments\":\"{\\\"item\\\":\\\"sword\\\"}\",\"call_id\":\"1\"}");
>             await Until(shopkeeper, () => lokutor.Last("tool_result") != null);
>             if (sold.Count != 1 || sold[0] != "sword") return Fail("the game sold it");
>             string told = (string)((Dictionary<string, object>)lokutor.Data("tool_result"))["result"];
>             if (told != "Gave the sword.") return Fail("and the character was told");
>
>             // It answers: text, and half a second of voice, played at the speed of a sound card.
>             lokutor.Send("{\"type\":\"transcript\",\"role\":\"agent\",\"data\":\"There you go.\"}");
>             lokutor.Send("{\"type\":\"status\",\"data\":\"speaking\",\"generation\":1}");
>             lokutor.Audio16(new byte[44100], 1);
>             if (!await Until(shopkeeper, () => shopkeeper.State == AgentState.Speaking)) return Fail("it speaks");
>             if (!await Until(shopkeeper, () => shopkeeper.State == AgentState.Ready)) return Fail("and listens again");
>             Console.WriteLine("passed");
>             return 0;
>         }
>     }
>
>     /// <summary>Runs frames until something is true, five seconds at most.</summary>
>     static async Task<bool> Until(LokutorSession session, Func<bool> done)
>     {
>         var block = new float[session.PlaybackRate / 50];
>         for (int frame = 0; frame < 250 && !done(); frame++)
>         {
>             session.Update();
>             session.Playback.Read(block, 0, block.Length);
>             await Task.Delay(20);
>         }
>         return done();
>     }
>
>     static int Fail(string what) { Console.WriteLine("FAILED: " + what); return 1; }
> }
> ```
>
> It needs no Unity: a console project that compiles `Runtime/Core/**/*.cs` of the package, `MockServer.cs` and this file. For the parts that need the engine, use Unity's own Test Framework and keep them small.

## The messages you need

| To make | Send |
| :- | :- |
| The conversation open | `{"type": "status", "data": "connected", "session_id": "test"}` |
| The player talk | `{"type": "status", "data": "listening"}`, then `{"type": "transcript", "role": "user", "data": "..."}` |
| The character think | `{"type": "status", "data": "thinking", "generation": 1}` |
| It call an action | `{"type": "tool_call", "name": "...", "arguments": "{...}", "call_id": "1"}` (`arguments` is a string of JSON) |
| It answer | `{"type": "transcript", "role": "agent", "data": "..."}`, `{"type": "status", "data": "speaking", "generation": 1}`, then audio |
| Its mouth move | `{"type": "visemes", "generation": 1, "data": [{"v": 10, "c": "aa", "t": 0.0, "d": 0.5}]}` |
| The player interrupt it | `{"type": "status", "data": "interrupted"}`, then a new generation |
| An error | `{"type": "error", "data": {"code": "...", "message": "...", "retryable": false}}` |

Every reply has a `generation`, one more than the last. Audio is 16-bit PCM, 44.1 kHz, mono, in base64 (`send_audio` and `Audio16` do it). The whole protocol is in [WebSocket protocol](https://docs.lokutor.com/guides/websocket-protocol.md).

## What is worth testing

* Every action, with arguments that make no sense: an item that does not exist, a negative price, a missing field.
* That the action *and* the facts (`set_context`) agree after it.
* The connection lost in the middle of a reply, and no credential at all. Both happen to players.
* An interruption while an action is running.
* The whole scene, from opening to closing, without a person: your tests and your trailer can use the same script.

What a mock server cannot tell you is whether the character is any good. For that, talk to it.

## The SDKs' own tests

They use the same servers, and are the longest examples there are:

```bash theme={null}
# Godot (from godot/)
godot --headless --path . --import
godot --headless --path . --script res://tests/unit_tests.gd

# Unity (from unity/)
dotnet run --project Tests~/CoreTests -- unit
dotnet build Tests~/CoreCompat
dotnet build Tests~/UnityCompileCheck
dotnet build Tests~/UnityCompileCheck -p:InputSystem=true
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.