using System.Text.RegularExpressions;
namespace Febe.Tests.Docs;
///
/// The user guide (docs/guida, published as the wiki of the repository): every page exists, every link between pages
/// points to a page that exists, and the guide says everything spec §15 lists under «Che cosa la guida deve dire per
/// forza», on the pages where Alberto looks for it.
///
[TestClass]
public sealed partial class GuideTests
{
/// The pages of the wiki, without «.md».
public static readonly string[] Pages =
[
"Home",
"Installazione-Docker-e-Unraid",
"Installazione-Windows",
"Primo-collegamento",
"Account-e-impostazioni",
"Libreria",
"Importazione",
"Limiti-e-comportamento",
"Attivita-e-arresti",
"Avvisi-e-Telegram",
"Copie-e-ricostruzione",
"Sicurezza-e-riservatezza",
"Problemi-comuni",
"Ipotesi-da-verificare",
"Sviluppo",
];
///
/// The mandatory points of spec §15: (point, pages that must say it, phrases that must all be there). Phrases are
/// compared without case, emphasis and line breaks.
///
public static IEnumerable MandatoryPoints =>
[
["rischio per l'account e condizioni d'uso", new[] { "Home" }, new[] { "contro le condizioni d'uso di Instagram", "la limitazione o la chiusura dell'account" }],
["che cosa fa Febe per ridurre il rischio", new[] { "Home" }, new[] { "che cosa fa febe per ridurre il rischio", "tetti giornalieri e orari", "al primo segnale di instagram si ferma" }],
["che cosa Febe non fa", new[] { "Home" }, new[] { "che cosa febe non fa", "non risolve captcha", "non usa proxy", "azzerare il rischio" }],
["le storie aperte da Febe risultano viste", new[] { "Home", "Account-e-impostazioni", "Sicurezza-e-riservatezza" }, new[] { "le storie aperte da febe risultano viste" }],
["contenitore e desktop non insieme sullo stesso account", new[] { "Home", "Installazione-Docker-e-Unraid", "Installazione-Windows", "Primo-collegamento", "Sicurezza-e-riservatezza" }, new[] { "non vanno usati insieme sullo stesso account" }],
["chi ha la cartella dei dati o una copia ha la sessione", new[] { "Primo-collegamento", "Sicurezza-e-riservatezza" }, new[] { "chi ha la cartella dei dati, o una sua copia, ha la sessione di instagram" }],
["l'interfaccia Docker non va esposta su Internet", new[] { "Sicurezza-e-riservatezza" }, new[] { "non esporre mai l'interfaccia docker su internet", "vpn", "https" }],
["in Docker la password di Instagram passa dal server", new[] { "Primo-collegamento", "Sicurezza-e-riservatezza" }, new[] { "la password di instagram passa dal server" }],
["il compromesso sulla sandbox di Chromium", new[] { "Installazione-Docker-e-Unraid", "Sicurezza-e-riservatezza" }, new[] { "sandbox", "seccomp", "febe_senza_sandbox=1", "compromesso" }],
["che cosa fare dopo una verifica o un rallentamento", new[] { "Attivita-e-arresti" }, new[] { "che cosa fare dopo una verifica", "che cosa fare dopo un rallentamento", "completa la verifica a mano", "riprendi", "tre rallentamenti in sette giorni" }],
["dove sono le copie del database e come si ricostruisce", new[] { "Copie-e-ricostruzione" }, new[] { "/dati/copie", "%localappdata%\\febe\\copie", "febe-aaaa-mm-gg.sqlite", "ricostruisci il database dalla libreria", "_febe.jsonl" }],
["esportazione CSV dell'elenco (§4.8)", new[] { "Libreria" }, new[] { "esporta l'elenco", "`;`", "utf-8 con bom" }],
["Telegram: BotFather e identificativo della chat (§13.3)", new[] { "Avvisi-e-Telegram" }, new[] { "@botfather", "/newbot", "getupdates", "\"chat\":{\"id\":", "invia una prova" }],
["pagina sui problemi comuni (M8)", new[] { "Problemi-comuni" }, new[] { "formato non riconosciuto", "disco quasi pieno", "no usable sandbox", "manca la password dell'interfaccia" }],
["ipotesi H1–H11 e S1–S6", new[] { "Ipotesi-da-verificare" }, new[] { "| h1 |", "| h11 |", "| s1 |", "| s6 |", "account di prova" }],
];
public static string GuideFolder()
{
var folder = new DirectoryInfo(AppContext.BaseDirectory);
while (folder is not null && !File.Exists(Path.Combine(folder.FullName, "Febe.slnx")))
{
folder = folder.Parent;
}
if (folder is null)
{
Assert.Inconclusive("Radice del repository non trovata.");
}
var guide = Path.Combine(folder.FullName, "docs", "guida");
var isCheckout = Directory.Exists(Path.Combine(folder.FullName, ".git")) || File.Exists(Path.Combine(folder.FullName, ".git"));
if (!Directory.Exists(guide) && !isCheckout)
{
// The build of the Docker image copies the sources without docs/ (see .dockerignore).
Assert.Inconclusive("Questa copia del repository non ha docs/ (costruzione dell'immagine Docker).");
}
Assert.IsTrue(Directory.Exists(guide), guide);
return guide;
}
[TestMethod]
public void EveryPageExistsWithATitle()
{
var guide = GuideFolder();
foreach (var page in Pages)
{
var path = Path.Combine(guide, page + ".md");
Assert.IsTrue(File.Exists(path), $"manca la pagina {page}");
var first = File.ReadLines(path).First();
StringAssert.StartsWith(first, "# ", $"{page}: la prima riga è il titolo");
}
Assert.IsTrue(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.IsEmpty(unknown, "pagine non elencate in GuideTests.Pages: " + string.Join(", ", unknown));
}
[TestMethod]
public void EveryWikiLinkPointsToAnExistingPage()
{
var guide = GuideFolder();
var problems = new List();
var linkedFrom = new Dictionary>(StringComparer.Ordinal);
foreach (var file in Directory.EnumerateFiles(guide, "*.md"))
{
var name = Path.GetFileNameWithoutExtension(file);
var targets = new HashSet(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) || target.StartsWith("mailto:", 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 (!File.Exists(Path.Combine(guide, target + ".md")) || target == "_Sidebar")
{
problems.Add($"{name}: «{target}» non esiste");
}
targets.Add(target);
}
linkedFrom[name] = targets;
}
Assert.IsEmpty(problems, string.Join("\n", problems));
var fromSidebar = linkedFrom["_Sidebar"];
var fromHome = linkedFrom["Home"];
foreach (var page in Pages)
{
Assert.Contains(page, fromSidebar, $"la barra laterale non porta a {page}");
if (page != "Home")
{
Assert.Contains(page, fromHome, $"l'indice della pagina iniziale non porta a {page}");
}
}
}
[TestMethod]
[DynamicData(nameof(MandatoryPoints))]
public void TheGuideSaysWhatTheSpecificationRequires(string point, string[] pages, string[] phrases)
{
var guide = GuideFolder();
foreach (var page in pages)
{
var text = Normalize(File.ReadAllText(Path.Combine(guide, page + ".md")));
var missing = phrases.Where(p => !text.Contains(Normalize(p), StringComparison.Ordinal)).ToList();
Assert.IsEmpty(missing, $"«{point}»: in {page} mancano: {string.Join(" | ", missing)}");
}
}
/// Lower case, typographic apostrophes as plain ones, no emphasis, one space for any run of blanks.
public static string Normalize(string text)
{
ArgumentNullException.ThrowIfNull(text);
var plain = text.Replace("**", string.Empty, StringComparison.Ordinal).Replace('’', '\'').ToLowerInvariant();
return Blanks().Replace(plain, " ");
}
[GeneratedRegex(@"(?[^)\s]+)\)")]
private static partial Regex Link();
[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();
}