# Debugging & Testing

> Run modules with the debug host and Api Debugger, inside a local Instance with th dev run, or in unit tests.

URL: https://www.trakhound.com/docs/trakhound-framework/debugging

A module can be run three ways while you build it: in a unit test, in the debug host that comes with each template, or inside a local Instance. Each creates the module the same way the Instance does, so what works here works when the Package is installed.

Diagram: Run a module three ways while building it. A unit test with TrakHound.Testing runs it with an in-memory Client and no Instance. The debug host runs it with dotnet run on your computer, with the Api Debugger at /\_debug, and connects to the Instance in trakhound.debug.json. th dev run installs it in a local Instance and reinstalls it each time you save, so it runs with the Instance's routing, security, and Zones.

| Way | Use it to | Needs |
| --- | --- | --- |
| [Unit tests](https://www.trakhound.com/docs/trakhound-framework/debugging#unit-tests) | Check a module's logic quickly, and on every build | A test project |
| [Debug host](https://www.trakhound.com/docs/trakhound-framework/debugging#debug-host) | Run and debug a module with `dotnet run`, and try an API's endpoints in the Api Debugger | An Instance only for `Client` calls |
| [Inside an Instance](https://www.trakhound.com/docs/trakhound-framework/debugging#dev-run) | Run it with the Instance's routing, security, Zones, MCP Server, and other Packages | A local Instance and the [CLI](https://www.trakhound.com/docs/trakhound-framework/cli) |

## Debug Host

Every template has a `Program.cs` that runs the module on your computer without an Instance. Run it with `dotnet run`, or start it from Visual Studio or VS Code. It's left out of the Package.

| Module | `dotnet run` |
| --- | --- |
| API | Serves the endpoints at `http://localhost:5091`, with the Api Debugger at `/_debug` |
| App | Serves the App at `http://localhost:5092`, with the Instance's stylesheets, Theme, and scripts |
| Function | Runs the Function once with its input and prints the response (exit code 1 when the run fails) |
| Worker | Starts the Worker and stops it on Ctrl+C |
| Service, Identity | Creates the module and calls it, without an Instance |

The debug host reads its settings from `trakhound.debug.json`:

```
{
  "instanceUrl": "http://localhost:8472",
  "apiKey": "",
  "parameters": {
    "interval": 5000
  }
}
```

| Setting | Default | What it sets |
| --- | --- | --- |
| `instanceUrl` | `http://localhost:8472` | The Instance `Client` connects to. The debug host says whether it reached it, and runs without it |
| `apiKey`, `bearerToken` |  | Credentials for an Instance that requires them |
| `parameters` |  | The configuration parameters, as set in the Package's configuration on an Instance |
| `input` |  | Functions only: the input parameters to run with when none are passed to `dotnet run` |
| `configurationId` | `debug` | The ID of the configuration |
| `volumePath` | `volume` | The folder used as the Volume, relative to the build output |
| `theme` | `light` | Apps only: the Theme shown until one is picked |

> The file is left out of the Package, but not out of source control. Leave `apiKey` empty in the committed file, or don't commit it.

### Api Debugger

An API's debug host serves the **Api Debugger** at `http://localhost:5091/_debug`. It lists the endpoints and streams from the OpenAPI document the Instance will create for the API, so a missing description or a wrong parameter type shows up before you install it.

- Send requests with a form for the parameters and an editor for the body, and see the response as JSON, text, an image, or a download.
- Connect to stream endpoints over WebSocket or Server-Sent Events, see each message as it arrives, and send input over a WebSocket.
- Watch the debug host's log as it's written: each request, and what the controller writes with `Log(...)`.

The debug host binds parameters and returns errors the same way the Instance does: a body that can't be read returns 400, and an exception returns 500 with its message.

## Debug Inside an Instance

To run a module inside a local Instance, with its routing, security, Zones, MCP Server, and other Packages, use `th dev run` in the project's folder:

```
th dev run --instance C:\TrakHound\Instance
```

It builds the project (Debug, with `.pdb` files), installs it in the Instance folder, and adds a configuration for it (`dev-<packageId>`). Then it watches the project and reinstalls it each time you save, and the Instance picks up each change within a few seconds, without a restart. Press Ctrl+C to stop, and the configuration and Package are removed.

- **The Instance** - `--instance` is the Instance's root folder, with its `packages` and `config` folders, or set the `TRAKHOUND_DEV_INSTANCE` environment variable. The Instance must be running from that folder. Writing to an Instance installed as a Windows Service needs an administrator prompt.
- **Versions** - The Instance only loads new code for a new version, so each build gets the next 4th number of the version (ex. `0.0.1.1`, `0.0.1.2`), and the previous one is uninstalled.
- **The configuration** - Its parameters are the `parameters` in `trakhound.debug.json`. An API or App gets the route in `--route`, the Package's default route, or its ID.
- **Debugging** - Attach your debugger to the Instance process, whose process ID `th dev run` prints. The debugger stays attached across reloads, and breakpoints bind to each new version.
- **Build errors** - A failed build is printed, and the Instance keeps running the last version that built.
- `--no-watch` builds and installs once. `--keep` keeps the configuration and Package when you stop, and `th dev clean` removes them later.

> Apps are reloaded too, but an App's old version can stay in memory, so restart the Instance now and then during a long session.

## Unit Tests

The `TrakHound.Testing` NuGet package runs modules in a unit test (xUnit, NUnit, or MSTest) without an Instance. Add a test project that references your Package project and `TrakHound.Testing`, then create a `TrakHoundTestContext` in each test:

```
public class CounterFunctionTests : IDisposable
{
    private readonly TrakHoundTestContext _context = new TrakHoundTestContext();

    public void Dispose() => _context.Dispose();

    [Fact]
    public async Task AddsToTheCount()
    {
        _context.Parameters["collection"] = "counts";

        var response = await _context.RunFunction<CounterFunction>(new Dictionary<string, string> { ["key"] = "a", ["by"] = "5" });

        Assert.Equal(200, response.StatusCode);
        Assert.Equal("5", (await _context.Client.Services.KeyValues.Read("counts", "a")).Result);
    }
}
```

The context gives modules what the Instance does: a Volume and Variables in a temporary folder (deleted on `Dispose`), the configuration `Parameters` you set, and a `Client`.

| Method | Creates |
| --- | --- |
| `CreateFunction<T>()`, `RunFunction<T>(input)` | A Function. `RunFunction` applies the [parameter](https://www.trakhound.com/docs/trakhound-framework/functions#parameters) defaults and returns 400 for invalid input, like the Instance |
| `CreateWorker<T>()` | A Worker (call `Start` and `Stop`) |
| `CreateApiController<T>()` | An API controller, initialized. Call its endpoint methods directly |
| `CreateService<T>()` | A Service |
| `CreateIdentityProvider<T>()`, `CreateIdentityContext(request)` | An Identity provider, and a context with the request headers and query parameters you set |

- What the modules log is in `_context.Logs`, and `GetLogs(TrakHoundLogLevel.Warning)` returns the warnings and errors.
- `Client.Services.KeyValues`, `Blobs`, and `TimeSeries` are in memory. `Client.Services.Use(service)` puts a Service of your own behind the Key-Value, Blob, Table, and Time Series calls it implements.
- `Client.Functions.Run` runs what you register with `RegisterFunction<T>("id")`, or a fake response with `Client.Functions.Register("id", parameters => ...)`. `Client.Functions.Runs` lists the runs your code requested.
- Everything else (ex. `Client.Api`) throws a `NotSupportedException` naming the property. Set that property to your own implementation, such as a mock.

## Welcome Page for Development Instances

An empty Instance shows nothing at its root (`/`). On a development Instance, install the `TrakHound.Welcome.App` Package to show a home page there instead (the Windows installer's [Default Packages](https://www.trakhound.com/docs/trakhound-framework/installation) page can include it). It installs the [API Explorer](https://www.trakhound.com/docs/trakhound-framework/api-catalog) with it (at `api-explorer`). The page shows:

- The Instance's ID, version, operating system, and health, with any failing health checks
- The Apps (with links), APIs, Functions, Services, Routers, and loaded Packages, with any load errors
- Links to the admin UI, the API Explorer, `llms.txt`, and the MCP Server
- The `dotnet new` commands for the templates, with `--instanceUrl` set to this Instance

It reads the System API from the visitor's browser with their own sign-in, so each section is shown only to visitors who can read it, and the System API must be turned on.

> The Welcome page is meant for development. Remove the Package, or its App configuration, before using the Instance in production.

## Next Steps

- [Standalone Hosts](https://www.trakhound.com/docs/trakhound-framework/standalone-hosts) - Run an API, Worker, or Function without an Instance
- [Building with AI Tools](https://www.trakhound.com/docs/trakhound-framework/ai-tools) - Let AI coding tools build, run, and fix modules
- [Development, Test & Production](https://www.trakhound.com/docs/trakhound-framework/environments) - Move a tested version to production
