From 622c5e1b4cabea7fb48303bfc7fd45dc0855651c Mon Sep 17 00:00:00 2001 From: Rhys Bevilaqua Date: Wed, 2 Dec 2026 02:06:12 +0000 Subject: [PATCH 1/2] Add container tests that run the testing tool smoke checks against packaged containers Adds ServiceControl.Container.Tests, which starts the primary, audit and monitoring containers from an image tag with caller-supplied settings and runs the testing tool smoke checks in-process against them. Adds PostgreSQL and Amazon SQS transports and a RequireTransport option to the testing tool. --- src/Directory.Packages.props | 1 + .../.editorconfig | 5 + .../ContainerTestSettings.cs | 155 ++++++++++++++++++ .../ContainerTestSettingsTests.cs | 80 +++++++++ .../Containers/ContainerPlatformFixture.cs | 44 +++++ .../Containers/PlatformTests.cs | 25 +++ .../Containers/ServiceControlPlatform.cs | 111 +++++++++++++ .../Containers/SmokeTests.cs | 78 +++++++++ src/ServiceControl.Container.Tests/README.md | 35 ++++ .../ServiceControl.Container.Tests.csproj | 26 +++ src/ServiceControl.slnx | 1 + tools/testing-tool/README.md | 5 +- .../TransportSelectionTests.cs | 16 +- .../TestingTool/NServiceBusSetup.cs | 72 +++++++- tools/testing-tool/TestingTool/Program.cs | 4 +- .../TestingTool/TestingTool.csproj | 2 + 16 files changed, 654 insertions(+), 6 deletions(-) create mode 100644 src/ServiceControl.Container.Tests/.editorconfig create mode 100644 src/ServiceControl.Container.Tests/ContainerTestSettings.cs create mode 100644 src/ServiceControl.Container.Tests/ContainerTestSettingsTests.cs create mode 100644 src/ServiceControl.Container.Tests/Containers/ContainerPlatformFixture.cs create mode 100644 src/ServiceControl.Container.Tests/Containers/PlatformTests.cs create mode 100644 src/ServiceControl.Container.Tests/Containers/ServiceControlPlatform.cs create mode 100644 src/ServiceControl.Container.Tests/Containers/SmokeTests.cs create mode 100644 src/ServiceControl.Container.Tests/README.md create mode 100644 src/ServiceControl.Container.Tests/ServiceControl.Container.Tests.csproj diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index de7453a655..7072c7796e 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -94,6 +94,7 @@ + diff --git a/src/ServiceControl.Container.Tests/.editorconfig b/src/ServiceControl.Container.Tests/.editorconfig new file mode 100644 index 0000000000..e30c2fb44d --- /dev/null +++ b/src/ServiceControl.Container.Tests/.editorconfig @@ -0,0 +1,5 @@ +[*.cs] + +# Justification: test code has no synchronization context +dotnet_diagnostic.CA2007.severity = none +dotnet_diagnostic.PS0018.severity = none diff --git a/src/ServiceControl.Container.Tests/ContainerTestSettings.cs b/src/ServiceControl.Container.Tests/ContainerTestSettings.cs new file mode 100644 index 0000000000..cd335c5fa0 --- /dev/null +++ b/src/ServiceControl.Container.Tests/ContainerTestSettings.cs @@ -0,0 +1,155 @@ +namespace ServiceControl.Container.Tests; + +using System.Text.Json; + +/// +/// Everything the suite takes from the environment. Settings are passed to the containers untouched, +/// so the suite never needs to know what they mean. +/// +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 Common { get; private init; } = new Dictionary(); + public IReadOnlyDictionary Primary { get; private init; } = new Dictionary(); + public IReadOnlyDictionary Audit { get; private init; } = new Dictionary(); + public IReadOnlyDictionary Monitoring { get; private init; } = new Dictionary(); + public IReadOnlyList Mounts { get; private init; } = []; + + /// The transport of the tests' own endpoint is the common one, the same one every container gets unless it overrides it. + 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 env) + { + var common = new Dictionary(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() + .ToDictionary(e => (string)e.Key, e => e.Value?.ToString() ?? string.Empty)); + + /// Why the suite cannot run meaningfully, or null. Containers cannot share a Learning transport folder with the tests. + 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; + } + + /// Suite defaults, then the common settings, then the instance's own. Later wins. + public static Dictionary Merge(IReadOnlyDictionary defaults, IReadOnlyDictionary common, IReadOnlyDictionary instance) + { + var merged = new Dictionary(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 settings, string name) => + settings.FirstOrDefault(s => s.Key.Equals(name, StringComparison.OrdinalIgnoreCase) || s.Key.Equals("SERVICECONTROL_" + name, StringComparison.OrdinalIgnoreCase)).Value; + + static Dictionary WithPrefix(IReadOnlyDictionary 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 ReadConfigFile(string path) + { + var text = File.ReadAllText(path); + + if (path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) + { + return new Dictionary(JsonSerializer.Deserialize>(text) ?? [], StringComparer.OrdinalIgnoreCase); + } + + var settings = new Dictionary(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 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(); +} diff --git a/src/ServiceControl.Container.Tests/ContainerTestSettingsTests.cs b/src/ServiceControl.Container.Tests/ContainerTestSettingsTests.cs new file mode 100644 index 0000000000..13bd5fbc31 --- /dev/null +++ b/src/ServiceControl.Container.Tests/ContainerTestSettingsTests.cs @@ -0,0 +1,80 @@ +namespace ServiceControl.Container.Tests; + +using NUnit.Framework; + +/// These need no Docker, but they run under the same filter as the rest of the project. +class ContainerTestSettingsTests +{ + static ContainerTestSettings Load(params (string Key, string Value)[] env) => + ContainerTestSettings.Load(env.ToDictionary(e => e.Key, e => e.Value)); + + [Test] + public void Instance_settings_override_common_settings_which_override_defaults() + { + var settings = Load(("TRANSPORTTYPE", "RabbitMQ.QuorumConventionalRouting"), ("CONNECTIONSTRING", "host=rabbit"), ("SC_CONTAINER_TESTS_AUDIT_CONNECTIONSTRING", "host=other")); + + var primary = ContainerTestSettings.Merge(new Dictionary { ["TRANSPORTTYPE"] = "default", ["X"] = "1" }, settings.Common, settings.Primary); + var audit = ContainerTestSettings.Merge(new Dictionary(), settings.Common, settings.Audit); + + Assert.Multiple(() => + { + Assert.That(primary["TRANSPORTTYPE"], Is.EqualTo("RabbitMQ.QuorumConventionalRouting")); + Assert.That(primary["X"], Is.EqualTo("1")); + Assert.That(primary["CONNECTIONSTRING"], Is.EqualTo("host=rabbit")); + Assert.That(audit["CONNECTIONSTRING"], Is.EqualTo("host=other")); + }); + } + + [TestCase("TRANSPORTTYPE")] + [TestCase("SERVICECONTROL_TRANSPORTTYPE")] + public void Prefixed_transport_names_are_found(string name) + { + var path = Path.GetTempFileName(); + File.WriteAllText(path, $"# comment\nexport {name}=\"SQLServer\"\nCONNECTIONSTRING=Server=x;Database=y\n"); + + try + { + var settings = Load(("SC_CONTAINER_TESTS_CONFIG", path)); + + Assert.Multiple(() => + { + Assert.That(settings.TransportType, Is.EqualTo("SQLServer")); + Assert.That(settings.TransportConnectionString, Is.EqualTo("Server=x;Database=y")); + Assert.That(settings.FindProblem(), Is.Null); + }); + } + finally + { + File.Delete(path); + } + } + + [TestCase(null, null)] + [TestCase("RabbitMQ", null)] + [TestCase(null, "host=rabbit")] + [TestCase("LearningTransport", "anything")] + public void Settings_that_would_use_the_learning_transport_are_a_problem(string? type, string? connectionString) + { + var env = new List<(string, string)>(); + if (type is not null) + { + env.Add(("TRANSPORTTYPE", type)); + } + + if (connectionString is not null) + { + env.Add(("CONNECTIONSTRING", connectionString)); + } + + Assert.That(Load([.. env]).FindProblem(), Is.Not.Null); + } + + [Test] + public void Mounts_are_parsed() => + Assert.That(Load(("SC_CONTAINER_TESTS_MOUNTS", "/a:/b:ro;/c:/d")).Mounts, + Is.EqualTo(new[] { new ContainerTestSettings.Mount("/a", "/b", true), new ContainerTestSettings.Mount("/c", "/d", false) })); + + [Test] + public void A_bad_mount_is_rejected() => + Assert.Throws(() => Load(("SC_CONTAINER_TESTS_MOUNTS", "/a"))); +} diff --git a/src/ServiceControl.Container.Tests/Containers/ContainerPlatformFixture.cs b/src/ServiceControl.Container.Tests/Containers/ContainerPlatformFixture.cs new file mode 100644 index 0000000000..09a962aa4a --- /dev/null +++ b/src/ServiceControl.Container.Tests/Containers/ContainerPlatformFixture.cs @@ -0,0 +1,44 @@ +namespace ServiceControl.Container.Tests.Containers; + +using ServiceControl.Container.Tests; + +using NUnit.Framework; + +/// Starts the containers once for the whole run. Without an image tag every test is skipped. +[SetUpFixture] +public class ContainerPlatformFixture +{ + internal static ContainerTestSettings Settings { get; private set; } = null!; + internal static ServiceControlPlatform Platform { get; private set; } = null!; + + [OneTimeSetUp] + public async Task Start() + { + Settings = ContainerTestSettings.LoadFromEnvironment(); + + if (string.IsNullOrWhiteSpace(Settings.Tag)) + { + Assert.Ignore("SC_CONTAINER_TESTS_TAG is not set."); + } + + if (Settings.FindProblem() is { } problem) + { + Assert.Fail(problem); + } + + Platform = await ServiceControlPlatform.Start(Settings, TestContext.CurrentContext.CancellationToken); + } + + [OneTimeTearDown] + public async Task Stop() + { + if (Platform is null) + { + return; + } + + // Always print the logs: a token or credential problem shows up here even when every test passed. + TestContext.Progress.WriteLine(await Platform.GetLogs()); + await Platform.DisposeAsync(); + } +} diff --git a/src/ServiceControl.Container.Tests/Containers/PlatformTests.cs b/src/ServiceControl.Container.Tests/Containers/PlatformTests.cs new file mode 100644 index 0000000000..511b2bffbc --- /dev/null +++ b/src/ServiceControl.Container.Tests/Containers/PlatformTests.cs @@ -0,0 +1,25 @@ +namespace ServiceControl.Container.Tests.Containers; + +using System.Text.Json; +using NUnit.Framework; + +class PlatformTests +{ + [Test] + public async Task Primary_reports_the_audit_instance_online() + { + using var client = new HttpClient { BaseAddress = ContainerPlatformFixture.Platform.PrimaryUrl }; + using var remotes = JsonDocument.Parse(await client.GetStringAsync("/api/configuration/remotes")); + + Assert.That(remotes.RootElement.EnumerateArray().Select(r => r.GetProperty("status").GetString()), Is.EqualTo(new[] { "online" })); + } + + [Test] + public async Task Monitoring_answers() + { + using var client = new HttpClient { BaseAddress = ContainerPlatformFixture.Platform.MonitoringUrl }; + using var response = await client.GetAsync("/"); + + Assert.That(response.IsSuccessStatusCode, Is.True); + } +} diff --git a/src/ServiceControl.Container.Tests/Containers/ServiceControlPlatform.cs b/src/ServiceControl.Container.Tests/Containers/ServiceControlPlatform.cs new file mode 100644 index 0000000000..284f493d70 --- /dev/null +++ b/src/ServiceControl.Container.Tests/Containers/ServiceControlPlatform.cs @@ -0,0 +1,111 @@ +namespace ServiceControl.Container.Tests.Containers; + +using ServiceControl.Container.Tests; + +using DotNet.Testcontainers.Builders; +using DotNet.Testcontainers.Configurations; +using DotNet.Testcontainers.Containers; +using DotNet.Testcontainers.Networks; + +/// The ServiceControl primary, audit and monitoring containers, started from one image tag. Nothing they depend on is started here. +sealed class ServiceControlPlatform : IAsyncDisposable +{ + const int PrimaryPort = 33333; + const int AuditPort = 44444; + const int MonitoringPort = 33633; + const string AuditAlias = "servicecontrol-audit"; + + readonly INetwork network; + readonly IContainer primary; + readonly IContainer audit; + readonly IContainer monitoring; + + ServiceControlPlatform(INetwork network, IContainer primary, IContainer audit, IContainer monitoring) + { + this.network = network; + this.primary = primary; + this.audit = audit; + this.monitoring = monitoring; + } + + public Uri PrimaryUrl => new($"http://{primary.Hostname}:{primary.GetMappedPublicPort(PrimaryPort)}"); + public Uri AuditUrl => new($"http://{audit.Hostname}:{audit.GetMappedPublicPort(AuditPort)}"); + public Uri MonitoringUrl => new($"http://{monitoring.Hostname}:{monitoring.GetMappedPublicPort(MonitoringPort)}"); + + /// What the smoke checks need on the primary. The caller's settings override these. + static readonly Dictionary PrimaryDefaults = new() + { + ["REMOTEINSTANCES"] = $$"""[{"api_uri":"http://{{AuditAlias}}:{{AuditPort}}/api"}]""", + ["SERVICECONTROL_ALLOWMESSAGEEDITING"] = "true", + ["SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING"] = "true" + }; + + public static async Task Start(ContainerTestSettings settings, CancellationToken cancellationToken = default) + { + var none = new Dictionary(); + var network = new NetworkBuilder().Build(); + var primary = Build(settings, network, "servicecontrol", "servicecontrol", PrimaryPort, ContainerTestSettings.Merge(PrimaryDefaults, settings.Common, settings.Primary)); + var audit = Build(settings, network, "servicecontrol-audit", AuditAlias, AuditPort, ContainerTestSettings.Merge(none, settings.Common, settings.Audit)); + var monitoring = Build(settings, network, "servicecontrol-monitoring", "servicecontrol-monitoring", MonitoringPort, ContainerTestSettings.Merge(none, settings.Common, settings.Monitoring)); + var platform = new ServiceControlPlatform(network, primary, audit, monitoring); + + try + { + await network.CreateAsync(cancellationToken); + await Task.WhenAll(primary.StartAsync(cancellationToken), audit.StartAsync(cancellationToken), monitoring.StartAsync(cancellationToken)); + return platform; + } + catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) + { + // A container that never became healthy is explained by its own log, not by the wait timeout. + var logs = await platform.GetLogs(); + await platform.DisposeAsync(); + throw new InvalidOperationException($"The ServiceControl containers did not start.{Environment.NewLine}{logs}", ex); + } + } + + public async Task GetLogs() + { + var logs = new System.Text.StringBuilder(); + foreach (var (name, container) in new[] { ("primary", primary), ("audit", audit), ("monitoring", monitoring) }) + { + logs.AppendLine($"===== {name} container log ====="); + try + { + var (stdout, stderr) = await container.GetLogsAsync(); + logs.AppendLine(stdout).AppendLine(stderr); + } + catch (Exception ex) + { + // The container may never have been created. + logs.AppendLine($"(no log: {ex.Message})"); + } + } + + return logs.ToString(); + } + + static IContainer Build(ContainerTestSettings settings, INetwork network, string repository, string alias, int port, Dictionary environment) + { + var builder = new ContainerBuilder($"{settings.Registry}/{repository}:{settings.Tag}") + .WithNetwork(network) + .WithNetworkAliases(alias) + .WithEnvironment(environment) + .WithPortBinding(port, true) + .WithCommand("--setup-and-run") + .WithWaitStrategy(Wait.ForUnixContainer().UntilContainerIsHealthy()); + + foreach (var mount in settings.Mounts) + { + builder = builder.WithBindMount(mount.HostPath, mount.ContainerPath, mount.ReadOnly ? AccessMode.ReadOnly : AccessMode.ReadWrite); + } + + return builder.Build(); + } + + public async ValueTask DisposeAsync() + { + await Task.WhenAll(primary.DisposeAsync().AsTask(), audit.DisposeAsync().AsTask(), monitoring.DisposeAsync().AsTask()); + await network.DisposeAsync(); + } +} diff --git a/src/ServiceControl.Container.Tests/Containers/SmokeTests.cs b/src/ServiceControl.Container.Tests/Containers/SmokeTests.cs new file mode 100644 index 0000000000..87d77f2765 --- /dev/null +++ b/src/ServiceControl.Container.Tests/Containers/SmokeTests.cs @@ -0,0 +1,78 @@ +namespace ServiceControl.Container.Tests.Containers; + +using ServiceControl.Container.Tests; + +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.AspNetCore.Mvc.Testing; +using NUnit.Framework; +using TestingTool.Contracts; + +/// Runs the testing tool's smoke checks, hosted in this process, against the containers. +class SmokeTests +{ + static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + [Test, CancelAfter(20 * 60 * 1000)] + public async Task Every_automated_smoke_check_passes() + { + var cancellationToken = TestContext.CurrentContext.CancellationToken; + var platform = ContainerPlatformFixture.Platform; + var settings = ContainerPlatformFixture.Settings; + + // Environment variables because Program reads its configuration before a test factory can add any. + using var _ = new EnvironmentVariables(new() + { + ["ConnectionStrings__transport"] = settings.TransportConnectionString, + ["TestingTool__ServiceControlApiUrl"] = platform.PrimaryUrl.ToString(), + ["TestingTool__MonitoringApiUrl"] = platform.MonitoringUrl.ToString(), + ["TestingTool__RequireTransport"] = "true" + }); + + await using var tool = new WebApplicationFactory(); + using var client = tool.CreateClient(); + client.Timeout = TimeSpan.FromMinutes(1); + + using (var start = await client.PostAsync("/api/smoke/start", null, cancellationToken)) + { + Assert.That(start.IsSuccessStatusCode, Is.True, await start.Content.ReadAsStringAsync(cancellationToken)); + } + + SmokeRunInfo run; + do + { + await Task.Delay(TimeSpan.FromSeconds(2), cancellationToken); + run = (await client.GetFromJsonAsync("/api/smoke", Json, cancellationToken))!; + } while (run.Running); + + var notPassed = run.Checks + .Where(c => c.Status is not (SmokeCheckStatus.Passed or SmokeCheckStatus.Manual)) + .Select(c => $"{c.Id}: {c.Status} - {c.Detail}") + .ToList(); + + Assert.That(notPassed, Is.Empty, string.Join(Environment.NewLine, notPassed)); + Assert.That(run.Checks.Count(c => c.Status == SmokeCheckStatus.Passed), Is.GreaterThan(0), "No smoke check ran."); + } + + sealed class EnvironmentVariables : IDisposable + { + readonly Dictionary previous = []; + + public EnvironmentVariables(Dictionary values) + { + foreach (var (name, value) in values) + { + previous[name] = Environment.GetEnvironmentVariable(name); + Environment.SetEnvironmentVariable(name, value); + } + } + + public void Dispose() + { + foreach (var (name, value) in previous) + { + Environment.SetEnvironmentVariable(name, value); + } + } + } +} diff --git a/src/ServiceControl.Container.Tests/README.md b/src/ServiceControl.Container.Tests/README.md new file mode 100644 index 0000000000..2c436e7be6 --- /dev/null +++ b/src/ServiceControl.Container.Tests/README.md @@ -0,0 +1,35 @@ +# Container tests + +Starts the packaged ServiceControl primary, audit and monitoring containers from an image tag and runs the [testing tool](/tools/testing-tool/README.md) smoke checks against them. The tool is hosted in the test process and uses the same transport as the containers. + +The suite starts nothing else. The transport, the database and any cloud resources must exist already, and the settings that point the containers at them are passed through untouched. + +The tests run only when `ServiceControl_TESTS_FILTER` contains `Container`, and the container tests skip when `SC_CONTAINER_TESTS_TAG` is not set. + +## Settings + +| Variable | Meaning | +| --- | --- | +| `SC_CONTAINER_TESTS_TAG` | Image tag for all three images. Required | +| `SC_CONTAINER_TESTS_REGISTRY` | Registry path of the images, default `ghcr.io/particular`. Use it for locally built images | +| `SC_CONTAINER_TESTS_CONFIG` | A `.env` (`KEY=VALUE`) or `.json` (`{"KEY":"VALUE"}`) file of environment variables for all containers | +| `SC_CONTAINER_TESTS_PRIMARY_*`, `SC_CONTAINER_TESTS_AUDIT_*`, `SC_CONTAINER_TESTS_MONITORING_*` | Environment variables for one container. The prefix is removed. They override the common settings | +| `SC_CONTAINER_TESTS_MOUNTS` | Bind mounts for all containers, `host:container[:ro]`, separated by `;`. For example an AWS profile or a web identity token file | +| `TRANSPORTTYPE`, `CONNECTIONSTRING` | The transport. Read from the process environment or the config file. The containers get them, and the tests' endpoint connects with them | + +Precedence, last wins: the suite's defaults, the common settings, the container's own settings. The suite's defaults are `REMOTEINSTANCES` (primary to audit), `SERVICECONTROL_ALLOWMESSAGEEDITING` and `SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING` on the primary, which the smoke checks need. + +The suite fails before starting anything when the transport is missing or is the Learning transport, because the containers could not share its folder with the tests. The tool's transport is the common `TRANSPORTTYPE`/`CONNECTIONSTRING`. See the tool's [Transport](/tools/testing-tool/README.md#transport) section for the connection strings it accepts. The tool supports fewer transports than ServiceControl does. + +## Example + +```bash +export ServiceControl_TESTS_FILTER=Container +export SC_CONTAINER_TESTS_TAG=pr-1234 +export TRANSPORTTYPE=PostgreSQL +export CONNECTIONSTRING='Host=db;Database=sc;Username=sc;Password=...' +export SC_CONTAINER_TESTS_CONFIG=./containers.env # STORAGETYPE, DATABASE_CONNECTIONSTRING, PARTICULARSOFTWARE_LICENSE ... +dotnet test src/ServiceControl.Container.Tests +``` + +Container logs are printed when the run ends, and when the containers fail to start. diff --git a/src/ServiceControl.Container.Tests/ServiceControl.Container.Tests.csproj b/src/ServiceControl.Container.Tests/ServiceControl.Container.Tests.csproj new file mode 100644 index 0000000000..1104b549d8 --- /dev/null +++ b/src/ServiceControl.Container.Tests/ServiceControl.Container.Tests.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + Container + enable + enable + + + + + + + + + + + + + + + + + + + diff --git a/src/ServiceControl.slnx b/src/ServiceControl.slnx index e9a507b944..0cf1789071 100644 --- a/src/ServiceControl.slnx +++ b/src/ServiceControl.slnx @@ -73,6 +73,7 @@ + diff --git a/tools/testing-tool/README.md b/tools/testing-tool/README.md index 11ed3bf265..b016157bed 100644 --- a/tools/testing-tool/README.md +++ b/tools/testing-tool/README.md @@ -309,7 +309,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`. @@ -325,6 +327,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 | diff --git a/tools/testing-tool/TestingTool.Tests/TransportSelectionTests.cs b/tools/testing-tool/TestingTool.Tests/TransportSelectionTests.cs index 23167a885a..75ac991dc1 100644 --- a/tools/testing-tool/TestingTool.Tests/TransportSelectionTests.cs +++ b/tools/testing-tool/TestingTool.Tests/TransportSelectionTests.cs @@ -13,6 +13,9 @@ public class TransportSelectionTests [TestCase("endpoint=SB://example.servicebus.windows.net/;SharedAccessKeyName=k;SharedAccessKey=ZmFrZQ==", "AzureServiceBus")] [TestCase("amqp://guest:guest@localhost:5672", "RabbitMQ")] [TestCase("Server=localhost;Database=Transport;User Id=sa;Password=x;TrustServerCertificate=true", "SqlServer")] + [TestCase("Host=localhost;Port=5432;Database=sc;Username=u;Password=p", "PostgreSql")] + [TestCase("Region=us-east-2", "AmazonSqs")] + [TestCase("Region=us-east-2;QueueNamePrefix=q;TopicNamePrefix=t", "AmazonSqs")] [TestCase("", "Learning")] public void Selects_transport_from_connection_string(string connectionString, string expected) => Assert.That(Select(connectionString).Name, Is.EqualTo(expected)); @@ -22,10 +25,19 @@ public void Selects_transport_from_connection_string(string connectionString, st public void Rejects_unrecognised_connection_string(string connectionString) => Assert.Throws(() => Select(connectionString)); - static SelectedTransport Select(string connectionString) + [TestCase("")] + [TestCase(" ")] + public void Strict_mode_rejects_a_missing_connection_string(string connectionString) => + Assert.Throws(() => Select(connectionString, requireTransport: true)); + + [Test] + public void Strict_mode_accepts_a_connection_string() => + Assert.That(Select("amqp://guest:guest@localhost:5672", requireTransport: true).Name, Is.EqualTo("RabbitMQ")); + + static SelectedTransport Select(string connectionString, bool requireTransport = false) { var configuration = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary { ["ConnectionStrings:transport"] = connectionString }) + .AddInMemoryCollection(new Dictionary { ["ConnectionStrings:transport"] = connectionString, ["TestingTool:RequireTransport"] = requireTransport.ToString() }) .Build(); var services = new ServiceCollection(); services.AddTestingToolEndpoint(new TestingToolOptions(), configuration); diff --git a/tools/testing-tool/TestingTool/NServiceBusSetup.cs b/tools/testing-tool/TestingTool/NServiceBusSetup.cs index 05baee80d5..3090bb5564 100644 --- a/tools/testing-tool/TestingTool/NServiceBusSetup.cs +++ b/tools/testing-tool/TestingTool/NServiceBusSetup.cs @@ -1,8 +1,12 @@ using System.Data.Common; +using Amazon; +using Amazon.SimpleNotificationService; +using Amazon.SQS; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Options; using NServiceBus; using NServiceBus.Features; +using Npgsql; using TestingTool.Auditing; using TestingTool.Smoke; @@ -23,7 +27,9 @@ public static class NServiceBusEndpointExtensions /// starts with amqp: or amqps: — RabbitMQ, quorum queues with conventional routing /// a connection string with an Endpoint=sb:// entry — Azure Service Bus, default topic topology /// a SQL Server connection string naming a database (Initial Catalog/Database) — SQL Server - /// not set or empty — Learning transport, for local standalone runs + /// a PostgreSQL connection string naming a Host — PostgreSQL (password sign-in) + /// Region=..., optionally with QueueNamePrefix and TopicNamePrefix — Amazon SQS, credentials from the AWS default chain + /// not set or empty — Learning transport, for local standalone runs; an error when TestingTool:RequireTransport is true /// /// Any other value throws, so a mistyped connection string can't silently send load to a /// Learning transport folder that ServiceControl never reads. The selected transport is @@ -91,6 +97,12 @@ public static SelectedTransport ConfigureTransport(EndpointConfiguration config, string transportName; if (string.IsNullOrWhiteSpace(transportConnectionString)) { + // Strict mode stops a container test from sending to a Learning folder that no container reads. + if (configuration.GetValue("TestingTool:RequireTransport")) + { + throw new InvalidOperationException("TestingTool:RequireTransport is set, but the 'transport' connection string (ConnectionStrings__transport) is empty, which would fall back to the Learning transport."); + } + transportName = "Learning"; config.UseTransport(); } @@ -112,12 +124,36 @@ public static SelectedTransport ConfigureTransport(EndpointConfiguration config, transportName = "SqlServer"; config.UseTransport(new SqlServerTransport(transportConnectionString)); } + else if (IsPostgreSqlConnectionString(transportConnectionString)) + { + transportName = "PostgreSql"; + config.UseTransport(new PostgreSqlTransport(transportConnectionString)); + } + else if (TryParseSqsConnectionString(transportConnectionString, out var sqs)) + { + transportName = "AmazonSqs"; + // Credentials come from the AWS default chain, never from the connection string. + var transport = new SqsTransport( + new AmazonSQSClient(RegionEndpoint.GetBySystemName(sqs.Region)), + new AmazonSimpleNotificationServiceClient(RegionEndpoint.GetBySystemName(sqs.Region))); + if (!string.IsNullOrEmpty(sqs.QueueNamePrefix)) + { + transport.QueueNamePrefix = sqs.QueueNamePrefix; + } + + if (!string.IsNullOrEmpty(sqs.TopicNamePrefix)) + { + transport.TopicNamePrefix = sqs.TopicNamePrefix; + } + + config.UseTransport(transport); + } else { throw new InvalidOperationException( "Unrecognised 'transport' connection string (ConnectionStrings__transport). Expected an " + "amqp:// or amqps:// URI for RabbitMQ, an Endpoint=sb://... connection string for Azure Service Bus, or a SQL Server connection string with " + - "Initial Catalog/Database for SQL Server. Leave it unset to use the Learning transport."); + "Initial Catalog/Database for SQL Server, a PostgreSQL connection string with Host for PostgreSQL, or Region=...[;QueueNamePrefix=...][;TopicNamePrefix=...] for Amazon SQS. Leave it unset to use the Learning transport."); } return new SelectedTransport(transportName); @@ -137,6 +173,38 @@ static bool IsAzureServiceBusConnectionString(string connectionString) } } + static bool IsPostgreSqlConnectionString(string connectionString) + { + try + { + return !string.IsNullOrWhiteSpace(new NpgsqlConnectionStringBuilder(connectionString).Host); + } + catch (ArgumentException) + { + return false; + } + } + + static bool TryParseSqsConnectionString(string connectionString, out (string Region, string? QueueNamePrefix, string? TopicNamePrefix) sqs) + { + sqs = default; + try + { + var builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; + if (!builder.TryGetValue("Region", out var region) || string.IsNullOrWhiteSpace(region.ToString())) + { + return false; + } + + sqs = (region.ToString()!, builder.TryGetValue("QueueNamePrefix", out var q) ? q.ToString() : null, builder.TryGetValue("TopicNamePrefix", out var t) ? t.ToString() : null); + return true; + } + catch (ArgumentException) + { + return false; + } + } + static bool IsSqlServerConnectionString(string connectionString) { try diff --git a/tools/testing-tool/TestingTool/Program.cs b/tools/testing-tool/TestingTool/Program.cs index 8183d9128b..54e038424a 100644 --- a/tools/testing-tool/TestingTool/Program.cs +++ b/tools/testing-tool/TestingTool/Program.cs @@ -337,4 +337,6 @@ app.MapFallbackToFile("index.html"); -app.Run(); \ No newline at end of file +app.Run(); +// Lets WebApplicationFactory host the tool in-process. +public partial class Program; diff --git a/tools/testing-tool/TestingTool/TestingTool.csproj b/tools/testing-tool/TestingTool/TestingTool.csproj index f20fd1c1f1..cfcbde204b 100644 --- a/tools/testing-tool/TestingTool/TestingTool.csproj +++ b/tools/testing-tool/TestingTool/TestingTool.csproj @@ -13,12 +13,14 @@ + + From 69385b1a998a9c69a4965846dd9e5f63184ef0a8 Mon Sep 17 00:00:00 2001 From: Rhys Bevilaqua Date: Wed, 2 Dec 2026 14:27:09 +0800 Subject: [PATCH 2/2] Expand container smoke coverage and move tests alongside the tool Move the container tests from src/ServiceControl.Container.Tests to tools/testing-tool/TestingTool.ContainerSmokeTests so they build and run with the testing tool solution. Run the custom-check smoke check through the NServiceBus.CustomChecks plugin, add an error-large-body check, and document the container tests. --- docs/testing.md | 4 + src/Directory.Packages.props | 1 - src/ServiceControl.Container.Tests/README.md | 35 ---- .../ServiceControl.Container.Tests.csproj | 26 --- src/ServiceControl.slnx | 1 - tools/testing-tool/README.md | 10 +- .../.editorconfig | 0 .../ContainerTestSettings.cs | 2 +- .../ContainerTestSettingsTests.cs | 2 +- .../Containers/ContainerPlatformFixture.cs | 4 +- .../Containers/PlatformTests.cs | 2 +- .../Containers/ServiceControlPlatform.cs | 4 +- .../Containers/SmokeTests.cs | 4 +- .../TestingTool.ContainerSmokeTests/README.md | 154 ++++++++++++++++++ .../TestingTool.ContainerSmokeTests.csproj | 22 +++ .../Smoke/SmokeChecksTests.cs | 90 ++++++---- .../Smoke/SmokeEndpointLifecycleTests.cs | 34 +++- tools/testing-tool/TestingTool.slnx | 1 + .../TestingTool/Smoke/SmokeApiClient.cs | 7 + .../TestingTool/Smoke/SmokeChecks.cs | 102 ++++++++---- .../TestingTool/Smoke/SmokeCustomCheck.cs | 29 ++++ .../TestingTool/Smoke/SmokeEndpoint.cs | 4 +- .../TestingTool/TestingTool.csproj | 1 + 23 files changed, 400 insertions(+), 139 deletions(-) delete mode 100644 src/ServiceControl.Container.Tests/README.md delete mode 100644 src/ServiceControl.Container.Tests/ServiceControl.Container.Tests.csproj rename {src/ServiceControl.Container.Tests => tools/testing-tool/TestingTool.ContainerSmokeTests}/.editorconfig (100%) rename {src/ServiceControl.Container.Tests => tools/testing-tool/TestingTool.ContainerSmokeTests}/ContainerTestSettings.cs (99%) rename {src/ServiceControl.Container.Tests => tools/testing-tool/TestingTool.ContainerSmokeTests}/ContainerTestSettingsTests.cs (98%) rename {src/ServiceControl.Container.Tests => tools/testing-tool/TestingTool.ContainerSmokeTests}/Containers/ContainerPlatformFixture.cs (92%) rename {src/ServiceControl.Container.Tests => tools/testing-tool/TestingTool.ContainerSmokeTests}/Containers/PlatformTests.cs (93%) rename {src/ServiceControl.Container.Tests => tools/testing-tool/TestingTool.ContainerSmokeTests}/Containers/ServiceControlPlatform.cs (98%) rename {src/ServiceControl.Container.Tests => tools/testing-tool/TestingTool.ContainerSmokeTests}/Containers/SmokeTests.cs (96%) create mode 100644 tools/testing-tool/TestingTool.ContainerSmokeTests/README.md create mode 100644 tools/testing-tool/TestingTool.ContainerSmokeTests/TestingTool.ContainerSmokeTests.csproj create mode 100644 tools/testing-tool/TestingTool/Smoke/SmokeCustomCheck.cs diff --git a/docs/testing.md b/docs/testing.md index 9d03e64bdc..ce3c2b7a52 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -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. diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index 7072c7796e..de7453a655 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -94,7 +94,6 @@ - diff --git a/src/ServiceControl.Container.Tests/README.md b/src/ServiceControl.Container.Tests/README.md deleted file mode 100644 index 2c436e7be6..0000000000 --- a/src/ServiceControl.Container.Tests/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Container tests - -Starts the packaged ServiceControl primary, audit and monitoring containers from an image tag and runs the [testing tool](/tools/testing-tool/README.md) smoke checks against them. The tool is hosted in the test process and uses the same transport as the containers. - -The suite starts nothing else. The transport, the database and any cloud resources must exist already, and the settings that point the containers at them are passed through untouched. - -The tests run only when `ServiceControl_TESTS_FILTER` contains `Container`, and the container tests skip when `SC_CONTAINER_TESTS_TAG` is not set. - -## Settings - -| Variable | Meaning | -| --- | --- | -| `SC_CONTAINER_TESTS_TAG` | Image tag for all three images. Required | -| `SC_CONTAINER_TESTS_REGISTRY` | Registry path of the images, default `ghcr.io/particular`. Use it for locally built images | -| `SC_CONTAINER_TESTS_CONFIG` | A `.env` (`KEY=VALUE`) or `.json` (`{"KEY":"VALUE"}`) file of environment variables for all containers | -| `SC_CONTAINER_TESTS_PRIMARY_*`, `SC_CONTAINER_TESTS_AUDIT_*`, `SC_CONTAINER_TESTS_MONITORING_*` | Environment variables for one container. The prefix is removed. They override the common settings | -| `SC_CONTAINER_TESTS_MOUNTS` | Bind mounts for all containers, `host:container[:ro]`, separated by `;`. For example an AWS profile or a web identity token file | -| `TRANSPORTTYPE`, `CONNECTIONSTRING` | The transport. Read from the process environment or the config file. The containers get them, and the tests' endpoint connects with them | - -Precedence, last wins: the suite's defaults, the common settings, the container's own settings. The suite's defaults are `REMOTEINSTANCES` (primary to audit), `SERVICECONTROL_ALLOWMESSAGEEDITING` and `SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING` on the primary, which the smoke checks need. - -The suite fails before starting anything when the transport is missing or is the Learning transport, because the containers could not share its folder with the tests. The tool's transport is the common `TRANSPORTTYPE`/`CONNECTIONSTRING`. See the tool's [Transport](/tools/testing-tool/README.md#transport) section for the connection strings it accepts. The tool supports fewer transports than ServiceControl does. - -## Example - -```bash -export ServiceControl_TESTS_FILTER=Container -export SC_CONTAINER_TESTS_TAG=pr-1234 -export TRANSPORTTYPE=PostgreSQL -export CONNECTIONSTRING='Host=db;Database=sc;Username=sc;Password=...' -export SC_CONTAINER_TESTS_CONFIG=./containers.env # STORAGETYPE, DATABASE_CONNECTIONSTRING, PARTICULARSOFTWARE_LICENSE ... -dotnet test src/ServiceControl.Container.Tests -``` - -Container logs are printed when the run ends, and when the containers fail to start. diff --git a/src/ServiceControl.Container.Tests/ServiceControl.Container.Tests.csproj b/src/ServiceControl.Container.Tests/ServiceControl.Container.Tests.csproj deleted file mode 100644 index 1104b549d8..0000000000 --- a/src/ServiceControl.Container.Tests/ServiceControl.Container.Tests.csproj +++ /dev/null @@ -1,26 +0,0 @@ - - - - net10.0 - Container - enable - enable - - - - - - - - - - - - - - - - - - - diff --git a/src/ServiceControl.slnx b/src/ServiceControl.slnx index 0cf1789071..e9a507b944 100644 --- a/src/ServiceControl.slnx +++ b/src/ServiceControl.slnx @@ -73,7 +73,6 @@ - diff --git a/tools/testing-tool/README.md b/tools/testing-tool/README.md index b016157bed..9c2e663f71 100644 --- a/tools/testing-tool/README.md +++ b/tools/testing-tool/README.md @@ -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.` 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.` with the `NServiceBus.CustomChecks` plugin and one check with id `Smoke.`, 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.` 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=` 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.` 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 | @@ -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. @@ -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 ``` @@ -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 diff --git a/src/ServiceControl.Container.Tests/.editorconfig b/tools/testing-tool/TestingTool.ContainerSmokeTests/.editorconfig similarity index 100% rename from src/ServiceControl.Container.Tests/.editorconfig rename to tools/testing-tool/TestingTool.ContainerSmokeTests/.editorconfig diff --git a/src/ServiceControl.Container.Tests/ContainerTestSettings.cs b/tools/testing-tool/TestingTool.ContainerSmokeTests/ContainerTestSettings.cs similarity index 99% rename from src/ServiceControl.Container.Tests/ContainerTestSettings.cs rename to tools/testing-tool/TestingTool.ContainerSmokeTests/ContainerTestSettings.cs index cd335c5fa0..667649d062 100644 --- a/src/ServiceControl.Container.Tests/ContainerTestSettings.cs +++ b/tools/testing-tool/TestingTool.ContainerSmokeTests/ContainerTestSettings.cs @@ -1,4 +1,4 @@ -namespace ServiceControl.Container.Tests; +namespace TestingTool.ContainerSmokeTests; using System.Text.Json; diff --git a/src/ServiceControl.Container.Tests/ContainerTestSettingsTests.cs b/tools/testing-tool/TestingTool.ContainerSmokeTests/ContainerTestSettingsTests.cs similarity index 98% rename from src/ServiceControl.Container.Tests/ContainerTestSettingsTests.cs rename to tools/testing-tool/TestingTool.ContainerSmokeTests/ContainerTestSettingsTests.cs index 13bd5fbc31..b34ed3edf1 100644 --- a/src/ServiceControl.Container.Tests/ContainerTestSettingsTests.cs +++ b/tools/testing-tool/TestingTool.ContainerSmokeTests/ContainerTestSettingsTests.cs @@ -1,4 +1,4 @@ -namespace ServiceControl.Container.Tests; +namespace TestingTool.ContainerSmokeTests; using NUnit.Framework; diff --git a/src/ServiceControl.Container.Tests/Containers/ContainerPlatformFixture.cs b/tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/ContainerPlatformFixture.cs similarity index 92% rename from src/ServiceControl.Container.Tests/Containers/ContainerPlatformFixture.cs rename to tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/ContainerPlatformFixture.cs index 09a962aa4a..3652eef3a3 100644 --- a/src/ServiceControl.Container.Tests/Containers/ContainerPlatformFixture.cs +++ b/tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/ContainerPlatformFixture.cs @@ -1,6 +1,6 @@ -namespace ServiceControl.Container.Tests.Containers; +namespace TestingTool.ContainerSmokeTests.Containers; -using ServiceControl.Container.Tests; +using TestingTool.ContainerSmokeTests; using NUnit.Framework; diff --git a/src/ServiceControl.Container.Tests/Containers/PlatformTests.cs b/tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/PlatformTests.cs similarity index 93% rename from src/ServiceControl.Container.Tests/Containers/PlatformTests.cs rename to tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/PlatformTests.cs index 511b2bffbc..1a5fd749c0 100644 --- a/src/ServiceControl.Container.Tests/Containers/PlatformTests.cs +++ b/tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/PlatformTests.cs @@ -1,4 +1,4 @@ -namespace ServiceControl.Container.Tests.Containers; +namespace TestingTool.ContainerSmokeTests.Containers; using System.Text.Json; using NUnit.Framework; diff --git a/src/ServiceControl.Container.Tests/Containers/ServiceControlPlatform.cs b/tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/ServiceControlPlatform.cs similarity index 98% rename from src/ServiceControl.Container.Tests/Containers/ServiceControlPlatform.cs rename to tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/ServiceControlPlatform.cs index 284f493d70..0130604eb7 100644 --- a/src/ServiceControl.Container.Tests/Containers/ServiceControlPlatform.cs +++ b/tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/ServiceControlPlatform.cs @@ -1,6 +1,6 @@ -namespace ServiceControl.Container.Tests.Containers; +namespace TestingTool.ContainerSmokeTests.Containers; -using ServiceControl.Container.Tests; +using TestingTool.ContainerSmokeTests; using DotNet.Testcontainers.Builders; using DotNet.Testcontainers.Configurations; diff --git a/src/ServiceControl.Container.Tests/Containers/SmokeTests.cs b/tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/SmokeTests.cs similarity index 96% rename from src/ServiceControl.Container.Tests/Containers/SmokeTests.cs rename to tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/SmokeTests.cs index 87d77f2765..cf378c811e 100644 --- a/src/ServiceControl.Container.Tests/Containers/SmokeTests.cs +++ b/tools/testing-tool/TestingTool.ContainerSmokeTests/Containers/SmokeTests.cs @@ -1,6 +1,6 @@ -namespace ServiceControl.Container.Tests.Containers; +namespace TestingTool.ContainerSmokeTests.Containers; -using ServiceControl.Container.Tests; +using TestingTool.ContainerSmokeTests; using System.Net.Http.Json; using System.Text.Json; diff --git a/tools/testing-tool/TestingTool.ContainerSmokeTests/README.md b/tools/testing-tool/TestingTool.ContainerSmokeTests/README.md new file mode 100644 index 0000000000..67de88fdef --- /dev/null +++ b/tools/testing-tool/TestingTool.ContainerSmokeTests/README.md @@ -0,0 +1,154 @@ +# Container tests + +Starts the packaged ServiceControl primary, audit and monitoring containers from an image tag and runs the [testing tool](../README.md) smoke checks against them. The tool is hosted in the test process and uses the same transport as the containers. + +The suite starts only the three ServiceControl containers. The services they depend on must exist already: the message broker or database that hosts the transport, the persistence database, and any cloud account and bucket. ServiceControl and the tests' endpoints create the queues, topics and tables themselves when they start. The settings that point the containers at these services are passed through untouched. + +## Prerequisites + +- A Docker daemon that the current user can reach, and access to the registry that holds the images (`docker login ghcr.io` for the default registry). +- The .NET SDK that `global.json` selects (.NET 10). +- A Particular Software license, in `PARTICULARSOFTWARE_LICENSE` for the test process and in the containers' settings file (see below). +- A transport service and a database that the host process and the containers can both reach. + +## Running + +The project is part of `TestingTool.slnx`, but it starts containers only when `SC_CONTAINER_TESTS_TAG` is set. While the variable is unset the container tests are skipped, so `dotnet test TestingTool.slnx` starts no container. With the variable set, the same command runs them too, so run the project explicitly: + +```bash +export SC_CONTAINER_TESTS_TAG='' +export SC_CONTAINER_TESTS_CONFIG='' +dotnet test tools/testing-tool/TestingTool.ContainerSmokeTests +``` + +The suite fails before starting anything when the transport is missing or is the Learning transport, because the containers cannot share its folder with the tests. The tool also runs with `TestingTool__RequireTransport=true` here, so an empty connection string is an error instead of a fallback to the Learning transport. + +Container logs are printed when the run ends, and when the containers fail to start. A credential or token problem shows in these logs even when every test passed. + +## Settings + +| Variable | Meaning | +| --- | --- | +| `SC_CONTAINER_TESTS_TAG` | Image tag for all three images. Required to run the container tests | +| `SC_CONTAINER_TESTS_REGISTRY` | Registry path of the images, default `ghcr.io/particular`. Use it for locally built images | +| `SC_CONTAINER_TESTS_CONFIG` | A `.env` (`KEY=VALUE`, optional `export`, optional quotes, `#` comments) or `.json` (`{"KEY":"VALUE"}`) file of environment variables for all containers | +| `SC_CONTAINER_TESTS_PRIMARY_*`, `SC_CONTAINER_TESTS_AUDIT_*`, `SC_CONTAINER_TESTS_MONITORING_*` | Environment variables for one container. The prefix is removed. They override the common settings | +| `SC_CONTAINER_TESTS_MOUNTS` | Bind mounts for all containers, `host:container[:ro\|rw]`, separated by `;` or new lines. Windows drive letters are not supported | +| `TRANSPORTTYPE`, `CONNECTIONSTRING` | The transport. Read from the process environment or the config file. The containers get them, and the tests' endpoint connects with them. The file wins over the process environment | + +Set only one connection-string form: `CONNECTIONSTRING` or `SERVICECONTROL_CONNECTIONSTRING`, not both. Conflicting forms can make the tool and the containers connect to different brokers. + +Precedence, last wins: the suite's defaults, the common settings, the container's own settings. The suite's defaults are `REMOTEINSTANCES` (primary to audit), `SERVICECONTROL_ALLOWMESSAGEEDITING` and `SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING` on the primary, which the smoke checks need. + +A container receives only these settings. Other variables of the test process, such as `AWS_PROFILE`, are not forwarded, so a setting that both sides need must be set in both places. The in-process tool reads the test process's own environment. + +The tool supports fewer transports than ServiceControl does. See its [Transport](../README.md#transport) section for the connection strings it accepts. ServiceControl setting names map to environment variables by replacing `/` and `.` with `_`, for example `MessageBody/S3/KeyPrefix` is `MESSAGEBODY_S3_KEYPREFIX`; see [Message body storage](../../../docs/message-body-storage.md) for the keys. + +The settings file holds credentials. Keep it outside the repository or in an ignored path, and do not paste it into issues or logs. In the examples, replace each `` with a real value. In shell commands the placeholders are inside quotes, and in settings files quotes are optional. + +## Example: PostgreSQL transport and database, file system bodies + +Run PostgreSQL locally and give it a password that exists only for this test database: + +```bash +POSTGRES_PASSWORD='' +docker run -d --name sc-test-postgres -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" -p 5432:5432 postgres +``` + +The tests' endpoint and the containers use the same connection string, so its host must be reachable from both. On Docker Desktop use `host.docker.internal`. On Linux use an address of the host that containers can reach, such as the gateway of Docker's bridge network (`docker network inspect bridge`), and make sure PostgreSQL accepts connections on it. + +Settings file `containers.env`: + +``` +TRANSPORTTYPE=PostgreSQL +CONNECTIONSTRING=Host=;Port=5432;Database=postgres;Username=postgres;Password= +STORAGETYPE=PostgreSQL +DATABASE_CONNECTIONSTRING=Host=;Port=5432;Database=postgres;Username=postgres;Password= +MESSAGEBODY_STORAGETYPE=FileSystem +PARTICULARSOFTWARE_LICENSE= +``` + +The primary and audit instances must each have their own body location, because retention deletes whole groups under a location (see [One location per instance](../../../docs/message-body-storage.md#one-location-per-instance)). The directories are inside the containers, so mount one host directory and give each instance a subdirectory. Make both writable for the container's non-root user. Use `chmod 777` only for a scratch directory that holds test data. + +With the PostgreSQL transport the in-process tool needs the queue names `Particular.ServiceControl` and `Particular.Monitoring` in quoted form, so each dotted name identifies one table rather than a schema and table. Set both with the double quotes included. These two settings change only the addresses the tool sends to. The containers keep their own queue names. + +```bash +mkdir -p "$PWD/bodies/primary" "$PWD/bodies/audit" +chmod 777 "$PWD/bodies" "$PWD/bodies/primary" "$PWD/bodies/audit" +export SC_CONTAINER_TESTS_MOUNTS="$PWD/bodies:/bodies" +export SC_CONTAINER_TESTS_PRIMARY_MESSAGEBODY_FILESYSTEM_STORAGEPATH=/bodies/primary +export SC_CONTAINER_TESTS_AUDIT_MESSAGEBODY_FILESYSTEM_STORAGEPATH=/bodies/audit +export TestingTool__ServiceControlInputQueue='"Particular.ServiceControl"' +export TestingTool__MonitoringQueueName='"Particular.Monitoring"' +export SC_CONTAINER_TESTS_TAG='' +export SC_CONTAINER_TESTS_CONFIG="$PWD/containers.env" +dotnet test tools/testing-tool/TestingTool.ContainerSmokeTests +``` + +## Example: Amazon SQS transport with S3 message bodies + +Create these first. The suite creates no IAM roles, policies or buckets, and nothing here deletes them: + +- A role, or a user, that allows SQS and SNS to create, use and tag the queues and topics under the run's name prefix, and S3 to read, write, list and delete under the run's key prefixes in the bucket. The [SQS transport documentation](https://docs.particular.net/transports/sqs/) lists the transport permissions. Grant the least that covers your prefix. +- An S3 bucket, for example `example-message-bodies`. ServiceControl setup creates the bucket when it is missing and the credentials allow it, so create it beforehand to keep that permission out of the role. + +The containers read AWS configuration from files mounted read-only, and the test process reads its own copy from the host. Put a `config` and a `credentials` file in one directory, readable by the container's non-root user, for example `$PWD/aws`. The profile must resolve from those files alone, for example by assuming a role: + +``` +[profile smoke-test] +role_arn = arn:aws:iam:::role/ +source_profile = +region = us-east-1 +``` + +Use a run name that is unique per run, for example `sc-smoke-`. Use a `RUN` shell variable for it in the commands below. The containers and the tests' endpoint must use the same queue prefix and the same topic prefix to communicate. The examples use one prefix for both resource types to simplify cleanup. + +Settings file `containers.env`, where the AWS paths are the paths inside the container: + +``` +TRANSPORTTYPE=AmazonSQS +CONNECTIONSTRING=Region=us-east-1;QueueNamePrefix=sc-smoke--;TopicNamePrefix=sc-smoke-- +STORAGETYPE=PostgreSQL +DATABASE_CONNECTIONSTRING=Host=;Port=5432;Database=postgres;Username=postgres;Password= +MESSAGEBODY_STORAGETYPE=S3 +MESSAGEBODY_S3_BUCKETNAME=example-message-bodies +MESSAGEBODY_S3_REGION=us-east-1 +AWS_PROFILE=smoke-test +AWS_CONFIG_FILE=/aws/config +AWS_SHARED_CREDENTIALS_FILE=/aws/credentials +PARTICULARSOFTWARE_LICENSE= +``` + +The primary and audit instances must not share a body key prefix, because retention deletes whole groups under a prefix. Set one per instance, scoped to the run. The environment name is the instance prefix followed by the setting name: + +If you ran the PostgreSQL example in the same shell, clear its queue address overrides first. They are PostgreSQL specific and break the SQS addresses, and the file system paths do not apply to S3. + +```bash +unset TestingTool__ServiceControlInputQueue TestingTool__MonitoringQueueName +unset SC_CONTAINER_TESTS_PRIMARY_MESSAGEBODY_FILESYSTEM_STORAGEPATH SC_CONTAINER_TESTS_AUDIT_MESSAGEBODY_FILESYSTEM_STORAGEPATH +RUN='' +export SC_CONTAINER_TESTS_MOUNTS="$PWD/aws:/aws:ro" +export SC_CONTAINER_TESTS_PRIMARY_MESSAGEBODY_S3_KEYPREFIX="sc-smoke-$RUN/primary/" +export SC_CONTAINER_TESTS_AUDIT_MESSAGEBODY_S3_KEYPREFIX="sc-smoke-$RUN/audit/" +# The in-process tool runs on the host, so these point at the host paths. +export AWS_PROFILE=smoke-test +export AWS_CONFIG_FILE="$PWD/aws/config" +export AWS_SHARED_CREDENTIALS_FILE="$PWD/aws/credentials" +export SC_CONTAINER_TESTS_TAG='' +export SC_CONTAINER_TESTS_CONFIG="$PWD/containers.env" +dotnet test tools/testing-tool/TestingTool.ContainerSmokeTests +``` + +Credentials always come from the AWS default credential chain, never from the connection string. Temporary credentials expire. A run that fails with access denied or expired token errors in the container logs or in the check details has a credential or permission problem and says nothing about the code under test. Refresh the credentials and run again with a new run name. + +The `error-large-body` smoke check fails a message with a body of about 190 KiB after serialization. The transport carries it with the current check, and it is above the 100 KB external body storage threshold, so the primary stores the body under its S3 prefix. + +### Cleanup + +The suite removes its containers and network. It does not remove anything it created in your accounts: + +- SQS queues and SNS topics whose names start with the run's prefix. ServiceControl and the tests' endpoints create them when they start. +- Objects under the run's S3 key prefixes. +- The tables and schemas that ServiceControl created in the database, and the local PostgreSQL container. + +Delete them by prefix after the run, with credentials that are allowed to. diff --git a/tools/testing-tool/TestingTool.ContainerSmokeTests/TestingTool.ContainerSmokeTests.csproj b/tools/testing-tool/TestingTool.ContainerSmokeTests/TestingTool.ContainerSmokeTests.csproj new file mode 100644 index 0000000000..1e17ae889c --- /dev/null +++ b/tools/testing-tool/TestingTool.ContainerSmokeTests/TestingTool.ContainerSmokeTests.csproj @@ -0,0 +1,22 @@ + + + + net10.0 + false + + + + + + + + + + + + + + + + + diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs index e9686d816b..fd3beef63a 100644 --- a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeChecksTests.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Options; using NServiceBus; using NUnit.Framework; -using ServiceControl.Plugin.CustomChecks.Messages; using TestingTool.Smoke; namespace TestingTool.Tests.Smoke; @@ -48,36 +47,6 @@ static async Task Run(SmokeChecks checks, string id, SmokeContext context) } } - IEnumerable Reports => session.Sent.Select(s => s.Message).OfType(); - - [Test] - public async Task Custom_check_passes_when_the_api_shows_this_runs_check_fail_then_pass() - { - var checks = CreateChecks(r => - { - var failed = r.RequestUri!.Query.Contains("status=fail"); - var own = Reports.LastOrDefault(); - var ownIsListed = own is not null && own.HasFailed == failed; - var entry = ownIsListed ? $$"""{"id":"u1","custom_check_id":"{{own!.CustomCheckId}}","status":"{{(failed ? "fail" : "pass")}}","failure_reason":{{JsonSerializer.Serialize(own.FailureReason)}},"reported_at":"2026-01-01T00:00:00Z"}""" : ""; - return r.Method == HttpMethod.Delete ? FakeHttpHandler.Status(HttpStatusCode.Accepted) : FakeHttpHandler.Json($"[{entry}]"); - }); - - await Run(checks, "custom-check-fail-then-pass", Context()); - - Assert.That(Reports.Select(r => r.HasFailed).ToArray(), Is.EqualTo(new[] { true, false })); - Assert.That(Reports.Select(r => r.CustomCheckId).Distinct().Single(), Is.EqualTo($"Smoke.{RunId}")); - } - - [Test] - public void Custom_check_ignores_a_failed_check_from_another_run() - { - var checks = CreateChecks(r => FakeHttpHandler.Json("""[{"id":"u0","custom_check_id":"Smoke.smoke-older","status":"fail","failure_reason":"x","reported_at":"2026-01-01T00:00:00Z"}]""")); - - var ex = Assert.ThrowsAsync(() => Run(checks, "custom-check-fail-then-pass", Context())); - - Assert.That(ex!.Message, Does.Contain($"no failed check with id Smoke.{RunId}")); - } - [Test] public void Audit_check_fails_without_a_remote_audit_instance() { @@ -115,6 +84,56 @@ public async Task Retry_single_retries_only_the_chosen_message_in_a_group_unique Assert.That(server.Retried, Has.Count.EqualTo(1)); } + [Test] + public async Task Error_large_body_sends_a_body_above_the_storage_threshold_and_reads_it_whole() + { + var server = new FailureServer(session, observations); + var checks = CreateChecks(server.Handle); + var context = Context(); + + await Run(checks, "error-large-body", context); + + var sent = (SmokeMessage)session.Sent.Single().Message; + Assert.That(sent.Note.Length, Is.GreaterThanOrEqualTo(150 * 1024)); + Assert.That(JsonSerializer.SerializeToUtf8Bytes(sent).Length, Is.GreaterThan(100 * 1024).And.LessThanOrEqualTo(200 * 1024)); + Assert.That(context.Detail, Does.Contain("SHA-256")); + } + + [Test] + public void Error_large_body_fails_when_the_stored_body_is_cut_short_of_the_text_sent() + { + var server = new FailureServer(session, observations) { StoredBodyLimit = 120 * 1024 }; + var checks = CreateChecks(server.Handle); + + var ex = Assert.ThrowsAsync(() => Run(checks, "error-large-body", Context())); + + Assert.That(ex!.Message, Does.Contain("cut short")); + } + + [Test] + public void A_stored_body_with_the_length_sent_but_other_text_fails_the_check() + { + var ex = Assert.Throws(() => SmokeChecks.RequireWholeBody(200 * 1024, new string('a', 1000), new string('b', 1000), "id1")); + + Assert.That(ex!.Message, Does.Contain("text differs")); + } + + [Test] + public void A_stored_body_with_fewer_characters_than_sent_fails_the_check() + { + var ex = Assert.Throws(() => SmokeChecks.RequireWholeBody(200 * 1024, "ab", "abc", "id1")); + + Assert.That(ex!.Message, Does.Contain("were sent")); + } + + [Test] + public void A_body_at_or_below_the_storage_threshold_does_not_pass() + { + var ex = Assert.Throws(() => SmokeChecks.RequireWholeBody(100 * 1024, "a", "a", "id1")); + + Assert.That(ex!.Message, Does.Contain("does not exceed")); + } + [Test] public void Retry_single_fails_when_the_retry_also_resolves_the_sibling() { @@ -186,6 +205,9 @@ sealed class FailureServer(FakeMessageSession session, SmokeObservations observa public bool RetryResolvesEverything { get; init; } public bool HandlesRetries { get; init; } = true; + + /// Serves the stored body cut to this many bytes, as a storage threshold bug would. + public int? StoredBodyLimit { get; init; } public List Retried { get; } = []; public List Archived { get; } = []; @@ -222,6 +244,12 @@ public HttpResponseMessage Handle(HttpRequestMessage request) return FakeHttpHandler.Status(HttpStatusCode.Accepted); } + if (path.StartsWith("/api/messages/") && path.EndsWith("/body")) + { + var bytes = JsonSerializer.SerializeToUtf8Bytes(failing.Single().Message); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(StoredBodyLimit is { } limit ? bytes[..limit] : bytes) }; + } + var id = path.Split('/')[3]; if (path.EndsWith("/retry")) { diff --git a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs index 6ab908db1a..69ad4f17fc 100644 --- a/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs +++ b/tools/testing-tool/TestingTool.Tests/Smoke/SmokeEndpointLifecycleTests.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; using NServiceBus; using NServiceBus.Features; using Microsoft.Extensions.Logging.Abstractions; @@ -30,8 +31,8 @@ public void TearDown() } } - Task Start(string name, Action? configure = null, CancellationToken ct = default) => - SmokeEndpoint.Start(name, config => config.UseTransport(new LearningTransport { StorageDirectory = storage }), configure, observations, "error", ct); + Task Start(string name, Action? configure = null, CancellationToken ct = default, Action? services = null) => + SmokeEndpoint.Start(name, config => config.UseTransport(new LearningTransport { StorageDirectory = storage }), configure, observations, "error", ct, services); static Dictionary Headers(string metadataFile) => JsonSerializer.Deserialize>(File.ReadAllText(metadataFile))!; @@ -98,6 +99,35 @@ public async Task The_heartbeat_plugin_sends_heartbeats_to_the_service_control_q await WaitUntil(() => QueueHeaders("Particular.ServiceControl").Any(h => h["NServiceBus.EnclosedMessageTypes"] == "ServiceControl.Plugin.Heartbeat.Messages.EndpointHeartbeat")); } + [Test] + public async Task The_custom_checks_plugin_runs_the_smoke_check_and_reports_it_failing_then_passing_to_the_service_control_queue() + { + Directory.CreateDirectory(Path.Combine(storage, "Particular.ServiceControl")); + var state = new SmokeCustomCheckState("Smoke.run1"); + + await using var endpoint = await Start("Smoke.CustomCheck", config => + { + config.AddCustomCheck(); + config.ReportCustomChecksTo("Particular.ServiceControl", SmokeCustomCheck.ReportTimeToLive); + }, services: services => services.AddSingleton(state)); + + var bodies = Path.Combine(storage, "Particular.ServiceControl", ".bodies"); + IEnumerable<(bool Failed, string? Reason)> Reports() => (Directory.Exists(bodies) ? Directory.GetFiles(bodies, "*.body.txt") : []) + .Select(f => JsonSerializer.Deserialize(File.ReadAllText(f))) + .Where(r => r.GetProperty("CustomCheckId").GetString() == "Smoke.run1") + .Select(r => (r.GetProperty("HasFailed").GetBoolean(), r.GetProperty("FailureReason").GetString())); + + await WaitUntil(() => Reports().Any(r => r.Failed)); + Assert.That(Reports().First(r => r.Failed).Reason, Is.EqualTo(state.FailureReason)); + + state.Pass(); + await WaitUntil(() => Reports().Any(r => !r.Failed)); + + // The plugin reports on every run, and each report carries the time to live that the cleanup waits for. + var metadata = Directory.GetFiles(Path.Combine(storage, "Particular.ServiceControl"), "*.metadata.txt").Select(f => Headers(f)); + Assert.That(metadata.Select(h => h["NServiceBus.Transport.Learning.TimeToBeReceived"]).Distinct().Single(), Is.EqualTo(SmokeCustomCheck.ReportTimeToLive.ToString())); + } + [Test] public async Task The_metrics_plugin_reports_processing_time_of_handled_messages_with_scanning_disabled() { diff --git a/tools/testing-tool/TestingTool.slnx b/tools/testing-tool/TestingTool.slnx index a1e67750a1..c1d1d52817 100644 --- a/tools/testing-tool/TestingTool.slnx +++ b/tools/testing-tool/TestingTool.slnx @@ -4,4 +4,5 @@ + \ No newline at end of file diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs b/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs index 76bc92aa02..f0faffa0ec 100644 --- a/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs +++ b/tools/testing-tool/TestingTool/Smoke/SmokeApiClient.cs @@ -53,6 +53,13 @@ public Task> GetGroupErrors(string groupId, Cancellation return response.StatusCode == HttpStatusCode.NotFound ? null : await Read(response, ct); } + /// Reads the body of a failed message from the primary, which serves it from external body storage. + public async Task GetFailedMessageBody(string id, CancellationToken ct) + { + using var response = await Send(HttpMethod.Get, $"/api/messages/{UriEscape(id)}/body", null, ct, HttpStatusCode.OK); + return await response.Content.ReadAsByteArrayAsync(ct); + } + public Task RetryMessage(string id, CancellationToken ct) => Run(HttpMethod.Post, $"/api/errors/{UriEscape(id)}/retry", null, ct, HttpStatusCode.Accepted); public Task RetryGroup(string groupId, CancellationToken ct) => diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs b/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs index 77bafc24aa..497601f58f 100644 --- a/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs +++ b/tools/testing-tool/TestingTool/Smoke/SmokeChecks.cs @@ -1,8 +1,11 @@ +using System.Security.Cryptography; +using System.Text; using System.Text.Json; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; +using Microsoft.Extensions.DependencyInjection; using NServiceBus; -using ServiceControl.Plugin.CustomChecks.Messages; +using TestingTool.Scenarios; using static TestingTool.Smoke.SmokeApiClient; namespace TestingTool.Smoke; @@ -26,7 +29,7 @@ public sealed class SmokeChecks( public IReadOnlyList Create() => [ new("custom-check-fail-then-pass", "Custom check fails, then passes", - "Reports a failed then a passed custom check with a run-specific id to the primary input queue, and reads it from GET /api/customchecks?status=fail and ?status=pass.", + "Starts a real endpoint named after the run with the NServiceBus.CustomChecks plugin and one check that fails, then passes. The plugin reports to the primary input queue. Reads the check from GET /api/customchecks?status=fail and ?status=pass.", CustomCheckFailThenPass), new("heartbeat-beating-then-dead", "Heartbeat is healthy, then the endpoint is reported dead", "Starts a real endpoint named after the run with the NServiceBus.Heartbeat plugin and reads heartbeat_information.reported_status from GET /api/endpoints: beating, then dead after the endpoint host stops. Takes about a minute.", @@ -46,6 +49,9 @@ public IReadOnlyList Create() => new("integration-event", "MessageFailed integration event is received", "Subscribes this endpoint to ServiceControl.Contracts.MessageFailed, fails one message, and matches the published event by a run header and the failed message id. Needs SERVICECONTROL_ENABLEEXTERNALINTEGRATIONSPUBLISHING=true on the instance that ingests errors.", IntegrationEvent), + new("error-large-body", "Large failed message body is stored and read back whole", + "Fails one message whose body is 150 KiB of generated text (about 190 KiB serialized, above the 100 KB external body storage threshold and under Azure Service Bus Standard's 256 KiB limit), then reads GET /api/messages/{id}/body from the primary and compares the text, length and SHA-256 with what was sent.", + ErrorLargeBody), new("retry-single", "Retry one failed message", "Fails two messages in a run-specific group, retries one with POST /api/errors/{id}/retry, and checks that it was handled and resolved while the other stayed unresolved.", RetrySingle), @@ -80,10 +86,11 @@ public IReadOnlyList Create() => async Task CustomCheckFailThenPass(SmokeContext ctx, CancellationToken ct) { var checkId = $"Smoke.{ctx.RunId}"; - var hostId = Guid.NewGuid(); - var reason = $"Smoke run {ctx.RunId} reports a failure"; + var state = new SmokeCustomCheckState(checkId); + // Wait for queued reports to expire after endpoint shutdown; reports already being processed can still arrive. ctx.OnCleanup(async token => { + await Task.Delay(SmokeCustomCheck.ReportTimeToLive, token); foreach (var status in new[] { "fail", "pass" }) { foreach (var view in (await api.GetCustomChecks(status, token)).Where(c => c.CustomCheckId == checkId)) @@ -93,18 +100,23 @@ async Task CustomCheckFailThenPass(SmokeContext ctx, CancellationToken ct) } }); - await SendCustomCheck(checkId, hostId, ctx.RunId, failed: true, reason, ct); + await StartEndpoint(ctx, $"TestingTool.Smoke.{ctx.RunId}", config => + { + config.AddCustomCheck(); + config.ReportCustomChecksTo(options.Value.ServiceControlInputQueue, SmokeCustomCheck.ReportTimeToLive); + }, ct, services => services.AddSingleton(state)); + await ctx.WaitFor("the custom check to appear as failed", async token => { var checks = (await api.GetCustomChecks("fail", token)).Where(c => c.CustomCheckId == checkId).ToList(); return checks.Count == 0 ? PollResult.Waiting($"no failed check with id {checkId}") - : checks[0].FailureReason == reason + : checks[0].FailureReason == state.FailureReason ? PollResult.Done(checks[0]) : PollResult.Waiting($"failure reason was '{checks[0].FailureReason}'"); }, ct); - await SendCustomCheck(checkId, hostId, ctx.RunId, failed: false, null, ct); + state.Pass(); await ctx.WaitFor("the custom check to pass and leave the failed list", async token => { var passed = (await api.GetCustomChecks("pass", token)).Any(c => c.CustomCheckId == checkId); @@ -112,24 +124,7 @@ await ctx.WaitFor("the custom check to pass and leave the failed list", async to return passed && !stillFailed ? PollResult.Done(true) : PollResult.Waiting($"passed list has it: {passed}, failed list has it: {stillFailed}"); }, ct); - ctx.Detail = $"Custom check {checkId} was reported failed, then passed."; - } - - Task SendCustomCheck(string checkId, Guid hostId, string runId, bool failed, string? reason, CancellationToken ct) - { - var send = new SendOptions(); - send.SetDestination(options.Value.ServiceControlInputQueue); - return session.Send(new ReportCustomCheckResult - { - HostId = hostId, - CustomCheckId = checkId, - Category = "Smoke", - HasFailed = failed, - FailureReason = reason, - ReportedAt = DateTime.UtcNow, - EndpointName = $"TestingTool.Smoke.{runId}", - Host = "TestingTool.Smoke" - }, send, ct); + ctx.Detail = $"Custom check {checkId} was run by the NServiceBus.CustomChecks plugin, reported failed, then passed."; } async Task HeartbeatBeatingThenDead(SmokeContext ctx, CancellationToken ct) @@ -158,9 +153,9 @@ public void DeleteEndpointRecords(SmokeContext ctx, params string[] names) => }); /// Starts a run-scoped endpoint on the transport of the load endpoint. The cleanup stops it if the check did not. - async Task StartEndpoint(SmokeContext ctx, string name, Action? configure, CancellationToken ct) + async Task StartEndpoint(SmokeContext ctx, string name, Action? configure, CancellationToken ct, Action? configureServices = null) { - var endpoint = await SmokeEndpoint.Start(name, config => NServiceBusEndpointExtensions.ConfigureTransport(config, configuration), configure, observations, options.Value.ErrorQueueName, ct); + var endpoint = await SmokeEndpoint.Start(name, config => NServiceBusEndpointExtensions.ConfigureTransport(config, configuration), configure, observations, options.Value.ErrorQueueName, ct, configureServices); ctx.OnEndpointStop(token => endpoint.StopAsync(token)); return endpoint; } @@ -322,6 +317,53 @@ async Task IntegrationEvent(SmokeContext ctx, CancellationToken ct) ctx.Detail = $"MessageFailed was received for failed message {failed.Id}."; } + /// The body size of the load scenario that exercises external body storage. + const int LargeBodyTextBytes = 150 * 1024; + + /// The documented default of MaxBodySizeToStore. + const int BodyStorageThresholdBytes = 100 * 1024; + + async Task ErrorLargeBody(SmokeContext ctx, CancellationToken ct) + { + var text = MessageTextGenerator.GenerateBody(0, LargeBodyTextBytes); + var failures = await FailMessages(ctx, "large-body", 1, note: text, ct: ct); + var failed = (await WaitForFailures(ctx, failures, ct)).Messages[0]; + + var stored = await api.GetFailedMessageBody(failed.Id, ct); + SmokeMessage received; + try + { + received = JsonSerializer.Deserialize(stored)!; + } + catch (JsonException ex) + { + throw new SmokeCheckFailedException($"The stored body of failed message {failed.Id} has {stored.Length} bytes and is not the message sent, it may be cut short: {ex.Message}"); + } + + RequireWholeBody(stored.Length, received.Note, text, failed.Id); + + ctx.Detail = $"The stored body of failed message {failed.Id} has {stored.Length} bytes, above the {BodyStorageThresholdBytes} byte threshold, and carries all {text.Length} characters of the text sent (SHA-256 {Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text)))[..16]})."; + } + + /// A body cut at the storage threshold, or altered, fails here instead of passing on presence. + public static void RequireWholeBody(int storedBytes, string receivedText, string sentText, string failedId) + { + if (storedBytes <= BodyStorageThresholdBytes) + { + throw new SmokeCheckFailedException($"The body of failed message {failedId} has {storedBytes} bytes, which does not exceed the {BodyStorageThresholdBytes} byte threshold, so it does not exercise external storage"); + } + + if (receivedText.Length != sentText.Length) + { + throw new SmokeCheckFailedException($"The body of failed message {failedId} carries {receivedText.Length} characters of text, {sentText.Length} were sent"); + } + + if (!SHA256.HashData(Encoding.UTF8.GetBytes(receivedText)).AsSpan().SequenceEqual(SHA256.HashData(Encoding.UTF8.GetBytes(sentText)))) + { + throw new SmokeCheckFailedException($"The body of failed message {failedId} has the length sent, but its text differs"); + } + } + async Task RetrySingle(SmokeContext ctx, CancellationToken ct) { var failures = await FailMessages(ctx, "retry-single", 2, ct: ct); @@ -394,7 +436,7 @@ async Task RetryThroughRedirect(SmokeContext ctx, CancellationToken ct) var from = source.MainAddress; var to = target.MainAddress; - var failures = await FailMessages(ctx, "redirect", 1, source.MainAddress, ct); + var failures = await FailMessages(ctx, "redirect", 1, source.MainAddress, ct: ct); var failed = (await WaitForFailures(ctx, failures, ct)).Messages[0]; if (failed.QueueAddress != from) { @@ -455,7 +497,7 @@ sealed record FailureGroup(string GroupId, IReadOnlyList Mess /// Sends failing messages that ServiceControl groups under an exception type unique to this check of /// this run. The group therefore holds only these messages, so a group retry cannot touch anything else. /// - async Task FailMessages(SmokeContext ctx, string checkId, int count, string? destination = null, CancellationToken ct = default) + async Task FailMessages(SmokeContext ctx, string checkId, int count, string? destination = null, string? note = null, CancellationToken ct = default) { var exceptionType = $"TestingTool.Smoke.Failure_{ctx.RunId}_{checkId}".Replace('-', '_'); var messageIds = new List(); @@ -474,7 +516,7 @@ async Task FailMessages(SmokeContext ctx, string checkId, int count, s RunId = ctx.RunId, Marker = marker, Fail = true, - Note = checkId, + Note = note ?? checkId, FailureType = exceptionType }, messageId, destination: destination, ct: ct); } diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeCustomCheck.cs b/tools/testing-tool/TestingTool/Smoke/SmokeCustomCheck.cs new file mode 100644 index 0000000000..ada666cba8 --- /dev/null +++ b/tools/testing-tool/TestingTool/Smoke/SmokeCustomCheck.cs @@ -0,0 +1,29 @@ +using NServiceBus.CustomChecks; + +namespace TestingTool.Smoke; + +/// Tells the of one run whether to fail. It starts failing and the smoke check switches it to passing. +public sealed class SmokeCustomCheckState(string checkId) +{ + volatile bool failing = true; + + public string CheckId { get; } = checkId; + + public string FailureReason => $"Smoke check {CheckId} fails on purpose"; + + public bool IsFailing => failing; + + public void Pass() => failing = false; +} + +/// A real NServiceBus.CustomChecks check that the plugin runs every and reports to ServiceControl. +public sealed class SmokeCustomCheck(SmokeCustomCheckState state) + : CustomCheck(state.CheckId, "Smoke", RepeatAfter) +{ + public static readonly TimeSpan RepeatAfter = TimeSpan.FromSeconds(2); + + public static readonly TimeSpan ReportTimeToLive = 4 * RepeatAfter; + + public override Task PerformCheck(CancellationToken cancellationToken = default) => + Task.FromResult(state.IsFailing ? CheckResult.Failed(state.FailureReason) : CheckResult.Pass); +} diff --git a/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs b/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs index 1a7cc2523d..a961cda2c1 100644 --- a/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs +++ b/tools/testing-tool/TestingTool/Smoke/SmokeEndpoint.cs @@ -39,7 +39,8 @@ public static async Task Start( Action? configure, SmokeObservations observations, string errorQueue, - CancellationToken ct) + CancellationToken ct, + Action? configureServices = null) { var config = new EndpointConfiguration(name); config.AssemblyScanner().Disable = true; @@ -58,6 +59,7 @@ public static async Task Start( builder.Logging.SetMinimumLevel(LogLevel.Critical); builder.Services.AddSingleton(observations); builder.Services.AddSingleton(new SmokeEndpointIdentity(name)); + configureServices?.Invoke(builder.Services); builder.Services.AddNServiceBusEndpoint(config); var host = builder.Build(); diff --git a/tools/testing-tool/TestingTool/TestingTool.csproj b/tools/testing-tool/TestingTool/TestingTool.csproj index cfcbde204b..2f8431afac 100644 --- a/tools/testing-tool/TestingTool/TestingTool.csproj +++ b/tools/testing-tool/TestingTool/TestingTool.csproj @@ -14,6 +14,7 @@ +