Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ Containers built by a PR and stored on GitHub Container Registry can be tested l
* ServicePulse (latest from Docker Hub)
6. Exit the CLI process. Aspire stops the application automatically.

## Container tests with the testing tool

The [container tests](../tools/testing-tool/TestingTool.ContainerSmokeTests/README.md) start the ServiceControl, audit and monitoring containers from an image tag and run the testing tool's smoke checks against them, using a transport, database and cloud resources that you provide. They run only when `SC_CONTAINER_TESTS_TAG` is set, so a normal test run never starts a container. The README covers the prerequisites, the settings and examples with PostgreSQL and with Amazon SQS and S3.

## Smoke tests with the testing tool

The [testing tool](../tools/testing-tool/README.md#smoke-tests) has a **Smoke tests** tab that sends deterministic messages with a run-specific identifier and verifies custom checks, heartbeats, retries, message editing, redirects, audit data, conversations, sagas, integration events and monitoring data through the ServiceControl APIs. Start it with the Aspire AppHost and `--audit-instances 1`, as described in the [load testing](load-testing.md) page. It complements the [testing scenarios](testing-scenarios.md) checklist: the rows it does not automate stay manual.
15 changes: 11 additions & 4 deletions tools/testing-tool/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,14 @@ Every check sends its own messages with a run identifier (`smoke-<8 hex digits>`

| Check | What it does | What it verifies |
|---|---|---|
| `custom-check-fail-then-pass` | Reports a failed, then a passed custom check with id `Smoke.<run>` to the primary input queue | `GET /api/customchecks?status=fail` lists it with the failure reason, then `?status=pass` lists it and `?status=fail` does not |
| `custom-check-fail-then-pass` | Starts a run-scoped endpoint `TestingTool.Smoke.<run>` with the `NServiceBus.CustomChecks` plugin and one check with id `Smoke.<run>`, run every 2 seconds. The check fails until the tool sees it failed, then passes. The plugin reports to the primary input queue | `GET /api/customchecks?status=fail` lists it with the failure reason, then `?status=pass` lists it and `?status=fail` does not |
| `heartbeat-beating-then-dead` | Starts a real in-process endpoint `TestingTool.Smoke.<run>` with the NServiceBus.Heartbeat plugin, then stops its host | `GET /api/endpoints` shows `heartbeat_information.reported_status` `beating`, then `dead` (about 45 seconds after the host stops with the default 40 second grace period; the check waits up to 100 seconds) |
| `audit-ingestion-fulltext` | Handles a message with a run-specific word in the body | `GET /api/messages/search?q=<word>` finds it with status `successful`, and `GET /api/messages/{id}/body` contains the word |
| `fanout-conversation` | Handles a message that sends two children per level for two levels, with a run-specific conversation id | `GET /api/conversations/{id}` returns the seven messages, and every `NServiceBus.RelatedTo` header points at a parent in the conversation |
| `saga-audit` | Runs a real saga (start, step, finish) with saga auditing to the audit queue | `GET /api/messages/search` finds the start message with its saga id, and `GET /api/sagas/{id}` lists `new`, `updated`, `completed` |
| `monitoring-data` | Starts a real endpoint `TestingTool.Smoke.<run>` with the NServiceBus.Metrics.ServiceControl plugin (2 second interval, as the load endpoint) and handles three messages that each take 100 ms | `GET /monitored-endpoints` on the monitoring instance lists the endpoint with a `processingTime` average above zero. Cleanup deletes the instance ids that monitoring reports for it |
| `integration-event` | Subscribes the tool endpoint to `ServiceControl.Contracts.MessageFailed` and fails one message | The published event arrives with the run header and the failed message id that `GET /api/recoverability/groups/{id}/errors` returns |
| `error-large-body` | Fails one message whose text is 150 KiB (the `large-messages` size, about 190 KiB serialized) in a group unique to the run | `GET /api/messages/{id}/body` on the primary returns more than 100 KB, and the text has the length and SHA-256 that were sent. With `--s3-body-storage` this reads the body back from the bucket |
| `retry-single` | Fails two messages in a group unique to the run, then retries one with `POST /api/errors/{id}/retry` | The tool handled and `GET /api/errors/{id}` reports `resolved` for that message, and its sibling is unresolved and unhandled |
| `retry-group` | Fails three messages in a unique group, then retries the group with `POST /api/recoverability/groups/{id}/errors/retry` | Every message was handled and is `resolved` |
| `edit-and-retry` | Fails a message, then edits it with `POST /api/edit/{id}` (snake_case body, every original header, `Fail` cleared) | The edited message arrives with `ServiceControl.EditOf` set to the failed message id and the edited text |
Expand All @@ -131,11 +132,11 @@ Prerequisites on the instance under test:
- The monitoring check needs `TestingTool__MonitoringApiUrl` to point at the monitoring instance. The AppHost sets it.
- Stop the retry, archive and retention-sweep jobs first: they act on every failed message group, so a start is refused while one runs. Scenarios and bypass writers may keep running.

Run it against a test instance only. Cleanup stops the run-scoped endpoint hosts, removes custom checks, endpoint and monitoring records, and redirects, and archives unresolved failures. Audited messages and resolved or archived failures remain subject to ServiceControl retention. If cleanup fails, the row reports the error and warns that data may remain.
Run it against a test instance only. Cleanup stops the run-scoped endpoint hosts and waits 8 seconds for queued custom-check reports to expire before deleting their records. A report already being processed can recreate a custom-check record after deletion. Cleanup also removes endpoint and monitoring records and redirects, and archives unresolved failures. Audited messages and resolved or archived failures remain subject to ServiceControl retention. If cleanup fails, the row reports the error and warns that data may remain.

Limits of the automation:

- The heartbeat, monitoring and redirect checks start real NServiceBus endpoints, each in its own host in the tool process, next to `TestingTool.Load`. They use the same transport, topology and serializer as the load endpoint, send failures to the same error queue, and handle only smoke messages. Their input addresses come from the transport (`ReceiveAddresses.MainReceiveAddress`), so SQL Server schema and catalog are included. Stopping a host, which a check does explicitly for the heartbeat and always at the end (before any API cleanup, so an unreachable ServiceControl cannot delay it), stops that endpoint and its plugins; it does not stop the tool or the load endpoint. It also does not delete the queues or tables the endpoint created: those run-scoped transport entities stay until the broker or database is torn down. The check exercises the NServiceBus.Heartbeat and NServiceBus.Metrics.ServiceControl plugins.
- The custom check, heartbeat, monitoring and redirect checks start real NServiceBus endpoints, each in its own host in the tool process, next to `TestingTool.Load`. They use the same transport, topology and serializer as the load endpoint, send failures to the same error queue, and handle only smoke messages. Their input addresses come from the transport (`ReceiveAddresses.MainReceiveAddress`), so SQL Server schema and catalog are included. Stopping a host, which a check does explicitly for the heartbeat and always at the end (before any API cleanup, so an unreachable ServiceControl cannot delay it), stops that endpoint and its plugins; it does not stop the tool or the load endpoint. It also does not delete the queues or tables the endpoint created: those run-scoped transport entities stay until the broker or database is torn down. The checks exercise the NServiceBus.CustomChecks, NServiceBus.Heartbeat and NServiceBus.Metrics.ServiceControl plugins.
- The saga is a real saga in the tool endpoint with the NServiceBus.SagaAudit plugin and learning persistence in the temp folder, not a snapshot written by hand.
- Rows marked manual are not automated: instance installation and upgrade, how ServicePulse renders custom checks, heartbeats, recoverability screens, search, the sequence diagram, the saga view and the monitoring graphs, the public integration events sample, chaos testing, and performance, load and stability testing. The API data behind the rendered views is verified by the automated rows above.

Expand All @@ -145,6 +146,8 @@ API:
- `POST /api/smoke/start` — start a run; 400 when one is running or a conflicting job is running
- `POST /api/smoke/stop` — cancel the current run

Packaged ServiceControl containers can run the same checks without the Aspire AppHost: see [container tests](TestingTool.ContainerSmokeTests/README.md).

## Layout

```
Expand All @@ -158,6 +161,7 @@ tools/testing-tool/
TestingTool.Scenarios/ # IScenario contract + the six scenario implementations
TestingTool.Contracts/ # shared DTOs (scenarios, status, jobs, bypass)
TestingTool.Tests/ # Unit tests for the tool itself
TestingTool.ContainerSmokeTests/ # Opt-in tests that run the smoke checks against packaged ServiceControl containers
TestingTool.AppHost/ # Aspire AppHost — orchestrates platform, tool, and observability stack
obs/ # observability config: OTel Collector, Prometheus, Grafana provisioning
# + prebuilt dashboard
Expand Down Expand Up @@ -309,7 +313,9 @@ on its own, set it to the broker your ServiceControl instance uses:
| starts with `amqp:` or `amqps:` (e.g. `amqp://guest:guest@localhost:5672`) | RabbitMQ — quorum queues, conventional routing topology |
| contains an `Endpoint=sb://...` entry (e.g. `Endpoint=sb://my-namespace.servicebus.windows.net/;SharedAccessKeyName=...;SharedAccessKey=...`) | Azure Service Bus — default topic topology. The direct error and audit writers send through the same endpoint, so they use it too |
| SQL Server connection string with `Initial Catalog` or `Database` (e.g. `Server=localhost;Database=Transport;...`) | SQL Server |
| not set or empty | Learning transport (local standalone runs only — ServiceControl won't see the messages) |
| PostgreSQL connection string with `Host` (e.g. `Host=localhost;Database=Transport;Username=...;Password=...`) | PostgreSQL. The tool signs in with the password only; it has no token authentication |
| `Region=...`, optionally with `QueueNamePrefix=...` and `TopicNamePrefix=...` (e.g. `Region=us-east-2`) | Amazon SQS. Credentials always come from the AWS default credential chain, never from the connection string |
| not set or empty | Learning transport (local standalone runs only — ServiceControl won't see the messages). With `TestingTool__RequireTransport=true` startup fails instead |
| anything else | startup fails with an error naming `ConnectionStrings__transport` |

The selected transport is logged at startup (`Using RabbitMQ transport` etc.). The smoke tests start their own run-scoped endpoints with the same selection, so they need the same `ConnectionStrings__transport`.
Expand All @@ -325,6 +331,7 @@ All configuration is via environment variables (no files, no database). Settings
| Setting | Default | Description |
|---|---|---|
| `ConnectionStrings__transport` (env) | *(none — Learning transport)* | Transport connection string; see [Transport](#transport) |
| `TestingTool__RequireTransport` | `false` | When `true`, an empty transport connection string is an error instead of a fallback to the Learning transport |
| `TestingTool__ServiceControlApiUrl` | `http://localhost:33333` | ServiceControl REST API base URL |
| `TestingTool__ReplayInterval` | `00:02:00` | Default interval for the retry job |
| `TestingTool__ReplayMinGroupSize` | `1` | Min messages in a group before retrying |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[*.cs]

# Justification: test code has no synchronization context
dotnet_diagnostic.CA2007.severity = none
dotnet_diagnostic.PS0018.severity = none
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
namespace TestingTool.ContainerSmokeTests;

using System.Text.Json;

/// <summary>
/// Everything the suite takes from the environment. Settings are passed to the containers untouched,
/// so the suite never needs to know what they mean.
/// </summary>
sealed class ContainerTestSettings
{
const string Prefix = "SC_CONTAINER_TESTS_";
const string DefaultRegistry = "ghcr.io/particular";

public string? Tag { get; private init; }
public string Registry { get; private init; } = DefaultRegistry;
public IReadOnlyDictionary<string, string> Common { get; private init; } = new Dictionary<string, string>();
public IReadOnlyDictionary<string, string> Primary { get; private init; } = new Dictionary<string, string>();
public IReadOnlyDictionary<string, string> Audit { get; private init; } = new Dictionary<string, string>();
public IReadOnlyDictionary<string, string> Monitoring { get; private init; } = new Dictionary<string, string>();
public IReadOnlyList<Mount> Mounts { get; private init; } = [];

/// <summary>The transport of the tests' own endpoint is the common one, the same one every container gets unless it overrides it.</summary>
public string? TransportType => Find(Common, "TRANSPORTTYPE");
public string? TransportConnectionString => Find(Common, "CONNECTIONSTRING");

public record Mount(string HostPath, string ContainerPath, bool ReadOnly);

public static ContainerTestSettings Load(IReadOnlyDictionary<string, string> env)
{
var common = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

// The names the container workflow already uses, so one set of variables serves both.
foreach (var key in new[] { "TRANSPORTTYPE", "CONNECTIONSTRING" })
{
if (env.TryGetValue(key, out var value))
{
common[key] = value;
}
}

if (env.TryGetValue(Prefix + "CONFIG", out var file) && !string.IsNullOrWhiteSpace(file))
{
foreach (var (key, value) in ReadConfigFile(file))
{
common[key] = value;
}
}

return new ContainerTestSettings
{
Tag = env.GetValueOrDefault(Prefix + "TAG"),
Registry = env.GetValueOrDefault(Prefix + "REGISTRY") is { Length: > 0 } registry ? registry.TrimEnd('/') : DefaultRegistry,
Common = common,
Primary = WithPrefix(env, Prefix + "PRIMARY_"),
Audit = WithPrefix(env, Prefix + "AUDIT_"),
Monitoring = WithPrefix(env, Prefix + "MONITORING_"),
Mounts = ParseMounts(env.GetValueOrDefault(Prefix + "MOUNTS"))
};
}

public static ContainerTestSettings LoadFromEnvironment() =>
Load(Environment.GetEnvironmentVariables().Cast<System.Collections.DictionaryEntry>()
.ToDictionary(e => (string)e.Key, e => e.Value?.ToString() ?? string.Empty));

/// <summary>Why the suite cannot run meaningfully, or null. Containers cannot share a Learning transport folder with the tests.</summary>
public string? FindProblem()
{
if (string.IsNullOrWhiteSpace(TransportType) || string.IsNullOrWhiteSpace(TransportConnectionString))
{
return "TRANSPORTTYPE and CONNECTIONSTRING must both be set (as environment variables or in SC_CONTAINER_TESTS_CONFIG). Without them the tests would fall back to the Learning transport, which the containers cannot read.";
}

if (TransportType.Contains("Learning", StringComparison.OrdinalIgnoreCase))
{
return "The Learning transport keeps its queues in a folder inside each container, so the tests cannot send to it. Use a transport that both the containers and this process can reach.";
}

return null;
}

/// <summary>Suite defaults, then the common settings, then the instance's own. Later wins.</summary>
public static Dictionary<string, string> Merge(IReadOnlyDictionary<string, string> defaults, IReadOnlyDictionary<string, string> common, IReadOnlyDictionary<string, string> instance)
{
var merged = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var source in new[] { defaults, common, instance })
{
foreach (var (key, value) in source)
{
merged[key] = value;
}
}

return merged;
}

static string? Find(IReadOnlyDictionary<string, string> settings, string name) =>
settings.FirstOrDefault(s => s.Key.Equals(name, StringComparison.OrdinalIgnoreCase) || s.Key.Equals("SERVICECONTROL_" + name, StringComparison.OrdinalIgnoreCase)).Value;

static Dictionary<string, string> WithPrefix(IReadOnlyDictionary<string, string> env, string prefix) =>
env.Where(e => e.Key.StartsWith(prefix, StringComparison.Ordinal) && e.Key.Length > prefix.Length)
.ToDictionary(e => e.Key[prefix.Length..], e => e.Value, StringComparer.OrdinalIgnoreCase);

static Dictionary<string, string> ReadConfigFile(string path)
{
var text = File.ReadAllText(path);

if (path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
return new Dictionary<string, string>(JsonSerializer.Deserialize<Dictionary<string, string>>(text) ?? [], StringComparer.OrdinalIgnoreCase);
}

var settings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var raw in text.Split('\n'))
{
var line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#'))
{
continue;
}

if (line.StartsWith("export ", StringComparison.Ordinal))
{
line = line["export ".Length..];
}

var separator = line.IndexOf('=');
if (separator <= 0)
{
throw new FormatException($"'{line}' in {path} is not KEY=VALUE.");
}

var value = line[(separator + 1)..].Trim();
if (value.Length >= 2 && (value[0] == '"' || value[0] == '\'') && value[^1] == value[0])
{
value = value[1..^1];
}

settings[line[..separator].Trim()] = value;
}

return settings;
}

// host:container[:ro], separated by ';' or new lines, so Windows drive letters are not supported.
static List<Mount> ParseMounts(string? value) =>
(value ?? string.Empty).Split([';', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(entry =>
{
var parts = entry.Split(':');
return parts.Length is 2 or 3 && (parts.Length == 2 || parts[2] is "ro" or "rw")
? new Mount(parts[0], parts[1], parts.Length == 3 && parts[2] == "ro")
: throw new FormatException($"Mount '{entry}' is not host:container[:ro|rw].");
})
.ToList();
}
Loading
Loading