Telegram: il messaggio di prova dice sempre il motivo vero, e la coda è sotto test (#35)
L'interfaccia aspettava la risposta di «Invia messaggio di prova» 30 s, mentre il client verso Telegram scadeva a 40 s: con Telegram irraggiungibile compariva «Il bot non ha risposto in tempo» invece di «Telegram non raggiungibile». Ora ogni richiesta a Telegram ha il suo tempo massimo, la nuova impostazione «Tempo massimo di una richiesta» (TelegramTimeoutSeconds, 15 s, da 5 a 60, vale subito), e oltre quel tempo l'esito è «Telegram non raggiungibile: nessuna risposta in N s». L'interfaccia aspetta 15 s in più del valore salvato, così l'errore vero arriva sempre; la lettura dei comandi aspetta il polling lungo più lo stesso tempo. Il client non ha più un tempo suo. Le attese del notificatore (fra i tentativi e nei cicli) si possono iniettare, senza cambiare il comportamento, e TelegramNotifierTests le prova contro un Telegram finto: messaggio di prova riuscito, rifiutato, con errore di rete, senza risposta, senza token o chat; i tre tentativi della coda con attese di 4 e 8 s e una sola riga nel registro finché un messaggio non riparte; una scadenza nella coda, che scrive «nessuna risposta in N s» e non chiude il ciclo di invio (il messaggio dopo parte); i comandi accettati solo dalla chat configurata. Guida: Telegram e Impostazioni. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bac49d3fc4
commit
ea6ba27462
7 files changed
+391
-18
No files matched your search
@@ -0,0 +1,324 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Mimante.Logging;
|
||||
using Mimante.Settings;
|
||||
using Mimante.Telegram;
|
||||
using Xunit;
|
||||
|
||||
namespace Mimante.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="TelegramNotifier"/> contro un Telegram finto (un <see cref="HttpMessageHandler"/>
|
||||
/// che risponde come la Bot API): il messaggio di prova, la coda con i tre tentativi e il filtro
|
||||
/// dei comandi. Le attese sono iniettate e brevissime, così i test non aspettano i secondi veri.
|
||||
/// Il formato dei messaggi è in <c>TelegramFormatTests</c>.
|
||||
/// </summary>
|
||||
public class TelegramNotifierTests
|
||||
{
|
||||
private const string Token = "123:finto";
|
||||
private const string Chat = "42";
|
||||
|
||||
/// <summary>Una richiesta arrivata al Telegram finto: metodo della Bot API, indirizzo e corpo.</summary>
|
||||
private sealed record Call(string Method, string Url, string Body);
|
||||
|
||||
/// <summary>Il Telegram finto: registra ogni richiesta e risponde con <paramref name="respond"/>.</summary>
|
||||
private sealed class FakeTelegram(Func<Call, CancellationToken, Task<HttpResponseMessage>> respond) : HttpMessageHandler
|
||||
{
|
||||
public ConcurrentQueue<Call> Calls { get; } = new();
|
||||
|
||||
public IReadOnlyList<Call> Sends => Calls.Where(c => c.Method == "sendMessage").ToList();
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
var url = request.RequestUri!.ToString();
|
||||
var method = request.RequestUri.AbsolutePath.Split('/').Last();
|
||||
var body = request.Content == null ? "" : await request.Content.ReadAsStringAsync(ct);
|
||||
var call = new Call(method, url, body);
|
||||
Calls.Enqueue(call);
|
||||
return await respond(call, ct);
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpResponseMessage Json(HttpStatusCode status, string json) =>
|
||||
new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
|
||||
|
||||
private static HttpResponseMessage Ok() => Json(HttpStatusCode.OK, """{"ok":true,"result":{}}""");
|
||||
|
||||
private static AppSettings Configured(bool commands = false) =>
|
||||
new() { TelegramBotToken = Token, TelegramChatId = Chat, TelegramCommandsEnabled = commands };
|
||||
|
||||
/// <summary>Le attese chieste dal notificatore; ognuna dura pochi millisecondi.</summary>
|
||||
private sealed class Delays
|
||||
{
|
||||
public ConcurrentQueue<TimeSpan> Asked { get; } = new();
|
||||
|
||||
public Task Wait(TimeSpan d, CancellationToken ct)
|
||||
{
|
||||
Asked.Enqueue(d);
|
||||
return Task.Delay(TimeSpan.FromMilliseconds(5), ct);
|
||||
}
|
||||
|
||||
/// <summary>Solo le attese fra un tentativo e l'altro (quelle dei cicli dei comandi sono di 10 e 30 s).</summary>
|
||||
public List<TimeSpan> Retries => Asked.Where(d => d < TimeSpan.FromSeconds(10)).ToList();
|
||||
}
|
||||
|
||||
private static (TelegramNotifier Notifier, FakeTelegram Fake, AppLog Log, Delays Delays) Make(
|
||||
AppSettings settings, Func<Call, CancellationToken, Task<HttpResponseMessage>> respond)
|
||||
{
|
||||
var fake = new FakeTelegram(respond);
|
||||
var log = new AppLog(null) { WriteToFile = false, Capacity = 200 };
|
||||
var delays = new Delays();
|
||||
var notifier = new TelegramNotifier(() => settings, log, new HttpClient(fake) { Timeout = Timeout.InfiniteTimeSpan }, delays.Wait);
|
||||
return (notifier, fake, log, delays);
|
||||
}
|
||||
|
||||
private static async Task Until(Func<bool> condition, string what)
|
||||
{
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTime.UtcNow > deadline) Assert.Fail("Non è successo in tempo: " + what);
|
||||
await Task.Delay(10);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<string> Warnings(AppLog log) =>
|
||||
log.Snapshot().Where(e => e.Level == LogLevel.Warning && e.Tag == "TELEGRAM").Select(e => e.Message).ToList();
|
||||
|
||||
// ── Messaggio di prova ──────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task Il_messaggio_di_prova_riuscito_va_alla_chat_configurata()
|
||||
{
|
||||
var (n, fake, _, _) = Make(Configured(), (_, _) => Task.FromResult(Ok()));
|
||||
await using var _n = n;
|
||||
|
||||
var (ok, msg) = await n.SendTestAsync(CancellationToken.None);
|
||||
|
||||
Assert.True(ok);
|
||||
Assert.Equal("Messaggio inviato", msg);
|
||||
var send = Assert.Single(fake.Sends);
|
||||
Assert.Equal($"{TelegramApi.BaseUrl}/bot{Token}/sendMessage", send.Url);
|
||||
Assert.Contains("\"chat_id\":\"42\"", send.Body, StringComparison.Ordinal);
|
||||
Assert.Contains("Messaggio di prova da Mimante", send.Body, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.BadRequest, """{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}""")]
|
||||
[InlineData(HttpStatusCode.Unauthorized, """{"ok":false,"error_code":401,"description":"Unauthorized"}""")]
|
||||
[InlineData(HttpStatusCode.OK, """{"ok":false}""")]
|
||||
public async Task Il_rifiuto_di_Telegram_dice_di_controllare_token_e_chat(HttpStatusCode status, string json)
|
||||
{
|
||||
var (n, _, _, _) = Make(Configured(), (_, _) => Task.FromResult(Json(status, json)));
|
||||
await using var _n = n;
|
||||
|
||||
var (ok, msg) = await n.SendTestAsync(CancellationToken.None);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Equal("Telegram ha rifiutato il messaggio: controlla token e chat id (scrivi prima un messaggio al bot)", msg);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Un_errore_di_rete_arriva_con_il_suo_messaggio()
|
||||
{
|
||||
var (n, _, _, _) = Make(Configured(), (_, _) => throw new HttpRequestException("host sconosciuto"));
|
||||
await using var _n = n;
|
||||
|
||||
var (ok, msg) = await n.SendTestAsync(CancellationToken.None);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Equal("Telegram non raggiungibile: host sconosciuto", msg);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Senza_risposta_entro_il_tempo_massimo_e_non_raggiungibile()
|
||||
{
|
||||
// Il valore vero va da 5 a 60 s (SettingsStore.Normalize); qui 1 s, per non aspettare.
|
||||
var s = Configured();
|
||||
s.TelegramTimeoutSeconds = 1;
|
||||
var (n, _, _, _) = Make(s, async (_, ct) => { await Task.Delay(Timeout.Infinite, ct); return Ok(); });
|
||||
await using var _n = n;
|
||||
|
||||
var started = DateTime.UtcNow;
|
||||
var (ok, msg) = await n.SendTestAsync(CancellationToken.None);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Equal("Telegram non raggiungibile: nessuna risposta in 1 s", msg);
|
||||
Assert.True(DateTime.UtcNow - started < TimeSpan.FromSeconds(8), "il tempo massimo non ha fermato la richiesta");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("", Chat)]
|
||||
[InlineData(" ", Chat)]
|
||||
[InlineData(Token, "")]
|
||||
[InlineData(Token, " ")]
|
||||
public async Task Senza_token_o_chat_non_parte_nessuna_richiesta(string token, string chat)
|
||||
{
|
||||
var (n, fake, _, _) = Make(new AppSettings { TelegramBotToken = token, TelegramChatId = chat }, (_, _) => Task.FromResult(Ok()));
|
||||
await using var _n = n;
|
||||
|
||||
var (ok, msg) = await n.SendTestAsync(CancellationToken.None);
|
||||
n.Enqueue("non deve partire");
|
||||
await Task.Delay(50);
|
||||
|
||||
Assert.False(ok);
|
||||
Assert.Equal("Scrivi token del bot e chat id, salva, poi riprova", msg);
|
||||
Assert.False(n.Configured);
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Il_tempo_massimo_si_normalizza_fra_5_e_60_secondi()
|
||||
{
|
||||
Assert.Equal(15, new AppSettings().TelegramTimeoutSeconds);
|
||||
Assert.Equal(5, SettingsStore.Normalize(new AppSettings { TelegramTimeoutSeconds = 0 }).TelegramTimeoutSeconds);
|
||||
Assert.Equal(60, SettingsStore.Normalize(new AppSettings { TelegramTimeoutSeconds = 600 }).TelegramTimeoutSeconds);
|
||||
Assert.Equal(20, SettingsStore.Normalize(new AppSettings { TelegramTimeoutSeconds = 20 }).TelegramTimeoutSeconds);
|
||||
}
|
||||
|
||||
// ── Coda ────────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task La_coda_prova_tre_volte_con_attese_di_4_e_8_secondi_e_lo_scrive_una_volta()
|
||||
{
|
||||
var (n, fake, log, delays) = Make(Configured(), (_, _) => throw new HttpRequestException("rete giù"));
|
||||
await using var _n = n;
|
||||
|
||||
n.Enqueue("uno");
|
||||
await Until(() => Warnings(log).Count == 1, "la riga dopo tre tentativi");
|
||||
|
||||
Assert.Equal(3, fake.Sends.Count);
|
||||
Assert.Equal(new[] { TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8) }, delays.Retries);
|
||||
Assert.Equal("Messaggio non inviato dopo tre tentativi: rete giù", Assert.Single(Warnings(log)));
|
||||
|
||||
// Un secondo messaggio che non parte non ripete la riga.
|
||||
n.Enqueue("due");
|
||||
await Until(() => fake.Sends.Count == 6 && delays.Retries.Count == 4, "i tre tentativi del secondo messaggio");
|
||||
n.Enqueue("tre");
|
||||
await Until(() => fake.Sends.Count == 9, "i tre tentativi del terzo messaggio");
|
||||
Assert.Single(Warnings(log));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Una_scadenza_nella_coda_si_scrive_e_non_ferma_gli_invii_successivi()
|
||||
{
|
||||
// Il valore vero va da 5 a 60 s (SettingsStore.Normalize); qui 1 s, per non aspettare.
|
||||
// Il primo messaggio non riceve mai risposta: i tre tentativi scadono uno dopo l'altro.
|
||||
var s = Configured();
|
||||
s.TelegramTimeoutSeconds = 1;
|
||||
var (n, fake, log, delays) = Make(s, async (c, ct) =>
|
||||
{
|
||||
if (c.Body.Contains("muto", StringComparison.Ordinal)) await Task.Delay(Timeout.Infinite, ct);
|
||||
return Ok();
|
||||
});
|
||||
await using var _n = n;
|
||||
|
||||
n.Enqueue("muto");
|
||||
await Until(() => Warnings(log).Count == 1, "la riga dopo tre scadenze");
|
||||
|
||||
Assert.Equal("Messaggio non inviato dopo tre tentativi: nessuna risposta in 1 s", Assert.Single(Warnings(log)));
|
||||
Assert.Equal(3, fake.Sends.Count);
|
||||
Assert.Equal(new[] { TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8) }, delays.Retries);
|
||||
|
||||
// La scadenza non ha chiuso il ciclo di invio: il messaggio dopo parte al primo tentativo.
|
||||
n.Enqueue("riparte");
|
||||
await Until(() => fake.Sends.Count == 4, "il messaggio dopo la scadenza");
|
||||
Assert.Contains("riparte", fake.Sends[3].Body, StringComparison.Ordinal);
|
||||
await Task.Delay(50);
|
||||
Assert.Equal(4, fake.Sends.Count);
|
||||
Assert.Equal(2, delays.Retries.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Un_messaggio_che_riparte_rimette_la_riga_al_prossimo_guasto()
|
||||
{
|
||||
var (n, fake, log, _) = Make(Configured(), (c, _) =>
|
||||
c.Body.Contains("guasto", StringComparison.Ordinal)
|
||||
? Task.FromResult(Json(HttpStatusCode.InternalServerError, """{"ok":false}"""))
|
||||
: Task.FromResult(Ok()));
|
||||
await using var _n = n;
|
||||
|
||||
n.Enqueue("guasto uno");
|
||||
await Until(() => Warnings(log).Count == 1, "la prima riga");
|
||||
Assert.Equal("Messaggio non inviato dopo tre tentativi", Warnings(log)[0]);
|
||||
|
||||
n.Enqueue("riparte");
|
||||
await Until(() => fake.Sends.Count == 4, "il messaggio che riparte");
|
||||
|
||||
n.Enqueue("guasto due");
|
||||
await Until(() => Warnings(log).Count == 2, "la seconda riga dopo la ripresa");
|
||||
Assert.Equal(7, fake.Sends.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task La_coda_si_ferma_al_primo_tentativo_riuscito()
|
||||
{
|
||||
var calls = 0;
|
||||
var (n, fake, log, delays) = Make(Configured(), (_, _) =>
|
||||
Interlocked.Increment(ref calls) == 1
|
||||
? throw new HttpRequestException("rete giù")
|
||||
: Task.FromResult(Ok()));
|
||||
await using var _n = n;
|
||||
|
||||
n.Enqueue("uno");
|
||||
n.Enqueue("due");
|
||||
await Until(() => fake.Sends.Count == 3, "i due messaggi");
|
||||
await Task.Delay(50);
|
||||
|
||||
Assert.Equal(3, fake.Sends.Count);
|
||||
Assert.Equal(new[] { TimeSpan.FromSeconds(4) }, delays.Retries);
|
||||
Assert.Empty(Warnings(log));
|
||||
}
|
||||
|
||||
// ── Comandi ─────────────────────────────────────────────────────────
|
||||
|
||||
[Fact]
|
||||
public async Task I_comandi_si_accettano_solo_dalla_chat_configurata()
|
||||
{
|
||||
const string updates = """
|
||||
{"ok":true,"result":[
|
||||
{"update_id":10,"message":{"chat":{"id":999},"text":"/halt"}},
|
||||
{"update_id":11,"message":{"chat":{"id":42},"text":" /Stato@mimante_bot "}},
|
||||
{"update_id":12,"message":{"chat":{"id":42}}},
|
||||
{"update_id":13,"message":{"chat":{"id":-42},"text":"/osserva"}}
|
||||
]}
|
||||
""";
|
||||
var polls = 0;
|
||||
var (n, fake, log, _) = Make(Configured(commands: true), async (c, ct) =>
|
||||
{
|
||||
if (c.Method != "getUpdates") return Ok();
|
||||
if (Interlocked.Increment(ref polls) == 1) return Json(HttpStatusCode.OK, updates);
|
||||
await Task.Delay(Timeout.Infinite, ct); // il polling lungo: nessun messaggio nuovo
|
||||
return Ok();
|
||||
});
|
||||
await using var _n = n;
|
||||
var received = new ConcurrentQueue<string>();
|
||||
n.CommandHandler = command => { received.Enqueue(command); return Task.FromResult("risposta a " + command); };
|
||||
|
||||
await Until(() => fake.Sends.Count == 1 && Volatile.Read(ref polls) >= 2, "la risposta al comando e la lettura successiva");
|
||||
|
||||
Assert.Equal(new[] { "/stato" }, received.ToList());
|
||||
Assert.Contains("risposta a /stato", fake.Sends[0].Body, StringComparison.Ordinal);
|
||||
Assert.Contains("\"chat_id\":\"42\"", fake.Sends[0].Body, StringComparison.Ordinal);
|
||||
|
||||
var gets = fake.Calls.Where(c => c.Method == "getUpdates").ToList();
|
||||
Assert.StartsWith($"{TelegramApi.BaseUrl}/bot{Token}/getUpdates?offset=0&timeout=25", gets[0].Url, StringComparison.Ordinal);
|
||||
Assert.Contains("offset=14&", gets[1].Url, StringComparison.Ordinal);
|
||||
|
||||
var commands = log.Snapshot().Where(e => e.Tag == "TELEGRAM").Select(e => e.Message).ToList();
|
||||
Assert.Equal(new[] { "Comando ricevuto: /stato" }, commands);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Con_i_comandi_spenti_non_si_leggono_i_messaggi()
|
||||
{
|
||||
var (n, fake, _, delays) = Make(Configured(commands: false), (_, _) => Task.FromResult(Ok()));
|
||||
await using var _n = n;
|
||||
n.CommandHandler = _ => Task.FromResult("no");
|
||||
|
||||
await Until(() => delays.Asked.Count(d => d == TimeSpan.FromSeconds(10)) >= 3, "qualche giro del ciclo dei comandi");
|
||||
|
||||
Assert.Empty(fake.Calls);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user