Bundle: redb-route / tests/redb.Route.Tests.Exec (tests.redb.Route.Tests.Exec.txt), 4 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/tests/redb.Route.Tests.Exec/ExecRestartTests.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Exec/ExecRestartTests.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Exec;
namespace redb.Route.Tests.Exec;
///
/// A scheduled exec consumer keeps running the command after Stop() and Start() of the same route context:
/// the stop ends the schedule of the cached endpoint, the start runs it again.
///
// Never in parallel with ExecTraceTests, whose span probe would take these ticks for its own.
[Collection("ExecScheduledTicks")]
public sealed class ExecRestartTests
{
private static bool IsWindows => OperatingSystem.IsWindows();
private static string Shell => IsWindows ? "cmd" : "sh";
private static string EchoArgs => IsWindows ? "/c%20echo%20tick" : "-c%20echo%20tick";
private static async Task WaitForAsync(Func condition, string because)
{
var deadline = DateTime.UtcNow.AddSeconds(10);
while (!condition() && DateTime.UtcNow < deadline)
await Task.Delay(50);
condition().Should().BeTrue(because);
}
[Fact]
public async Task Schedule_runs_after_the_context_is_stopped_and_started_again()
{
var ticks = 0;
await using var ctx = new RouteContext();
ctx.AddComponent(new ExecComponent());
ctx.AddRoutes(r => r.From($"exec://run?command={Shell}&args={EchoArgs}&schedule=200ms")
.Process(_ => Interlocked.Increment(ref ticks)));
await ctx.Start();
await WaitForAsync(() => Volatile.Read(ref ticks) >= 1, "scheduled exec runs the command");
await ctx.Stop();
var before = Volatile.Read(ref ticks);
await ctx.Start();
await WaitForAsync(() => Volatile.Read(ref ticks) > before, "exec runs the command again after a restart");
}
}
Path: redb-route/tests/redb.Route.Tests.Exec/ExecTests.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Exec/ExecTests.cs
----
using System.Diagnostics;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Exec;
namespace redb.Route.Tests.Exec;
///
/// Unit tests for the exec connector. They actually spawn host processes — we use
/// portable commands (cmd.exe / sh) and short-running probes so the suite stays fast
/// and works on every CI runner.
///
public sealed class ExecProducerTests
{
private static bool IsWindows => OperatingSystem.IsWindows();
private static string EchoCmd => IsWindows ? "cmd" : "sh";
private static string[] EchoArgs(string text) =>
IsWindows ? new[] { "/c", "echo", text } : new[] { "-c", $"echo {text}" };
///
/// The same arguments as one Args string. The producer splits it on spaces outside double quotes, so the script of
/// sh -c is quoted: unquoted, -c echo hello ran a bare echo with hello as $0.
///
private static string EchoArgsLine(string text) =>
IsWindows ? $"/c echo {text}" : $"-c \"echo {text}\"";
private static (ExecProducer producer, ExecEndpoint endpoint) NewProducer(ExecEndpointOptions options)
{
var component = new ExecComponent();
var uri = new EndpointUri("exec", "run", "exec://run", new Dictionary());
var endpoint = new ExecEndpoint(uri, component, options);
return (new ExecProducer(endpoint, options), endpoint);
}
private static IExchange NewExchange(string body = "")
=> Exchange.Create(new Message(body), scopeFactory: null);
[Fact]
public async Task Process_RunsCommand_AndPopulatesJsonBodyAndHeaders()
{
var options = new ExecEndpointOptions
{
Command = EchoCmd,
Args = EchoArgsLine("hello"),
TimeoutMs = 5000
};
var (producer, _) = NewProducer(options);
await producer.Start();
var exchange = NewExchange();
await producer.Process(exchange);
exchange.Out.Should().NotBeNull();
var payload = JsonSerializer.Deserialize((string)exchange.Out!.Body!);
payload.GetProperty("exitCode").GetInt32().Should().Be(0);
payload.GetProperty("stdout").GetString().Should().Contain("hello");
payload.GetProperty("timedOut").GetBoolean().Should().BeFalse();
exchange.Out.Headers[ExecHeaders.ExitCode].Should().Be(0);
exchange.Out.Headers[ExecHeaders.TimedOut].Should().Be(false);
exchange.Out.Headers[ExecHeaders.CommandLine].Should().NotBeNull();
}
[Fact]
public async Task Process_HonoursAllowlist_AndRejectsForeignCommand()
{
var options = new ExecEndpointOptions
{
Command = EchoCmd,
Args = EchoArgsLine("nope"),
AllowedCommands = "git,ls",
TimeoutMs = 5000
};
var (producer, _) = NewProducer(options);
await producer.Start();
var act = () => producer.Process(NewExchange());
await act.Should().ThrowAsync()
.WithMessage("*not on the allowlist*");
}
[Fact]
public async Task Process_AllowlistMatch_IsCaseInsensitiveOnFileNameOnly()
{
var options = new ExecEndpointOptions
{
Command = EchoCmd,
Args = EchoArgsLine("ok"),
AllowedCommands = IsWindows ? "CMD" : "SH",
TimeoutMs = 5000
};
var (producer, _) = NewProducer(options);
await producer.Start();
await producer.Process(NewExchange());
// No exception => allowlist accepted the command despite case mismatch.
}
[Fact]
public async Task Process_HonoursTimeout_AndKillsProcess()
{
// sleep 5 seconds — but we cap at 200ms.
var options = new ExecEndpointOptions
{
Command = IsWindows ? "cmd" : "sh",
Args = IsWindows ? "/c ping -n 6 127.0.0.1 > nul" : "-c \"sleep 5\"",
TimeoutMs = 200
};
var (producer, _) = NewProducer(options);
await producer.Start();
var sw = Stopwatch.StartNew();
var exchange = NewExchange();
await producer.Process(exchange);
sw.Stop();
// Should bail out very quickly (< 2s) — well under the 5s sleep.
sw.ElapsedMilliseconds.Should().BeLessThan(2_000);
exchange.Out!.Headers[ExecHeaders.TimedOut].Should().Be(true);
exchange.Out.Headers[ExecHeaders.ExitCode].Should().Be(-1);
}
[Fact]
public async Task Process_AcceptsJsonBody_OverridingUriOptions()
{
var options = new ExecEndpointOptions
{
Command = "should-not-run",
AllowedCommands = $"should-not-run,{(IsWindows ? "cmd" : "sh")}",
TimeoutMs = 5000
};
var (producer, _) = NewProducer(options);
await producer.Start();
var argsJson = JsonSerializer.Serialize(EchoArgs("hi-from-json"));
var jsonBody = $$"""
{"command": "{{EchoCmd}}", "args": {{argsJson}} }
""";
var exchange = NewExchange(jsonBody);
await producer.Process(exchange);
var payload = JsonSerializer.Deserialize((string)exchange.Out!.Body!);
payload.GetProperty("stdout").GetString().Should().Contain("hi-from-json");
}
[Fact]
public async Task Process_AcceptsHeaderInputs_OverridingUriOptions()
{
var options = new ExecEndpointOptions
{
Command = "should-not-run",
AllowedCommands = $"should-not-run,{(IsWindows ? "cmd" : "sh")}",
TimeoutMs = 5000
};
var (producer, _) = NewProducer(options);
await producer.Start();
var exchange = NewExchange();
exchange.In.Headers[ExecHeaders.Command] = EchoCmd;
exchange.In.Headers[ExecHeaders.Args] = EchoArgsLine("hi-from-header");
await producer.Process(exchange);
var payload = JsonSerializer.Deserialize((string)exchange.Out!.Body!);
payload.GetProperty("stdout").GetString().Should().Contain("hi-from-header");
}
[Fact]
public async Task Process_PlainTextOutput_WhenJsonResponseDisabled()
{
var options = new ExecEndpointOptions
{
Command = EchoCmd,
Args = EchoArgsLine("plain-out"),
JsonResponse = false,
CaptureStderrInBody = false,
TimeoutMs = 5000
};
var (producer, _) = NewProducer(options);
await producer.Start();
var exchange = NewExchange();
await producer.Process(exchange);
((string)exchange.Out!.Body!).Should().Contain("plain-out");
exchange.Out.ContentType.Should().Be("text/plain");
}
[Fact]
public async Task Process_NoCommand_Throws()
{
var options = new ExecEndpointOptions { TimeoutMs = 5000 };
var (producer, _) = NewProducer(options);
await producer.Start();
var act = () => producer.Process(NewExchange());
await act.Should().ThrowAsync()
.WithMessage("*no command resolved*");
}
}
public sealed class ExecEndpointOptionsTests
{
[Fact]
public void Validate_RejectsNegativeTimeout()
{
var o = new ExecEndpointOptions { TimeoutMs = -1 };
var act = () => o.Validate();
act.Should().Throw().WithMessage("*TimeoutMs*");
}
[Fact]
public void Validate_RejectsNonPositiveByteCaps()
{
new ExecEndpointOptions { MaxStdoutBytes = 0 }
.Invoking(o => o.Validate()).Should().Throw();
new ExecEndpointOptions { MaxStderrBytes = 0 }
.Invoking(o => o.Validate()).Should().Throw();
}
[Fact]
public void Validate_AcceptsZeroTimeoutAsUnlimited()
{
var o = new ExecEndpointOptions { TimeoutMs = 0 };
var act = () => o.Validate();
act.Should().NotThrow();
}
}
public sealed class ExecConsumerTests
{
[Theory]
[InlineData("500ms", 500)]
[InlineData("30s", 30_000)]
[InlineData("5m", 5 * 60 * 1000)]
[InlineData("1h", 60 * 60 * 1000)]
public void ParseInterval_AcceptsAllSupportedUnits(string schedule, int expectedMs)
{
var ts = ExecConsumer.ParseInterval(schedule);
ts.Should().NotBeNull();
ts!.Value.TotalMilliseconds.Should().Be(expectedMs);
}
[Theory]
[InlineData("0 0 * * *")] // cron
[InlineData("five-seconds")]
[InlineData("")]
public void ParseInterval_RejectsNonIntervalSchedules(string schedule)
{
ExecConsumer.ParseInterval(schedule).Should().BeNull();
}
}
public sealed class ExecBuilderTests
{
[Fact]
public void Build_EmitsExpectedUri()
{
string uri = ExecDsl.Run("git")
.Args("status", "--short")
.AllowedCommands("git", "ls")
.WorkingDirectory("/srv/app")
.EnvOverride("LANG", "C")
.TimeoutMs(5000)
.MaxStdoutBytes(2048)
.Schedule("30s");
uri.Should().StartWith("exec://run?");
uri.Should().Contain("command=git");
uri.Should().Contain("args=status%20--short");
uri.Should().Contain("allowedCommands=git%2Cls");
uri.Should().Contain("workingDirectory=%2Fsrv%2Fapp");
uri.Should().Contain("environmentOverrides=LANG%3DC");
uri.Should().Contain("timeoutMs=5000");
uri.Should().Contain("maxStdoutBytes=2048");
uri.Should().Contain("schedule=30s");
}
[Fact]
public void Build_OmitsUnsetParameters()
{
string uri = ExecDsl.Run("ls").Build();
uri.Should().Be("exec://run?command=ls");
}
}
public sealed class ExecComponentTests
{
[Fact]
public void CreateEndpoint_ReadsOptionsFromUriParameters()
{
var component = new ExecComponent();
var rawParams = new Dictionary
{
["command"] = "git",
["allowedCommands"] = "git,ls",
["timeoutMs"] = "1234"
};
var uri = new EndpointUri("exec", "run", "exec://run", rawParams);
var endpoint = component.CreateEndpoint(uri) as ExecEndpoint;
endpoint.Should().NotBeNull();
endpoint!.EndpointOptions.Command.Should().Be("git");
endpoint.EndpointOptions.AllowedCommands.Should().Be("git,ls");
endpoint.EndpointOptions.TimeoutMs.Should().Be(1234);
}
[Fact]
public void Component_HasCorrectScheme()
{
new ExecComponent().Scheme.Should().Be("exec");
}
}
public sealed class ServiceCollectionExtensionsTests
{
[Fact]
public void AddRedbRouteExec_RegistersComponent()
{
var services = new ServiceCollection();
services.AddSingleton(Substitute.For());
services.AddRedbRouteExec();
var sp = services.BuildServiceProvider();
var component = sp.GetService();
component.Should().NotBeNull();
component!.Scheme.Should().Be("exec");
}
}
Path: redb-route/tests/redb.Route.Tests.Exec/ExecTraceTests.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Exec/ExecTraceTests.cs
----
using System.Diagnostics;
using redb.Route.Abstractions;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Exec;
using redb.Route.Telemetry;
using redb.Route.Tests.Telemetry;
namespace redb.Route.Tests.Exec;
///
/// A scheduled tick carries no trace context: the consumer opens a root span per tick, never a child of the activity the
/// timer loop inherited from whoever started it, with the run of the command and the route under it; a failed route
/// marks it red. The producer's client span is named after the resolved executable, file name only, and carries it as
/// process.executable.name; a refused command marks it red. EnableTelemetry=false opens none of these spans.
///
// One collection with ExecRestartTests: its schedule ticks the same shell, and the probe here counted those green tick
// spans as this route's.
[Collection("ExecScheduledTicks")]
public sealed class ExecTraceTests
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10);
private static bool IsWindows => OperatingSystem.IsWindows();
private static string Shell => IsWindows ? "cmd" : "sh";
private static string EchoArgs => IsWindows ? "/c%20echo%20tick" : "-c%20echo%20tick";
private readonly string _routeId = $"exec-trace-{Guid.NewGuid():N}";
private static string TickUri => $"exec://run?command={Shell}&args={EchoArgs}&schedule=200ms";
private static RouteTelemetryProbe Ticks()
=> new(a => a.Kind == ActivityKind.Consumer && RouteTelemetryProbe.Tag(a, "process.executable.name") == Shell);
private async Task StartTicking(Action step, bool telemetry = true)
{
var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry });
ctx.AddComponent(new ExecComponent());
ctx.AddRoutes(r => r.From(TickUri).RouteId(_routeId).Process(step));
using (new Activity("host startup").SetIdFormat(ActivityIdFormat.W3C).Start())
await ctx.Start();
return ctx;
}
private static async Task Until(Func done)
{
var deadline = DateTime.UtcNow + Wait;
while (!done() && DateTime.UtcNow < deadline)
await Task.Delay(50);
}
[Fact]
public async Task Each_tick_opens_a_root_span_with_the_command_run_under_it()
{
using var ticks = Ticks();
using var runs = new RouteTelemetryProbe(a => a.Kind == ActivityKind.Client
&& RouteTelemetryProbe.Tag(a, "process.executable.name") == Shell);
await using (await StartTicking(_ => { }))
await Until(() => ticks.Activities.Count >= 2);
ticks.Activities.Should().HaveCountGreaterThanOrEqualTo(2);
ticks.Activities.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId),
"a tick carries no context, so its span starts a trace rather than joining the host's");
var tick = ticks.Activities[0];
runs.Activities.Should().Contain(a => a.ParentSpanId == tick.SpanId, "the command runs inside the tick");
}
[Fact]
public async Task A_failed_route_marks_the_tick_span_red()
{
using var ticks = Ticks();
IReadOnlyList ended;
await using (await StartTicking(_ => throw new InvalidOperationException("route failed")))
{
await Until(() => ticks.Activities.Count >= 1);
ended = ticks.Activities; // before the stop: a tick the stop interrupts is not a failure
}
ended.Should().NotBeEmpty().And.OnlyContain(a => a.Status == ActivityStatusCode.Error);
}
[Fact]
public async Task A_tick_whose_command_is_refused_is_recorded_with_its_text()
{
const string uri = "exec://run?command=deploy-tool&allowedCommands=git&schedule=200ms";
await using var ctx = new RouteContext();
ctx.AddComponent(new ExecComponent());
ctx.AddRoutes(r => r.From(uri).RouteId(_routeId).Process(_ => { }));
await ctx.Start();
var endpoint = (IEndpointStatistics)ctx.GetEndpoint(uri);
await Until(() => endpoint.Errors > 0);
endpoint.Errors.Should().BeGreaterThan(0, "the refused command fails the tick");
endpoint.LastErrorMessage.Should().NotBeNullOrEmpty("the dashboard shows why the tick failed");
}
[Fact]
public async Task Tracing_off_opens_no_span()
{
// The tick spans and this route's spans; the producer tests of another class run commands of their own.
using var probe = new RouteTelemetryProbe(a =>
(a.Kind == ActivityKind.Consumer && RouteTelemetryProbe.Tag(a, "process.executable.name") == Shell)
|| RouteTelemetryProbe.Tag(a, RouteTelemetryProbe.RouteIdTag) == _routeId);
var ticked = new TaskCompletionSource();
await using (await StartTicking(_ => ticked.TrySetResult(), telemetry: false))
(await Task.WhenAny(ticked.Task, Task.Delay(Wait))).Should().Be(ticked.Task);
probe.Activities.Should().BeEmpty();
}
[Fact]
public async Task The_client_span_is_named_after_the_executable_file_and_a_refused_command_marks_it_red()
{
using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start();
using var runs = new RouteTelemetryProbe(a => a.Kind == ActivityKind.Client && a.TraceId == outer.TraceId);
await using var ctx = new RouteContext();
ctx.AddComponent(new ExecComponent());
await ctx.Start();
using var template = new ProducerTemplate(ctx);
template.Start();
var exchange = new Exchange(new Message(string.Empty));
exchange.In.Headers[ExecHeaders.Command] = Path.Combine(Path.GetTempPath(), "secrets", "deploy-tool");
var act = () => template.SendAsync("exec://run?allowedCommands=git", exchange);
await act.Should().ThrowAsync();
var run = runs.Activities.Should().ContainSingle().Subject;
run.DisplayName.Should().Be("exec deploy-tool", "the file name only, not the path");
run.GetTagItem("process.executable.name").Should().Be("deploy-tool");
run.Status.Should().Be(ActivityStatusCode.Error);
}
}
Path: redb-route/tests/redb.Route.Tests.Exec/redb.Route.Tests.Exec.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.Exec/redb.Route.Tests.Exec.csproj
----