Bundle: redb-route / tests/redb.Route.Tests.Telegram (tests.redb.Route.Tests.Telegram.txt), 8 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.Telegram/TelegramConnectionFactoryTests.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.Telegram/TelegramConnectionFactoryTests.cs ---- using redb.Route.Core; using redb.Route.Telegram; using redb.Route.Telegram.Fluent; namespace redb.Route.Tests.Telegram; /// /// The bot token — a full account credential — must be able to live in the registry /// instead of the endpoint URI, so it never reaches logs, telemetry, or the dashboard. /// public sealed class TelegramConnectionFactoryTests { private const string Token = "123456:AAH-TOPSECRET-BOT-TOKEN"; private static TelegramComponent Wire(string name, TelegramConnectionFactory factory) { var context = new RouteContext(); var component = new TelegramComponent(); context.AddComponent(component); context.AddToRegistry(name, factory); return component; } [Fact] public void Factory_SuppliesToken_WhenUriCarriesNone() { var component = Wire("support-bot", new TelegramConnectionFactory { Token = Token, SendTimeoutSeconds = 42 }); var uri = EndpointUriParser.Parse("telegram://receive?connectionFactory=support-bot"); // Validate() requires a token — this would throw if the factory were not applied first. var endpoint = (TelegramEndpoint)component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); uri.ToUriString().Should().NotContain(Token); uri.ToString().Should().NotContain(Token); } [Fact] public void ExplicitUriToken_WinsOverFactory() { var component = Wire("f", new TelegramConnectionFactory { Token = "from:FACTORY" }); var uri = EndpointUriParser.Parse("telegram://send?connectionFactory=f&token=from:URI&chatId=1"); var endpoint = (TelegramEndpoint)component.CreateEndpoint(uri); endpoint.Should().NotBeNull(); // the URI value survived the merge (endpoint construction validated it) uri.RawParameters["token"].Should().Be("from:URI"); } [Fact] public void MissingFactory_FailsLoud() { var context = new RouteContext(); var component = new TelegramComponent(); context.AddComponent(component); var uri = EndpointUriParser.Parse("telegram://receive?connectionFactory=absent&token=inline:TOKEN"); var act = () => component.CreateEndpoint(uri); // A typo in connectionFactory must fail loud, not fall back silently act.Should().Throw() .Which.Message.Should().Contain("absent"); } [Fact] public void TokenLessDsl_EmitsConnectionFactoryAndNoToken() { var uri = Tg.Receive().ConnectionFactory("support-bot").Build(); uri.Should().Be("telegram://receive?connectionFactory=support-bot"); uri.Should().NotContain("token="); } [Fact] public void TokenDsl_StillEmitsToken_Unchanged() { var uri = Tg.Send("abc:123").ChatId(42).Build(); uri.Should().Contain("token="); uri.Should().StartWith("telegram://send?token="); } [Fact] public void TheTokenInARequestUrlPath_IsMaskedInTheEndpointsLastErrorWarningAndRefusal() { // The Bot API puts the token in the path (https://api.telegram.org/bot/sendMessage), where no key=value // masking finds it; the endpoint knows its token and masks it by value, plain or URL-escaped. var component = Wire("support-bot", new TelegramConnectionFactory { Token = Token }); var endpoint = (TelegramEndpoint)component.CreateEndpoint(EndpointUriParser.Parse("telegram://send?connectionFactory=support-bot&chatId=1")); endpoint.RecordError(new HttpRequestException($"POST https://api.telegram.org/bot{Token}/sendMessage failed")); endpoint.RecordWarning($"retrying https://api.telegram.org/bot{Uri.EscapeDataString(Token)}/getUpdates"); endpoint.RecordRefused($"refused for bot{Token}"); endpoint.LastErrorMessage.Should().Be("POST https://api.telegram.org/bot****/sendMessage failed"); endpoint.LastWarningMessage.Should().Be("retrying https://api.telegram.org/bot****/getUpdates"); endpoint.LastRefusalMessage.Should().Be("refused for bot****"); } [Fact] public void ATokenGivenInTheUri_IsMaskedByValueToo() { var component = new TelegramComponent(); new RouteContext().AddComponent(component); var endpoint = (TelegramEndpoint)component.CreateEndpoint(EndpointUriParser.Parse($"telegram://send?token={Token}&chatId=1")); endpoint.RecordError(new HttpRequestException($"GET https://api.telegram.org/bot{Token}/getMe: 401")); endpoint.LastErrorMessage.Should().NotContain(Token).And.Contain("bot****/getMe"); } } Path: redb-route/tests/redb.Route.Tests.Telegram/TelegramDownloadTests.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.Telegram/TelegramDownloadTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telegram; using Telegram.Bot; using Telegram.Bot.Requests.Abstractions; using Telegram.Bot.Types; using Message = redb.Route.Core.Message; using TgDsl = redb.Route.Telegram.Fluent.Tg; namespace redb.Route.Tests.Telegram; /// /// The download producer mode: getFile plus the transfer, against a mocked /// — no network, no real bot. /// /// What the mode is for is one line of a voice route ("the user sent a recording, fetch it"), /// and everything worth testing about it is what happens when that line is not the happy path: /// which file id wins, and what stops a large upload from becoming a large allocation. /// /// public sealed class TelegramDownloadTests { private const string Token = "123456:AAAA-Test_Token"; private static TelegramEndpoint Endpoint(string extra = "") => (TelegramEndpoint)new TelegramComponent() .CreateEndpoint(EndpointUriParser.Parse($"telegram://download?token={Token}{extra}")); /// /// A client that answers getFile with and streams /// on the transfer, recording the file id it was asked for. /// private static ITelegramBotClient Client( TGFile file, byte[] payload, Action? onDownload = null) { var mock = Substitute.For(); mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(_ => Task.FromResult(file)); mock.DownloadFile(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(call => { onDownload?.Invoke(call.ArgAt(0)); var destination = call.ArgAt(1); destination.Write(payload, 0, payload.Length); return Task.CompletedTask; }); return mock; } private static TGFile File(string path = "voice/file_1.oga", long? size = null) => new() { FileId = "file-id", FileUniqueId = "unique-id", FilePath = path, FileSize = size }; private static async Task RunAsync( TelegramEndpoint endpoint, ITelegramBotClient client, IExchange exchange) { var producer = (TelegramProducer)endpoint.CreateProducer(); producer.UseTestClient(client); await producer.Start(); try { await producer.Process(exchange); return exchange; } finally { await producer.Stop(); } } // ── The ordinary case ───────────────────────────────────────────────────── [Fact] public async Task Download_PutsTheBytesInOut_AndDescribesTheFile() { var payload = new byte[] { 1, 2, 3, 4, 5 }; var exchange = new Exchange(new Message(null)); exchange.In.Headers[TelegramHeaders.AttachmentFileId] = "voice-file-id"; await RunAsync(Endpoint(), Client(File(), payload), exchange); exchange.Out.Should().NotBeNull("download is the one producer mode that returns something"); exchange.Out!.Body.Should().BeOfType().Which.Should().Equal(payload); exchange.Out.Headers[TelegramHeaders.FilePath].Should().Be("voice/file_1.oga"); exchange.Out.Headers[TelegramHeaders.FileSize].Should().Be(5L); exchange.Out.Headers[TelegramHeaders.FileUniqueId].Should().Be("unique-id"); } [Fact] public async Task Download_TakesTheAttachmentWithNoConfigurationAtAll() { string? requested = null; var exchange = new Exchange(new Message(null)); exchange.In.Headers[TelegramHeaders.AttachmentFileId] = "voice-file-id"; var client = Substitute.For(); client.SendRequest(Arg.Any>(), Arg.Any()) .Returns(call => { // The request object carries the file id the producer resolved; reading it back // is the only way to prove WHICH file was asked for, not merely that one was. requested = call.ArgAt>(0) .GetType().GetProperty("FileId")?.GetValue(call.ArgAt>(0)) as string; return Task.FromResult(File()); }); client.DownloadFile(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(_ => Task.CompletedTask); await RunAsync(Endpoint(), client, exchange); requested.Should().Be("voice-file-id", "the header the consumer already writes is what a voice route has, and needing to " + "restate it in the URI would make the common case the configured one"); } [Fact] public async Task Download_ExplicitHeaderBeatsTheAttachment() { string? requested = null; var exchange = new Exchange(new Message(null)); exchange.In.Headers[TelegramHeaders.AttachmentFileId] = "the-users-recording"; exchange.In.Headers[TelegramHeaders.FileId] = "the-one-we-asked-for"; var client = Client(File(), [7], onDownload: _ => { }); client.SendRequest(Arg.Any>(), Arg.Any()) .Returns(call => { var request = call.ArgAt>(0); requested = request.GetType().GetProperty("FileId")?.GetValue(request) as string; return Task.FromResult(File()); }); await RunAsync(Endpoint(), client, exchange); requested.Should().Be("the-one-we-asked-for", "a route that names the file it wants must be obeyed; the attachment is the default"); } // ── Refusals ────────────────────────────────────────────────────────────── [Fact] public async Task Download_RefusesADeclaredOversizeBeforeTransferring() { var transferred = false; var exchange = new Exchange(new Message(null)); exchange.In.Headers[TelegramHeaders.AttachmentFileId] = "big-file"; var client = Client(File(size: 5_000), new byte[5_000], onDownload: _ => transferred = true); var act = async () => await RunAsync(Endpoint("&maxDownloadBytes=1024"), client, exchange); await act.Should().ThrowAsync() .WithMessage("*ceiling*"); transferred.Should().BeFalse( "when Telegram states the size up front there is no reason to start a transfer that " + "is going to be rejected at the end of it"); } [Fact] public async Task Download_StopsATransferThatPassesTheCeilingWithNoDeclaredSize() { var exchange = new Exchange(new Message(null)); exchange.In.Headers[TelegramHeaders.AttachmentFileId] = "undeclared-file"; // file_size is optional in the Bot API. Trusting it alone would leave "how much memory // does one message cost" to the sender. var client = Client(File(size: null), new byte[4096]); var act = async () => await RunAsync(Endpoint("&maxDownloadBytes=1024"), client, exchange); await act.Should().ThrowAsync() .WithMessage("*ceiling*"); } [Fact] public async Task Download_WithNoFileIdAnywhere_SaysWhereToPutOne() { var exchange = new Exchange(new Message(null)); var act = async () => await RunAsync(Endpoint(), Client(File(), []), exchange); await act.Should().ThrowAsync() .WithMessage($"*{TelegramHeaders.AttachmentFileId}*"); } [Fact] public async Task Download_WithoutAFilePath_SaysTheFileIsUnreachable() { var exchange = new Exchange(new Message(null)); exchange.In.Headers[TelegramHeaders.AttachmentFileId] = "expired-file"; // getFile answers without a file_path for a file a bot may not download — expired, or // over the Bot API's own 20 MB ceiling. Failing here beats downloading from "null". var act = async () => await RunAsync(Endpoint(), Client(File(path: ""), []), exchange); await act.Should().ThrowAsync() .WithMessage("*file_path*"); } // ── URI and DSL ─────────────────────────────────────────────────────────── [Fact] public void Dsl_CarriesTheDownloadOptions() { var uri = TgDsl.Download(Token).FileId("abc").MaxDownloadBytes(2048).Build(); uri.Should().StartWith("telegram://download?"); uri.Should().Contain("fileId=abc").And.Contain("maxDownloadBytes=2048"); var parsed = EndpointUriParser.Parse(uri); var options = new TelegramEndpointOptions(); options.BindFromUri(parsed.RawParameters); ((TelegramEndpoint)new TelegramComponent().CreateEndpoint(parsed)).Mode.Should().Be("download"); options.FileId.Should().Be("abc"); options.MaxDownloadBytes.Should().Be(2048); } [Fact] public void Options_DefaultCeilingMatchesWhatTelegramItselfAllows() { // 20 MB is the Bot API's limit on what a bot may download, so the default refuses // exactly what Telegram would refuse — and no route has to know the number. new TelegramEndpointOptions().MaxDownloadBytes.Should().Be(20L * 1024 * 1024); } [Fact] public void Options_ANegativeCeilingIsRejectedAtStart() { var act = () => new TelegramComponent() .CreateEndpoint(EndpointUriParser.Parse($"telegram://download?token={Token}&maxDownloadBytes=-1")); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests.Telegram/TelegramIntegrationTests.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.Telegram/TelegramIntegrationTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Telegram; using Telegram.Bot; using Telegram.Bot.Exceptions; using Telegram.Bot.Polling; using Telegram.Bot.Requests; using Telegram.Bot.Requests.Abstractions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; using Message = redb.Route.Core.Message; using TgMessage = Telegram.Bot.Types.Message; namespace redb.Route.Tests.Telegram; /// /// In-process E2E tests for the Telegram connector — no network, no real bot. The producer runs /// against a mocked (send calls are extension methods over /// SendRequest, so NSubstitute can intercept them); the consumer is driven through its /// internal test seams (AttachToLiveBot=false + DeliverMessageForTest / /// RaiseErrorForTest). Each test proves one of the review's required fixes. /// public sealed class TelegramIntegrationTests { private const string Token = "123456:AAAA-Test_Token"; private static TelegramEndpoint Endpoint(string mode, string extra = "") => (TelegramEndpoint)new TelegramComponent() .CreateEndpoint(EndpointUriParser.Parse($"telegram://{mode}?token={Token}{extra}")); private static IProcessor Recorder(Func onEach) { var p = Substitute.For(); p.Process(Arg.Any(), Arg.Any()) .Returns(call => onEach(call.Arg())); return p; } private static TgMessage SentMessage(int id = 100) => new() { Id = id, Chat = new Chat { Id = 1, Type = ChatType.Private } }; private static TgMessage IncomingText(string text, long chatId = 123) => new() { Id = 10, Text = text, Chat = new Chat { Id = chatId, Type = ChatType.Private }, From = new User { Id = 7, FirstName = "Ann", Username = "ann" } }; // ── Consumer: roundtrip ─────────────────────────────────────────── [Fact] public async Task Consumer_Roundtrip_PopulatesBodyAndHeaders() { object? body = null; long? chatId = null; var consumer = (TelegramConsumer)Endpoint("receive").CreateConsumer(Recorder(ex => { body = ex.In.Body; chatId = ex.In.Headers.TryGetValue(TelegramHeaders.ChatId, out var v) ? (long?)v : null; return Task.CompletedTask; })); consumer.AttachToLiveBot = false; await consumer.Start(); try { await consumer.DeliverMessageForTest(IncomingText("hello"), UpdateType.Message, CancellationToken.None); body.Should().Be("hello"); chatId.Should().Be(123L); } finally { await consumer.Stop(); } } // ── Consumer: graceful drain (fix §3) ───────────────────────────── [Fact] public async Task Consumer_Stop_DrainsInFlight_NoHang() { var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var completed = false; var consumer = (TelegramConsumer)Endpoint("receive").CreateConsumer(Recorder(async _ => { entered.TrySetResult(); await release.Task; completed = true; })); consumer.AttachToLiveBot = false; await consumer.Start(); var delivery = Task.Run(() => consumer.DeliverMessageForTest(IncomingText("slow"), UpdateType.Message, CancellationToken.None)); await entered.Task; // in-flight incremented, processor blocked var sw = Stopwatch.StartNew(); var stop = consumer.Stop(); await Task.Delay(150); stop.IsCompleted.Should().BeFalse("Stop must wait for the in-flight message to drain"); release.SetResult(); // let the processor finish await stop; await delivery; sw.Stop(); completed.Should().BeTrue("the in-flight message was processed to completion, not force-cancelled"); sw.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(10), "drain must not burn the full 30s DrainTimeout — handlers detach in OnStopAccepting"); } // ── Consumer: error policy = at-most-once (fix §4) ──────────────── [Fact] public async Task Consumer_ProcessorThrows_MessageDropped_StreamSurvives() { var attempts = 0; var secondDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var consumer = (TelegramConsumer)Endpoint("receive").CreateConsumer(Recorder(_ => { if (Interlocked.Increment(ref attempts) == 1) throw new InvalidOperationException("boom"); secondDone.TrySetResult(); return Task.CompletedTask; })); consumer.AttachToLiveBot = false; await consumer.Start(); try { // First update: the processor throws — the consumer must swallow it (at-most-once, no rethrow). var act = async () => await consumer.DeliverMessageForTest(IncomingText("bad"), UpdateType.Message, CancellationToken.None); await act.Should().NotThrowAsync("a processor failure is logged as a drop, never rethrown into the poll loop"); // Second update proves the stream is still alive after the drop. await consumer.DeliverMessageForTest(IncomingText("good"), UpdateType.Message, CancellationToken.None); await secondDone.Task; attempts.Should().Be(2); } finally { await consumer.Stop(); } } // ── Consumer: fatal vs transient polling error (fix §4) ─────────── [Fact] public async Task Consumer_FatalPollingError_IsDetected() { var consumer = (TelegramConsumer)Endpoint("receive").CreateConsumer(Recorder(_ => Task.CompletedTask)); consumer.AttachToLiveBot = false; await consumer.Start(); try { await consumer.RaiseErrorForTest( new ApiRequestException("Unauthorized: bot token revoked", 401), HandleErrorSource.PollingError); consumer.FatalPollingErrorDetected.Should().BeTrue(); } finally { await consumer.Stop(); } } [Fact] public async Task Consumer_TransientPollingError_IsNotFatal() { var consumer = (TelegramConsumer)Endpoint("receive").CreateConsumer(Recorder(_ => Task.CompletedTask)); consumer.AttachToLiveBot = false; await consumer.Start(); try { await consumer.RaiseErrorForTest(new HttpRequestException("network blip"), HandleErrorSource.PollingError); consumer.FatalPollingErrorDetected.Should().BeFalse(); } finally { await consumer.Stop(); } } // ── Consumer: concurrency via .Threads(N) (fix §6) ──────────────── [Fact] public async Task Consumer_ThreadsProcessor_ProcessesUpToPoolSizeInParallel() { const int pool = 5, total = 20; await using var context = new RouteContext(); var current = 0; var max = 0; var maxLock = new object(); var body = Recorder(async _ => { var c = Interlocked.Increment(ref current); lock (maxLock) { if (c > max) max = c; } await Task.Delay(50); Interlocked.Decrement(ref current); }); var threads = new ThreadsProcessor(body, pool, maxQueueSize: 0, context); var consumer = (TelegramConsumer)Endpoint("receive").CreateConsumer(threads); consumer.AttachToLiveBot = false; await consumer.Start(); try { // A serial source (mirrors the single getUpdates stream): each hand-off returns fast, so the // pool still saturates to N concurrent workers. for (var i = 0; i < total; i++) await consumer.DeliverMessageForTest(IncomingText($"m{i}"), UpdateType.Message, CancellationToken.None); // Drain the pool deterministically (completes the backlog, then joins the workers). await ((IRouteLifecycleListener)threads).OnContextStopping(context, CancellationToken.None); threads.ProcessedCount.Should().Be(total, "no message is lost across the pool"); max.Should().Be(pool, "the pool saturates to exactly N concurrent workers via .Threads(N)"); } finally { await consumer.Stop(); } } // ── Producer: 429 RetryAfter is honoured (fix §5) ───────────────── [Fact] public async Task Producer_RateLimited429_WaitsRetryAfter_ThenRetries() { var mock = Substitute.For(); var calls = 0; mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(_ => { if (Interlocked.Increment(ref calls) == 1) throw new ApiRequestException("Too Many Requests", 429, new ResponseParameters { RetryAfter = 1 }); return Task.FromResult(SentMessage()); }); var producer = (TelegramProducer)Endpoint("send", "&chatId=555").CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { var sw = Stopwatch.StartNew(); var exchange = new Exchange(new Message("hi")); await producer.Process(exchange); sw.Stop(); calls.Should().Be(2, "the producer must retry once after a 429"); sw.Elapsed.Should().BeGreaterThanOrEqualTo(TimeSpan.FromMilliseconds(900), "the producer must wait the retry_after hint (~1s) before retrying"); exchange.In.Headers.Should().ContainKey(TelegramHeaders.SentMessageId); } finally { await producer.Stop(); } } // ── Producer: non-429 errors propagate (fix §4/§5) ──────────────── [Fact] public async Task Producer_NonRateLimitError_Propagates() { var mock = Substitute.For(); mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns>(_ => throw new ApiRequestException("Bad Request: chat not found", 400)); var producer = (TelegramProducer)Endpoint("send", "&chatId=555").CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { var act = async () => await producer.Process(new Exchange(new Message("hi"))); await act.Should().ThrowAsync().Where(e => e.ErrorCode == 400); } finally { await producer.Stop(); } } // ── Producer: chatId precedence header > option (fix §5) ────────── [Fact] public async Task Producer_ChatId_HeaderOverridesOption() { var mock = Substitute.For(); long? sentTo = null; mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(ci => { var req = (IChatTargetable)ci.Arg>(); sentTo = req.ChatId.Identifier; return Task.FromResult(SentMessage()); }); var producer = (TelegramProducer)Endpoint("send", "&chatId=111").CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { var exchange = new Exchange(new Message("hi")); exchange.In.Headers[TelegramHeaders.ChatId] = 999L; // header overrides option await producer.Process(exchange); sentTo.Should().Be(999L, "the telegram.chatId header takes precedence over the URI option"); } finally { await producer.Stop(); } } [Fact] public async Task Producer_ChatId_FallsBackToOption() { var mock = Substitute.For(); long? sentTo = null; mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(ci => { var req = (IChatTargetable)ci.Arg>(); sentTo = req.ChatId.Identifier; return Task.FromResult(SentMessage()); }); var producer = (TelegramProducer)Endpoint("send", "&chatId=111").CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { await producer.Process(new Exchange(new Message("hi"))); sentTo.Should().Be(111L, "with no header the URI chatId option is used"); } finally { await producer.Stop(); } } // ── Producer: replyToMessageId option (expression) — reply to the incoming message ── private const string ReplyToIncomingUri = "&chatId=555&replyToMessageId=${header.telegram.messageId}"; [Fact] public async Task Producer_ReplyToIncoming_UsesIncomingMessageId() { var mock = Substitute.For(); int? repliedTo = null; mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(ci => { var req = (SendMessageRequest)ci.Arg>(); repliedTo = req.ReplyParameters?.MessageId; return Task.FromResult(SentMessage()); }); var producer = (TelegramProducer)Endpoint("send", ReplyToIncomingUri).CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { var exchange = new Exchange(new Message("hi")); exchange.In.Headers[TelegramHeaders.MessageId] = 42; // set by the consumer await producer.Process(exchange); repliedTo.Should().Be(42, "the replyToMessageId expression resolves to the incoming telegram.messageId"); } finally { await producer.Stop(); } } [Fact] public async Task Producer_ReplyToIncoming_ExplicitHeaderWins() { var mock = Substitute.For(); int? repliedTo = null; mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(ci => { var req = (SendMessageRequest)ci.Arg>(); repliedTo = req.ReplyParameters?.MessageId; return Task.FromResult(SentMessage()); }); var producer = (TelegramProducer)Endpoint("send", ReplyToIncomingUri).CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { var exchange = new Exchange(new Message("hi")); exchange.In.Headers[TelegramHeaders.MessageId] = 42; exchange.In.Headers[TelegramHeaders.ReplyToMessageId] = 7; // explicit target await producer.Process(exchange); repliedTo.Should().Be(7, "an explicit telegram.replyToMessageId header wins over the option"); } finally { await producer.Stop(); } } [Fact] public async Task Producer_ReplyToIncoming_NoIncomingMessageId_SendsUnthreaded() { var mock = Substitute.For(); var captured = false; int? repliedTo = null; mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(ci => { var req = (SendMessageRequest)ci.Arg>(); captured = true; repliedTo = req.ReplyParameters?.MessageId; return Task.FromResult(SentMessage()); }); var producer = (TelegramProducer)Endpoint("send", ReplyToIncomingUri).CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { await producer.Process(new Exchange(new Message("hi"))); // no telegram.messageId header captured.Should().BeTrue(); repliedTo.Should().BeNull("an empty expression resolution sends the message unthreaded, not fail"); } finally { await producer.Stop(); } } // ── Producer: edit targets the message from the messageId option expression ── [Fact] public async Task Producer_Edit_MessageIdOptionExpression_TargetsSentMessage() { var mock = Substitute.For(); int? edited = null; mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(ci => { var req = (EditMessageTextRequest)ci.Arg>(); edited = req.MessageId; return Task.FromResult(SentMessage()); }); var producer = (TelegramProducer)Endpoint( "edit", "&chatId=555&messageId=${header.telegram.sentMessageId}").CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { var exchange = new Exchange(new Message("updated")); exchange.In.Headers[TelegramHeaders.SentMessageId] = 100; // written by an upstream send await producer.Process(exchange); edited.Should().Be(100, "the messageId expression resolves to telegram.sentMessageId"); } finally { await producer.Stop(); } } // ── Producer: document carries the reply markup header ──────────── [Fact] public async Task Producer_Document_PassesReplyMarkup() { var mock = Substitute.For(); ReplyMarkup? markup = null; mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(ci => { var req = (SendDocumentRequest)ci.Arg>(); markup = req.ReplyMarkup; return Task.FromResult(SentMessage()); }); var producer = (TelegramProducer)Endpoint("document", "&chatId=555").CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { var exchange = new Exchange(new Message(new byte[] { 1, 2, 3 })); exchange.In.Headers[TelegramHeaders.FileName] = "report.pdf"; exchange.In.Headers[TelegramHeaders.ReplyMarkup] = new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData("Open", "act:open")); await producer.Process(exchange); markup.Should().NotBeNull("document mode must honour telegram.replyMarkup"); } finally { await producer.Stop(); } } // ── Producer: answer with showAlert ─────────────────────────────── [Fact] public async Task Producer_Answer_ShowAlert_PassesFlag() { var mock = Substitute.For(); bool? shown = null; mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(ci => { var req = (AnswerCallbackQueryRequest)ci.Arg>(); shown = req.ShowAlert; return Task.FromResult(true); }); var producer = (TelegramProducer)Endpoint("answer", "&showAlert=true").CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { var exchange = new Exchange(new Message("Are you sure?")); exchange.In.Headers[TelegramHeaders.CallbackQueryId] = "cbq-1"; await producer.Process(exchange); shown.Should().BeTrue("showAlert=true must reach the Bot API call"); } finally { await producer.Stop(); } } [Fact] public async Task Producer_NoChatId_Throws() { var mock = Substitute.For(); var producer = (TelegramProducer)Endpoint("send").CreateProducer(); // no chatId option producer.UseTestClient(mock); await producer.Start(); try { var act = async () => await producer.Process(new Exchange(new Message("hi"))); await act.Should().ThrowAsync().WithMessage("*chatId*"); } finally { await producer.Stop(); } } // ── Producer: statistics ownership (audit follow-up) ────────────── [Fact] public async Task Producer_DoesNotSelfRecord_MessagesOut() { // Ownership audit: MessagesOut belongs to the core (ToProcessor for a routed .To(), // the ProducerTemplate for template sends) - the old per-send self-recording here // doubled every routed number. A hand-built Process moves nothing into MessagesOut. var mock = Substitute.For(); mock.SendRequest(Arg.Any>(), Arg.Any()) .Returns(_ => Task.FromResult(SentMessage())); var endpoint = Endpoint("send", "&chatId=555"); var producer = (TelegramProducer)endpoint.CreateProducer(); producer.UseTestClient(mock); await producer.Start(); try { await producer.Process(new Exchange(new Message("hi"))); await producer.Process(new Exchange(new Message("hi2"))); endpoint.MessagesOut.Should().Be(0, "MessagesOut is written by the core, the own write doubled it in the route"); } finally { await producer.Stop(); } } } Path: redb-route/tests/redb.Route.Tests.Telegram/TelegramKeyboardTests.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.Telegram/TelegramKeyboardTests.cs ---- using Telegram.Bot.Types.ReplyMarkups; using redb.Route.Telegram.Fluent; namespace redb.Route.Tests.Telegram; /// /// Unit tests for the fluent keyboard builder () — no network required. /// Covers inline / reply keyboard construction, button types, reply-keyboard options, /// keyboard removal, and the "empty row is ignored" rule. /// public class TelegramKeyboardTests { private static List> Rows(InlineKeyboardMarkup m) => m.InlineKeyboard.Select(r => r.ToList()).ToList(); private static List> Rows(ReplyKeyboardMarkup m) => m.Keyboard.Select(r => r.ToList()).ToList(); // ── Inline keyboard ─────────────────────────────────────────────── [Fact] public void Inline_BuildsRowsAndButtons() { var markup = TgKeyboard.Inline(k => k .Row(r => r.Callback("✅ Yes", "act:yes").Callback("❌ No", "act:no")) .Row(r => r.Url("📖 Docs", "https://example.com"))); var rows = Rows(markup); rows.Should().HaveCount(2); rows[0].Should().HaveCount(2); rows[0][0].Text.Should().Be("✅ Yes"); rows[0][0].CallbackData.Should().Be("act:yes"); rows[0][1].CallbackData.Should().Be("act:no"); rows[1].Should().HaveCount(1); rows[1][0].Text.Should().Be("📖 Docs"); rows[1][0].Url.Should().Be("https://example.com"); } [Fact] public void Inline_IgnoresEmptyRows() { var markup = TgKeyboard.Inline(k => k .Row(r => { /* no buttons */ }) .Row(r => r.Callback("A", "a"))); Rows(markup).Should().HaveCount(1); } // ── Reply keyboard ──────────────────────────────────────────────── [Fact] public void Reply_BuildsButtonsAndOptions() { var markup = TgKeyboard.Reply(k => k .Row(r => r.Button("📋 Menu").Button("❓ Help")) .Resize() .OneTime() .Persistent() .Selective() .Placeholder("Type here")); var rows = Rows(markup); rows.Should().HaveCount(1); rows[0].Select(b => b.Text).Should().Equal("📋 Menu", "❓ Help"); markup.ResizeKeyboard.Should().BeTrue(); markup.OneTimeKeyboard.Should().BeTrue(); markup.IsPersistent.Should().BeTrue(); markup.Selective.Should().BeTrue(); markup.InputFieldPlaceholder.Should().Be("Type here"); } [Fact] public void Reply_OptionsUnsetByDefault() { var markup = TgKeyboard.Reply(k => k.Row(r => r.Button("A"))); markup.ResizeKeyboard.Should().BeFalse(); markup.OneTimeKeyboard.Should().BeFalse(); markup.IsPersistent.Should().BeFalse(); markup.Selective.Should().BeFalse(); markup.InputFieldPlaceholder.Should().BeNull(); } // ── Remove keyboard ─────────────────────────────────────────────── [Fact] public void Remove_ProducesRemoveMarkup() { var markup = TgKeyboard.Remove(); markup.RemoveKeyboard.Should().BeTrue(); markup.Selective.Should().BeFalse(); } [Fact] public void Remove_Selective() { var markup = TgKeyboard.Remove(selective: true); markup.RemoveKeyboard.Should().BeTrue(); markup.Selective.Should().BeTrue(); } // ── Null guards ─────────────────────────────────────────────────── [Fact] public void Inline_NullBuild_Throws() { var act = () => TgKeyboard.Inline(null!); act.Should().Throw(); } [Fact] public void Reply_NullBuild_Throws() { var act = () => TgKeyboard.Reply(null!); act.Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests.Telegram/TelegramTraceTests.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.Telegram/TelegramTraceTests.cs ---- using System.Diagnostics; using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Telegram; using redb.Route.Telemetry; using redb.Route.Tests.Telemetry; using Telegram.Bot; using Telegram.Bot.Exceptions; using Telegram.Bot.Requests.Abstractions; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Message = redb.Route.Core.Message; using TgMessage = Telegram.Bot.Types.Message; namespace redb.Route.Tests.Telegram; /// /// An update carries no trace context: the consumer opens a root span per routed update, never a child of the activity /// the polling loop holds, with redb.route.endpoint; a failed route marks it red, whether the failure stays on /// the exchange or escapes it. The producer's span marks a failed send red. EnableTelemetry=false opens none of /// these spans. In process, through the connector's test seams; each test uses a chat of its own. /// public sealed class TelegramTraceTests { private const string Token = "123456:AAAA-Test_Token"; private readonly long _chat = Random.Shared.NextInt64(1_000_000, long.MaxValue); private readonly int _messageId = Random.Shared.Next(1_000_000, int.MaxValue); // Spans are found by the message id: the chat id identifies a person and is not written to a span. private RouteTelemetryProbe Spans(ActivityKind kind) => new(a => a.Kind == kind && Equals(a.GetTagItem("messaging.telegram.message.id"), _messageId)); private TgMessage Incoming() => new() { Id = _messageId, Text = "hello", Chat = new Chat { Id = _chat, Type = ChatType.Private }, From = new User { Id = 7, FirstName = "Ann" }, }; /// A started consumer in a context of its own, driven through the delivery seam. private static async Task<(RouteContext Context, TelegramConsumer Consumer)> StartConsumer( Func route, bool telemetry = true) { var ctx = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = telemetry }); ctx.AddComponent(new TelegramComponent()); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()).Returns(call => route(call.Arg())); var consumer = (TelegramConsumer)ctx.GetEndpoint($"telegram://receive?token={Token}").CreateConsumer(processor); consumer.AttachToLiveBot = false; await consumer.Start(); return (ctx, consumer); } [Fact] public async Task Each_update_opens_a_root_span_even_under_an_ambient_activity() { using var probe = Spans(ActivityKind.Consumer); var (ctx, consumer) = await StartConsumer(_ => Task.CompletedTask); try { using (new Activity("polling loop").SetIdFormat(ActivityIdFormat.W3C).Start()) { await consumer.DeliverMessageForTest(Incoming(), UpdateType.Message, CancellationToken.None); await consumer.DeliverMessageForTest(Incoming(), UpdateType.Message, CancellationToken.None); } } finally { await consumer.Stop(); await ctx.DisposeAsync(); } probe.Activities.Should().HaveCount(2); probe.Activities.Should().OnlyContain(a => a.ParentSpanId == default(ActivitySpanId), "an update carries no context, so its span starts a trace rather than joining the loop's"); probe.Activities.Should().OnlyContain(a => a.GetTagItem("messaging.telegram.chat.id") == null, "the chat id identifies a person; a route that needs it adds it with SpanTag"); RouteTelemetryProbe.Tag(probe.Activities[0], RouteTelemetryProbe.EndpointTag).Should().StartWith("telegram:"); } [Fact] public async Task A_failed_route_marks_the_span_red_whether_the_failure_stays_on_the_exchange_or_escapes() { using var probe = Spans(ActivityKind.Consumer); var calls = 0; var (ctx, consumer) = await StartConsumer(e => { if (Interlocked.Increment(ref calls) == 1) { e.Exception = new InvalidOperationException("route failed"); // left on the exchange return Task.CompletedTask; } throw new InvalidOperationException("escaped"); }); try { await consumer.DeliverMessageForTest(Incoming(), UpdateType.Message, CancellationToken.None); await consumer.DeliverMessageForTest(Incoming(), UpdateType.Message, CancellationToken.None); } finally { await consumer.Stop(); await ctx.DisposeAsync(); } probe.Activities.Should().HaveCount(2).And.OnlyContain(a => a.Status == ActivityStatusCode.Error); } [Fact] public async Task Tracing_off_opens_no_span_on_either_side() { using var probe = new RouteTelemetryProbe(a => Equals(a.GetTagItem("messaging.telegram.message.id"), _messageId)); var (ctx, consumer) = await StartConsumer(_ => Task.CompletedTask, telemetry: false); using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start(); using var sends = new RouteTelemetryProbe(a => a.Kind == ActivityKind.Producer && a.TraceId == outer.TraceId); try { await consumer.DeliverMessageForTest(Incoming(), UpdateType.Message, CancellationToken.None); var bot = Substitute.For(); bot.SendRequest(Arg.Any>(), Arg.Any()) .Returns(Task.FromResult(new TgMessage { Id = 1, Chat = new Chat { Id = _chat, Type = ChatType.Private } })); var producer = (TelegramProducer)ctx.GetEndpoint($"telegram://send?token={Token}&chatId={_chat}").CreateProducer(); producer.UseTestClient(bot); await producer.Start(); await producer.Process(new Exchange(new Message("hi"))); await producer.Stop(); } finally { await consumer.Stop(); await ctx.DisposeAsync(); } probe.Activities.Should().BeEmpty(); sends.Activities.Should().BeEmpty(); } [Fact] public async Task A_failed_send_marks_the_producer_span_red() { using var outer = new Activity("caller").SetIdFormat(ActivityIdFormat.W3C).Start(); using var sends = new RouteTelemetryProbe(a => a.Kind == ActivityKind.Producer && a.TraceId == outer.TraceId); await using var ctx = new RouteContext(); ctx.AddComponent(new TelegramComponent()); var bot = Substitute.For(); bot.SendRequest(Arg.Any>(), Arg.Any()) .Returns>(_ => throw new ApiRequestException("Bad Request: chat not found", 400)); var producer = (TelegramProducer)ctx.GetEndpoint($"telegram://send?token={Token}&chatId={_chat}").CreateProducer(); producer.UseTestClient(bot); await producer.Start(); var act = () => producer.Process(new Exchange(new Message("hi"))); await act.Should().ThrowAsync(); await producer.Stop(); var send = sends.Activities.Should().ContainSingle().Subject; send.Status.Should().Be(ActivityStatusCode.Error); RouteTelemetryProbe.Tag(send, RouteTelemetryProbe.EndpointTag).Should().StartWith("telegram:"); send.GetTagItem("messaging.telegram.chat.id").Should().BeNull(); send.GetTagItem("messaging.destination.name").Should().BeNull("the destination of a send is the chat id"); } } Path: redb-route/tests/redb.Route.Tests.Telegram/TelegramTransportTests.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.Telegram/TelegramTransportTests.cs ---- using redb.Route.Telegram; namespace redb.Route.Tests.Telegram; /// /// The shared HTTP transport of a bot. A getUpdates long poll is ~50 s of silence on the wire, and /// tunnels/NATs cut a silent TLS connection at about that mark — every idle poll then dies with /// "The response ended prematurely". HTTP/2 PING frames while the request is in flight are what /// keeps the poll (and a long download) alive, so the transport must ask for HTTP/2 and ping well /// inside the ~50 s window. /// public sealed class TelegramTransportTests { [Fact] public void SharedHttpClient_UsesHttp2_WithKeepAlivePings() { var handler = TelegramComponent.BuildHandler(); handler.KeepAlivePingPolicy.Should().Be(HttpKeepAlivePingPolicy.WithActiveRequests); handler.KeepAlivePingDelay.Should().BeGreaterThan(TimeSpan.Zero).And.BeLessThan(TimeSpan.FromSeconds(30)); handler.KeepAlivePingTimeout.Should().BeGreaterThan(TimeSpan.Zero); using var http = TelegramComponent.BuildHttpClient(); http.DefaultRequestVersion.Should().Be(System.Net.HttpVersion.Version20); http.DefaultVersionPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower, "HTTP/1.1 must stay the fallback"); http.Timeout.Should().BeGreaterThan(TimeSpan.FromSeconds(50), "must exceed Telegram's long-poll cap plus a margin"); } [Fact] public async Task EveryRequest_IsUpgradedToHttp2_BeforeItReachesTheSocket() { // Telegram.Bot builds its own HttpRequestMessages, which start at HTTP/1.1 no matter what // the client's DefaultRequestVersion says — so the upgrade has to happen per request. var inner = new RecordingHandler(); using var http = new HttpClient(new Http2UpgradeHandler(inner)); using var request = new HttpRequestMessage(HttpMethod.Post, "https://api.telegram.org/bot1/getMe"); request.Version.Should().Be(System.Net.HttpVersion.Version11, "that is what a hand-built message starts with"); using var _ = await http.SendAsync(request); inner.SeenVersion.Should().Be(System.Net.HttpVersion.Version20); inner.SeenPolicy.Should().Be(HttpVersionPolicy.RequestVersionOrLower, "HTTP/1.1 must stay the fallback"); } private sealed class RecordingHandler : HttpMessageHandler { public Version? SeenVersion { get; private set; } public HttpVersionPolicy? SeenPolicy { get; private set; } protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { SeenVersion = request.Version; SeenPolicy = request.VersionPolicy; return Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new StringContent("{}") }); } } } Path: redb-route/tests/redb.Route.Tests.Telegram/TelegramUnitTests.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.Telegram/TelegramUnitTests.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telegram; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using TgDsl = redb.Route.Telegram.Fluent.Tg; using TgParseMode = Telegram.Bot.Types.Enums.ParseMode; using Message = redb.Route.Core.Message; using TgMessage = Telegram.Bot.Types.Message; namespace redb.Route.Tests.Telegram; /// /// Unit tests for the Telegram connector — no network required. Cover URI→options binding, /// ${env:} token resolution, validation (incl. parseMode enum), the fluent DSL round-trip /// (esp. the previously-lost .Timeout() / .BodyIsFileId()), header helpers, the update /// mapper, the webhook serializer, component scheme + endpoint mode routing, and the single-stream guard. /// public class TelegramUnitTests { private const string Token = "123456:AAAA-Test_Token"; private static TelegramEndpointOptions Bind(string query) { var uri = EndpointUriParser.Parse($"telegram://send?{query}"); var options = new TelegramEndpointOptions(); options.BindFromUri(uri.RawParameters); return options; } // ── Options binding ─────────────────────────────────────────────── [Fact] public void Options_BindsAllProducerParams() { var o = Bind($"token={Token}&chatId=987654&parseMode=HTML&caption=hi" + "&fileName=report.pdf&bodyIsFileId=true&disableNotification=true" + "&replyToMessageId=77&messageId=12&showAlert=true&sendTimeoutSeconds=45"); o.Token.Should().Be(Token); o.ChatId.Should().Be("987654"); o.ParseMode.Should().Be("HTML"); o.Caption.Should().Be("hi"); o.FileName.Should().Be("report.pdf"); o.BodyIsFileId.Should().BeTrue(); o.DisableNotification.Should().BeTrue(); o.ReplyToMessageId.Should().Be("77"); o.MessageId.Should().Be("12"); o.ShowAlert.Should().BeTrue(); o.SendTimeoutSeconds.Should().Be(45); } [Fact] public void Options_Defaults() { var o = Bind($"token={Token}"); o.ChatId.Should().BeNull(); o.ParseMode.Should().BeNull(); o.BodyIsFileId.Should().BeFalse(); o.DisableNotification.Should().BeFalse(); o.ReplyToMessageId.Should().BeNull(); o.MessageId.Should().BeNull(); o.ShowAlert.Should().BeFalse(); o.SendTimeoutSeconds.Should().Be(120); } // ── Token expression resolution ─────────────────────────────────── [Fact] public void ResolveTokenExpression_ResolvesEnvVar() { var name = "TG_TEST_TOKEN_" + Guid.NewGuid().ToString("N"); Environment.SetEnvironmentVariable(name, Token); try { TelegramEndpointOptions.ResolveTokenExpression($"${{env:{name}}}").Should().Be(Token); } finally { Environment.SetEnvironmentVariable(name, null); } } [Fact] public void ResolveTokenExpression_LiteralUnchanged() { TelegramEndpointOptions.ResolveTokenExpression(Token).Should().Be(Token); } [Fact] public void Token_PropertyPlaceholder_ReadsEnvironmentWithoutConfiguration() { // {{NAME}} is the general spelling: resolved by the context before the component binds the URI. var name = "TG_TEST_TOKEN_" + Guid.NewGuid().ToString("N"); Environment.SetEnvironmentVariable(name, Token); try { using var context = new RouteContext(); context.AddComponent(new TelegramComponent()); var viaPlaceholder = context.GetEndpoint("telegram://send?token={{" + name + "}}&chatId=1"); viaPlaceholder.Should().BeOfType() .And.BeSameAs(context.GetEndpoint($"telegram://send?token={Token}&chatId=1")); } finally { Environment.SetEnvironmentVariable(name, null); } } [Fact] public void ResolveTokenExpression_MissingEnvVar_Throws() { var name = "TG_MISSING_" + Guid.NewGuid().ToString("N"); var act = () => TelegramEndpointOptions.ResolveTokenExpression($"${{env:{name}}}"); act.Should().Throw().WithMessage("*not set*"); } // ── Validation ──────────────────────────────────────────────────── [Theory] [InlineData("chatId=1")] // missing token [InlineData("token=&chatId=1")] // empty token [InlineData("token=t&parseMode=Markdwn")] // typo in parseMode [InlineData("token=t&sendTimeoutSeconds=0")] // out of range (low) [InlineData("token=t&sendTimeoutSeconds=601")] // out of range (high) [InlineData("token=t&replyToMessageId=abc")] // constant that is not a message id [InlineData("token=t&messageId=abc")] // constant that is not a message id public void Validate_RejectsBadConfig(string query) { var act = () => Bind(query).Validate(); act.Should().Throw(); } [Theory] [InlineData("token=t")] [InlineData("token=t&parseMode=HTML")] [InlineData("token=t&parseMode=Markdown")] [InlineData("token=t&parseMode=MarkdownV2")] [InlineData("token=t&parseMode=none")] [InlineData("token=t&sendTimeoutSeconds=600")] public void Validate_AcceptsValidConfig(string query) { var act = () => Bind(query).Validate(); act.Should().NotThrow(); } [Theory] [InlineData(null, true, TgParseMode.None)] [InlineData("", true, TgParseMode.None)] [InlineData("HTML", true, TgParseMode.Html)] [InlineData("html", true, TgParseMode.Html)] [InlineData("Markdown", true, TgParseMode.Markdown)] [InlineData("MarkdownV2", true, TgParseMode.MarkdownV2)] [InlineData("none", true, TgParseMode.None)] [InlineData("Markdwn", false, TgParseMode.None)] [InlineData("bogus", false, TgParseMode.None)] public void TryParseParseMode_TruthTable(string? raw, bool expectedOk, TgParseMode expectedMode) { var ok = TelegramEndpointOptions.TryParseParseMode(raw, out var mode); ok.Should().Be(expectedOk); if (expectedOk) mode.Should().Be(expectedMode); } // ── Fluent DSL round-trip ───────────────────────────────────────── [Fact] public void Dsl_Send_RoundTripsThroughOptions() { string uri = TgDsl.Send(Token) .ChatId(987654) .ParseMode("HTML") .DisableNotification() .ReplyToIncoming() .Timeout(30) .BodyIsFileId(); var parsed = EndpointUriParser.Parse(uri); var o = new TelegramEndpointOptions(); o.BindFromUri(parsed.RawParameters); o.Token.Should().Be(Token); o.ChatId.Should().Be("987654"); o.ParseMode.Should().Be("HTML"); o.DisableNotification.Should().BeTrue(); o.ReplyToMessageId.Should().Be("${header.telegram.messageId}", ".ReplyToIncoming() is sugar for the incoming-message-id expression"); // Previously lost by the builder — these two are the point of the test. o.SendTimeoutSeconds.Should().Be(30); o.BodyIsFileId.Should().BeTrue(); } [Fact] public void Dsl_Document_EmitsExpectedUri() { string uri = TgDsl.Document(Token).ChatId(1).FileName("report.pdf").Caption("Daily"); uri.Should().StartWith("telegram://document?"); uri.Should().Contain("fileName=report.pdf"); uri.Should().Contain("caption=Daily"); } [Fact] public void Dsl_Edit_MessageId_RoundTripsThroughOptions() { string uri = TgDsl.Edit(Token).ChatId(1).MessageId(12); var parsed = EndpointUriParser.Parse(uri); var o = new TelegramEndpointOptions(); o.BindFromUri(parsed.RawParameters); o.MessageId.Should().Be("12"); } [Fact] public void Dsl_Answer_ShowAlert_EmitsExpectedUri() { string uri = TgDsl.Answer(Token).ShowAlert(); uri.Should().StartWith("telegram://answer?"); uri.Should().Contain("showAlert=true"); } // ── Header helpers ──────────────────────────────────────────────── [Fact] public void Headers_PrefixAndGuard() { TelegramHeaders.ChatId.Should().StartWith("telegram."); TelegramHeaders.IsRedbHeader(TelegramHeaders.MessageId).Should().BeTrue(); TelegramHeaders.IsRedbHeader("customHeader").Should().BeFalse(); } // ── Update mapper ───────────────────────────────────────────────── [Fact] public void MapMessage_TextMessage_PopulatesBodyAndHeaders() { var msg = new TgMessage { Id = 42, Text = "hello", Chat = new Chat { Id = 123, Type = ChatType.Private }, From = new User { Id = 7, FirstName = "Ann", Username = "ann", LanguageCode = "en" } }; var m = new Message(); TelegramUpdateMapper.MapMessage(msg, UpdateType.Message, m); m.Body.Should().Be("hello"); m.Headers[TelegramHeaders.MessageId].Should().Be(42); m.Headers[TelegramHeaders.ChatId].Should().Be(123L); m.Headers[TelegramHeaders.ChatType].Should().Be("Private"); m.Headers[TelegramHeaders.UpdateType].Should().Be("Message"); m.Headers[TelegramHeaders.UserId].Should().Be(7L); m.Headers[TelegramHeaders.FirstName].Should().Be("Ann"); m.Headers[TelegramHeaders.Username].Should().Be("ann"); m.Headers[TelegramHeaders.LanguageCode].Should().Be("en"); } [Fact] public void MapUpdate_TextMessage_ReturnsTrue() { var update = new Update { Id = 1, Message = new TgMessage { Id = 10, Text = "hi", Chat = new Chat { Id = 5, Type = ChatType.Group } } }; var m = new Message(); TelegramUpdateMapper.MapUpdate(update, m).Should().BeTrue(); m.Body.Should().Be("hi"); m.Headers[TelegramHeaders.UpdateId].Should().Be(1L); m.Headers[TelegramHeaders.ChatId].Should().Be(5L); } [Fact] public void MapUpdate_EditedMessage_ReturnsTrue() { var update = new Update { Id = 2, EditedMessage = new TgMessage { Id = 11, Text = "edited", Chat = new Chat { Id = 6, Type = ChatType.Supergroup } } }; var m = new Message(); TelegramUpdateMapper.MapUpdate(update, m).Should().BeTrue(); m.Headers[TelegramHeaders.UpdateType].Should().Be("EditedMessage"); m.Body.Should().Be("edited"); } [Fact] public void MapUpdate_CallbackQuery_PopulatesCallbackHeaders() { var update = new Update { Id = 3, CallbackQuery = new CallbackQuery { Id = "cbq-1", Data = "action:approve", From = new User { Id = 9, FirstName = "Bob", Username = "bob" }, Message = new TgMessage { Id = 12, Chat = new Chat { Id = 77, Type = ChatType.Private } } } }; var m = new Message(); TelegramUpdateMapper.MapUpdate(update, m).Should().BeTrue(); m.Body.Should().Be("action:approve"); m.Headers[TelegramHeaders.CallbackQueryId].Should().Be("cbq-1"); m.Headers[TelegramHeaders.CallbackData].Should().Be("action:approve"); m.Headers[TelegramHeaders.UserId].Should().Be(9L); m.Headers[TelegramHeaders.ChatId].Should().Be(77L); } [Fact] public void MapMessage_WebAppData_PopulatesBodyAndHeaders() { var msg = new TgMessage { Id = 43, Chat = new Chat { Id = 123, Type = ChatType.Private }, From = new User { Id = 7, FirstName = "Ann" }, WebAppData = new WebAppData { Data = """{"city":"Moscow"}""", ButtonText = "Собрать" } }; var m = new Message(); TelegramUpdateMapper.MapMessage(msg, UpdateType.Message, m); // No Text on a web_app_data message — the payload becomes the body. m.Body.Should().Be("""{"city":"Moscow"}"""); m.Headers[TelegramHeaders.WebAppData].Should().Be("""{"city":"Moscow"}"""); m.Headers[TelegramHeaders.WebAppButtonText].Should().Be("Собрать"); m.Headers.Should().NotContainKey(TelegramHeaders.Text); m.Headers[TelegramHeaders.ChatId].Should().Be(123L); } [Fact] public void MapMessage_Voice_ExposesFileIdAndMetadata() { var msg = new TgMessage { Id = 44, Chat = new Chat { Id = 123, Type = ChatType.Private }, From = new User { Id = 7, FirstName = "Ann" }, Voice = new Voice { FileId = "AwACAgIAAxkBAAI", FileUniqueId = "AgADXwEAAg", Duration = 48, MimeType = "audio/ogg", FileSize = 91_234, }, }; var m = new Message(); TelegramUpdateMapper.MapMessage(msg, UpdateType.Message, m); // Without these headers a voice note is unreachable: the body carries Text, which a // recording does not have, so a route could see THAT a file arrived and still have no // way to fetch it. m.Headers[TelegramHeaders.AttachmentKind].Should().Be("voice"); m.Headers[TelegramHeaders.AttachmentFileId].Should().Be("AwACAgIAAxkBAAI"); m.Headers[TelegramHeaders.AttachmentDuration].Should().Be(48); m.Headers[TelegramHeaders.AttachmentMimeType].Should().Be("audio/ogg"); m.Headers[TelegramHeaders.AttachmentFileSize].Should().Be(91_234L); // The body stays "what the user typed", and a voice note has nothing typed. m.Body.Should().Be(string.Empty); // The producer's own file_id key must NOT be set from an incoming file: headers travel // with the exchange, and a route that answers with a document would otherwise echo the // user's own recording back at them. m.Headers.Should().NotContainKey(TelegramHeaders.FileId); } [Fact] public void MapMessage_PhotoWithCaption_TakesLargestSizeAndKeepsCaptionOutOfBody() { var msg = new TgMessage { Id = 45, Chat = new Chat { Id = 123, Type = ChatType.Private }, Caption = "вот моя карта", Photo = [ new PhotoSize { FileId = "small", FileUniqueId = "u1", Width = 90, Height = 90, FileSize = 1_200 }, new PhotoSize { FileId = "large", FileUniqueId = "u2", Width = 1280, Height = 1280, FileSize = 240_000 }, ], }; var m = new Message(); TelegramUpdateMapper.MapMessage(msg, UpdateType.Message, m); // A photo arrives as a size ladder; the largest is the one a route asking for the // picture actually wants — downscaling is the caller's choice, not the mapper's. m.Headers[TelegramHeaders.AttachmentKind].Should().Be("photo"); m.Headers[TelegramHeaders.AttachmentFileId].Should().Be("large"); m.Headers[TelegramHeaders.AttachmentFileSize].Should().Be(240_000L); // Caption is a header, not the body: promoting it would make a captioned photo // indistinguishable from a typed command downstream. m.Headers[TelegramHeaders.AttachmentCaption].Should().Be("вот моя карта"); m.Body.Should().Be(string.Empty); } [Fact] public void MapMessage_Document_ReportsNameAndTextMessageStaysClean() { var document = new TgMessage { Id = 46, Chat = new Chat { Id = 123, Type = ChatType.Private }, Document = new Document { FileId = "doc-1", FileUniqueId = "u3", FileName = "отчёт.pdf", MimeType = "application/pdf", FileSize = 5_000, }, }; var docMessage = new Message(); TelegramUpdateMapper.MapMessage(document, UpdateType.Message, docMessage); docMessage.Headers[TelegramHeaders.AttachmentKind].Should().Be("document"); docMessage.Headers[TelegramHeaders.AttachmentFileName].Should().Be("отчёт.pdf"); docMessage.Headers[TelegramHeaders.AttachmentMimeType].Should().Be("application/pdf"); docMessage.Headers.Should().NotContainKey(TelegramHeaders.AttachmentDuration); // A plain text message must not grow attachment headers — the addition is additive // only where there is a file. var text = new TgMessage { Id = 47, Text = "hello", Chat = new Chat { Id = 123, Type = ChatType.Private }, }; var textMessage = new Message(); TelegramUpdateMapper.MapMessage(text, UpdateType.Message, textMessage); textMessage.Headers.Should().NotContainKey(TelegramHeaders.AttachmentKind); textMessage.Headers.Should().NotContainKey(TelegramHeaders.AttachmentFileId); textMessage.Body.Should().Be("hello"); } [Fact] public void MapUpdate_VoiceMessage_CarriesAttachmentHeadersThroughTheUpdatePath() { var update = new Update { Id = 900, Message = new TgMessage { Id = 48, Chat = new Chat { Id = 123, Type = ChatType.Private }, Voice = new Voice { FileId = "v-1", FileUniqueId = "u4", Duration = 3 }, }, }; var m = new Message(); // Long polling and webhooks share the mapper on purpose; a header that appeared on one // path only would make the webhook contour quietly different. TelegramUpdateMapper.MapUpdate(update, m).Should().BeTrue(); m.Headers[TelegramHeaders.AttachmentKind].Should().Be("voice"); m.Headers[TelegramHeaders.AttachmentFileId].Should().Be("v-1"); m.Headers[TelegramHeaders.AttachmentDuration].Should().Be(3); } [Fact] public void MapUpdate_TextMessage_HasNoWebAppHeaders() { var update = new Update { Id = 4, Message = new TgMessage { Id = 13, Text = "plain", Chat = new Chat { Id = 5, Type = ChatType.Private } } }; var m = new Message(); TelegramUpdateMapper.MapUpdate(update, m).Should().BeTrue(); m.Body.Should().Be("plain"); m.Headers.Should().NotContainKey(TelegramHeaders.WebAppData); m.Headers.Should().NotContainKey(TelegramHeaders.WebAppButtonText); } [Fact] public void MapUpdate_UnsupportedType_ReturnsFalse() { // An update with no recognised payload (only the id) maps to Unknown → skipped. var update = new Update { Id = 99 }; TelegramUpdateMapper.MapUpdate(update, new Message()).Should().BeFalse(); } // ── Webhook serializer ──────────────────────────────────────────── [Fact] public void Serializer_DeserializesWebhookJsonToUpdate() { var json = System.Text.Encoding.UTF8.GetBytes( """{"update_id":55,"message":{"message_id":10,"date":0,"chat":{"id":123,"type":"private"},"text":"webhook-hi"}}"""); var serializer = new TelegramUpdateSerializer(); var update = serializer.Deserialize(json); update.Should().NotBeNull(); update!.Id.Should().Be(55); update.Message!.Text.Should().Be("webhook-hi"); update.Message.Chat.Id.Should().Be(123); } [Fact] public void Serializer_Serialize_IsNotSupported() { var act = () => new TelegramUpdateSerializer().Serialize(new Update()); act.Should().Throw(); } [Fact] public async Task UnpackProcessor_MapsUpdateFromBody() { var exchange = new Exchange(new Message { Body = new Update { Id = 4, Message = new TgMessage { Id = 1, Text = "unpack-me", Chat = new Chat { Id = 8, Type = ChatType.Private } } } }); await new TelegramUpdateUnpackProcessor().Process(exchange); exchange.In.Body.Should().Be("unpack-me"); exchange.In.Headers[TelegramHeaders.ChatId].Should().Be(8L); } // ── Component + endpoint ────────────────────────────────────────── [Fact] public void Component_SchemeAndEndpointCreation() { var component = new TelegramComponent(); component.Scheme.Should().Be("telegram"); var endpoint = component.CreateEndpoint(EndpointUriParser.Parse($"telegram://receive?token={Token}")); endpoint.Should().BeOfType(); ((TelegramEndpoint)endpoint).Mode.Should().Be("receive"); endpoint.CreateConsumer(Substitute.For()).Should().BeAssignableTo(); } [Theory] [InlineData("send")] [InlineData("document")] [InlineData("photo")] [InlineData("answer")] [InlineData("edit")] [InlineData("delete")] [InlineData("download")] public void Endpoint_ProducerModes_CreateProducer(string mode) { var endpoint = new TelegramComponent() .CreateEndpoint(EndpointUriParser.Parse($"telegram://{mode}?token={Token}")); ((TelegramEndpoint)endpoint).Mode.Should().Be(mode); endpoint.CreateProducer().Should().BeAssignableTo(); } [Fact] public void Endpoint_NonReceiveMode_CannotCreateConsumer() { var endpoint = new TelegramComponent() .CreateEndpoint(EndpointUriParser.Parse($"telegram://send?token={Token}")); var act = () => endpoint.CreateConsumer(Substitute.For()); act.Should().Throw(); } [Fact] public void Endpoint_UnknownMode_Throws() { var act = () => new TelegramComponent() .CreateEndpoint(EndpointUriParser.Parse($"telegram://bogus?token={Token}")); act.Should().Throw(); } // ── Single-stream guard ─────────────────────────────────────────── [Fact] public void RegisterConsumer_SecondForSameToken_Throws() { var component = new TelegramComponent(); component.RegisterConsumer(Token); var act = () => component.RegisterConsumer(Token); act.Should().Throw().WithMessage("*one consumer per bot token*"); } [Fact] public void RegisterConsumer_AfterUnregister_Succeeds() { var component = new TelegramComponent(); component.RegisterConsumer(Token); component.UnregisterConsumer(Token); var act = () => component.RegisterConsumer(Token); act.Should().NotThrow(); } } Path: redb-route/tests/redb.Route.Tests.Telegram/redb.Route.Tests.Telegram.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.Telegram/redb.Route.Tests.Telegram.csproj ----