Files
Mimante/tests/Mimante.Tests/GuideTests.cs
T
Alby96andClaude Opus 5.5 187e0a0f1f
verifica / controlli (push) Successful in 51s
verifica / prove (push) Successful in 2m11s
verifica / immagine (push) Successful in 11m4s
«Prova gli avvisi» in Impostazioni ▸ Telegram, versione 1.9.4 (#35)
Il messaggio di prova dice solo che la chat funziona; Alberto ha chiesto di
vedere come arrivano davvero gli avvisi. Il bottone nuovo manda un esempio
per ognuno dei 13 avvisi che il bot manda (vinta, persa, sessione, HALT e
ripresa, spazio dati, errore del motore, database fermo e fermo all'avvio,
riepilogo, puntate gratis, pausa del riscatto, forziere), costruito con lo
stesso formatter del messaggio vero e dati finti. Il titolo comincia per
«Prova:»; se l'interruttore di quel tipo è spento il testo lo dice (per il
forziere contano «Avviso forzieri» e «Messaggio su Telegram»).

Gli invii partono subito, senza coda, uno ogni 1,5 s per stare sotto il
limite di Telegram di un messaggio al secondo per chat; al primo rifiuto o
errore la prova si ferma e dice quanti ne sono partiti e perché. Una seconda
prova mentre la prima gira è rifiutata, e un annullamento libera il bottone.
Nel registro una riga con i soli numeri.

Per usare gli stessi formatter, i messaggi che si scrivevano sul posto (spazio
dati, database fermo, puntate gratis, pausa, forziere) sono ora funzioni di
TelegramFormat: il testo che arriva è lo stesso. Una prova ricava dai sorgenti
i formatter usati dagli avvisi veri e fallisce se uno resta senza esempio.

Versione 1.9.4, con la sezione del CHANGELOG che riporta anche la prova del
simulatore stabilizzata (#51) e le chiusure del 28/11; la guida dice il nuovo
stato delle prove dal vivo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:24:20 +01:00

179 lines
9.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Text.RegularExpressions;
using Xunit;
namespace Mimante.Tests;
/// <summary>
/// The user guide (docs/guida, published as the wiki of the repository, as in Febe): every page exists with a title,
/// every link between pages points to a page that exists in the wiki format, the sidebar and the home page reach every
/// page, and the points Alberto looks for are on the page where he looks for them.
/// </summary>
public sealed partial class GuideTests
{
/// <summary>The pages of the wiki, without «.md», in the order of the sidebar.</summary>
public static readonly string[] Pages =
[
"Home",
"Installazione-Docker-e-Unraid",
"Primo-avvio",
"Aste",
"Cerca-e-prodotti",
"Come-decide-il-modello",
"Paletti-e-rischio",
"Storico-ed-esportazioni",
"Puntate-gratis",
"Impostazioni",
"Telegram",
"Dati-e-backup",
"Sicurezza-e-riservatezza",
"Problemi-comuni",
"Sviluppo",
];
/// <summary>(point, page that must say it, phrases that must all be there), compared without case, emphasis and line breaks.</summary>
public static TheoryData<string, string, string[]> MandatoryPoints => new()
{
{ "la sessione si incolla nelle Impostazioni", "Primo-avvio", ["impostazioni", "accesso a bidoo", "copia come curl"] },
{ "senza utente il bot non punta", "Primo-avvio", ["non punta"] },
{ "il registro risponde in HTTP", "Installazione-Docker-e-Unraid", ["--insecure-registry", "ui_password", "db_password", "db_host"] },
{ "aggiornare da Bidoo BidBot", "Installazione-Docker-e-Unraid", ["/mnt/user/appdata/mimante", "pg_dump"] },
{ "i tre modi delle aste", "Aste", ["ferma", "osserva", "attiva"] },
{ "il modello è l'unico decisore", "Come-decide-il-modello", ["paletti"] },
{ "prima del modello pronto si punta entro i paletti (ADR 0018)", "Come-decide-il-modello",
["un'eccezione", "non ancora pronto", "valore del prodotto è ignoto", "apprendimento acceso", "la spesa non ha tetto"] },
{ "in Attiva presto la spesa non ha tetto (ADR 0018)", "Primo-avvio",
["modello non ancora pronto", "valore del prodotto è ignoto", "tutti a zero", "la spesa non ha tetto"] },
{ "DB_PORT e PORT non si leggono più (ADR 0019)", "Installazione-Docker-e-Unraid", ["db_port e port", "non si leggono più", "8080"] },
{ "l'HALT si toglie a mano", "Paletti-e-rischio", ["halt", "togli il blocco"] },
{ "il riscatto è spento di fabbrica", "Puntate-gratis", ["spento di fabbrica"] },
{ "Telegram con BotFather", "Telegram", ["@botfather", "/newbot", "chat id"] },
{ "la prova degli avvisi", "Telegram", ["prova gli avvisi", "arrivano davvero sul telefono", "prova:", "in uso è spento"] },
{ "chi ha /config ha la sessione", "Sicurezza-e-riservatezza", ["/config/sessione", "internet"] },
{ "pubblicare la guida", "Sviluppo", ["docs/guida", "mimante.wiki.git"] },
};
[Fact]
public void EveryPageExistsWithATitle()
{
var guide = GuideFolder();
foreach (var page in Pages)
{
var path = Path.Combine(guide, page + ".md");
Assert.True(File.Exists(path), $"manca la pagina {page}");
Assert.StartsWith("# ", File.ReadLines(path).First());
}
Assert.True(File.Exists(Path.Combine(guide, "_Sidebar.md")), "manca _Sidebar.md");
var unknown = Directory.EnumerateFiles(guide, "*.md")
.Select(Path.GetFileNameWithoutExtension)
.Where(name => name != "_Sidebar" && !Pages.Contains(name))
.ToList();
Assert.True(unknown.Count == 0, "pagine non elencate in GuideTests.Pages: " + string.Join(", ", unknown));
}
[Fact]
public void EveryWikiLinkPointsToAnExistingPageAndEveryPageIsReachable()
{
var guide = GuideFolder();
var problems = new List<string>();
var linkedFrom = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);
foreach (var file in Directory.EnumerateFiles(guide, "*.md"))
{
var name = Path.GetFileNameWithoutExtension(file);
var targets = new HashSet<string>(StringComparer.Ordinal);
// Code is not a link: «`[Testo](Nome-Pagina)`» explains the format.
var text = InlineCode().Replace(FencedCode().Replace(File.ReadAllText(file), string.Empty), string.Empty);
foreach (Match match in Link().Matches(text))
{
var target = match.Groups["target"].Value;
if (target.StartsWith("http://", StringComparison.Ordinal) || target.StartsWith("https://", StringComparison.Ordinal))
continue;
if (!WikiPage().IsMatch(target))
problems.Add($"{name}: «{target}» non è il nome di una pagina del wiki (niente .md, cartelle o ancore)");
else if (target == "_Sidebar" || !File.Exists(Path.Combine(guide, target + ".md")))
problems.Add($"{name}: «{target}» non esiste");
targets.Add(target);
}
linkedFrom[name] = targets;
}
Assert.True(problems.Count == 0, string.Join("\n", problems));
foreach (var page in Pages)
{
Assert.True(linkedFrom["_Sidebar"].Contains(page), $"la barra laterale non porta a {page}");
if (page != "Home") Assert.True(linkedFrom["Home"].Contains(page), $"l'indice della pagina iniziale non porta a {page}");
}
}
[Fact]
public void ImagesComeFromTheScreenshotsOfTheRepository()
{
var guide = GuideFolder();
var shots = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(guide))!, "docs", "schermate");
var problems = new List<string>();
foreach (var file in Directory.EnumerateFiles(guide, "*.md"))
{
foreach (Match match in Image().Matches(File.ReadAllText(file)))
{
var target = match.Groups["target"].Value;
const string prefix = "https://gitea.encke-hake.ts.net/Alby96/Mimante/raw/branch/main/docs/schermate/";
if (!target.StartsWith(prefix, StringComparison.Ordinal))
problems.Add($"{Path.GetFileName(file)}: immagine fuori da docs/schermate: {target}");
else if (!File.Exists(Path.Combine(shots, target[prefix.Length..])))
problems.Add($"{Path.GetFileName(file)}: la schermata {target[prefix.Length..]} non esiste");
}
}
Assert.True(problems.Count == 0, string.Join("\n", problems));
}
[Theory]
[MemberData(nameof(MandatoryPoints))]
public void TheGuideSaysWhatAlbertoLooksFor(string point, string page, string[] phrases)
{
var text = Normalize(File.ReadAllText(Path.Combine(GuideFolder(), page + ".md")));
var missing = phrases.Where(p => !text.Contains(Normalize(p), StringComparison.Ordinal)).ToList();
Assert.True(missing.Count == 0, $"«{point}»: in {page} mancano: {string.Join(" | ", missing)}");
}
/// <summary>«Prova gli avvisi» in the Telegram page says how many messages it sends: the same number as the samples.</summary>
[Fact]
public void TheTelegramPageCountsTheAlertSamples()
{
var count = Mimante.Telegram.TelegramFormat.Samples(new Mimante.Settings.AppSettings()).Count;
var text = Normalize(File.ReadAllText(Path.Combine(GuideFolder(), "Telegram.md")));
Assert.Contains($"manda {count} messaggi, uno per ogni tipo", text, StringComparison.Ordinal);
Assert.Contains($"inviati: {count} di {count}", text, StringComparison.Ordinal);
Assert.Contains($"{count} messaggi con il titolo", Normalize(File.ReadAllText(Path.Combine(GuideFolder(), "Impostazioni.md"))), StringComparison.Ordinal);
}
/// <summary>Lower case, typographic apostrophes as plain ones, no emphasis or code marks, one space for any run of blanks.</summary>
public static string Normalize(string text)
{
var plain = text.Replace("**", "", StringComparison.Ordinal).Replace("`", "", StringComparison.Ordinal).Replace('’', '\'').ToLowerInvariant();
return Blanks().Replace(plain, " ");
}
private static string GuideFolder()
{
for (var d = new DirectoryInfo(AppContext.BaseDirectory); d != null; d = d.Parent)
if (File.Exists(Path.Combine(d.FullName, "Mimante.slnx"))) return Path.Combine(d.FullName, "docs", "guida");
throw new InvalidOperationException("Mimante.slnx not found above " + AppContext.BaseDirectory);
}
[GeneratedRegex(@"(?<!!)\[[^\]]*\]\((?<target>[^)\s]+)\)")]
private static partial Regex Link();
[GeneratedRegex(@"!\[[^\]]*\]\((?<target>[^)\s]+)\)")]
private static partial Regex Image();
[GeneratedRegex(@"^_?[A-Za-z0-9]+(-[A-Za-z0-9]+)*$")]
private static partial Regex WikiPage();
[GeneratedRegex(@"\s+")]
private static partial Regex Blanks();
[GeneratedRegex(@"^```.*?^```", RegexOptions.Singleline | RegexOptions.Multiline)]
private static partial Regex FencedCode();
[GeneratedRegex(@"`[^`\n]*`")]
private static partial Regex InlineCode();
}