Correzioni della revisione di C6: installatore, CI senza jq, caratteri e schermate senza Node
Le 14 osservazioni della revisione di funzione/senza-terzi, ciascuna con la prova che l'avrebbe trovata. Installatore: un aggiornamento senza /D= va nella cartella già installata (InstallLocation) invece che in quella predefinita, che lasciava la vecchia copia. Una cartella senza permessi non sembra più «Febe aperto». La dimensione in «App installate» conta solo i due file dell'installatore. I file in sola lettura si sostituiscono e si tolgono. «Febe» in Esegui all'avvio si toglie solo se avvia quella copia, non un Febe portatile. Febe parte alla fine solo con «Fine» e la casella spuntata. /PROVA= rifiuta la radice di un disco. CI: jq non c'era ed era un componente esterno. JSON letto e scritto con .gitea/scripts/json.sh (json-campi.awk e json-stringa.awk sul lettore json.awk) per gitleaks, Trivy e la release. Le credenziali del registro stanno solo in un DOCKER_CONFIG temporaneo della pubblicazione, con plugin, contesti e contesto corrente del runner, tolto alla fine. Le prove del rilascio girano in debian:trixie con Chromium, come la verifica, senza prove saltate. Ogni flusso usa shell: bash. Caratteri: tolti fonts-liberation e fonts-noto-color-emoji dall'immagine e dalle prove della CI, perché Chromium non li chiede. Resta fonts-dejavu-core. Icone: la prova della griglia legge davvero i percorsi SVG (tutti i comandi, archi e curve) e i punti. La lettura dei nomi delle icone vede ogni forma con cui l'interfaccia li chiede. Schermate: tools/schermate (Node) diventa tools/Febe.Schermate, in C# con ClientWebSocket e System.Text.Json, nessun pacchetto, solo verso indirizzi di questo computer. Provato contro una dimostrazione con Edge su Windows. Documenti: CLAUDE.md, processo, guida, LEGGIMI e docker.md aggiornati. Righe nuove in decisioni.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
525d7dfdaa
commit
be662f2d28
46 files changed
+2091
-283
No files matched your search
@@ -181,6 +181,16 @@ public sealed class InstallerTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheLastPageStartsFebeOnlyWithFine()
|
||||
{
|
||||
// Windows gives back the state of the box on a cancel too: Esc or the close button must not start Febe.
|
||||
Assert.IsTrue(DialogInterface.StartsFebe(DialogInterface.Yes, runChecked: true));
|
||||
Assert.IsFalse(DialogInterface.StartsFebe(DialogInterface.Yes, runChecked: false));
|
||||
Assert.IsFalse(DialogInterface.StartsFebe(TaskDialog.CancelId, runChecked: true), "Esc or ✕ with «Apri Febe adesso» ticked");
|
||||
Assert.IsFalse(DialogInterface.StartsFebe(TaskDialog.CancelId, runChecked: false));
|
||||
}
|
||||
|
||||
private static (string Setup, byte[] Program) Pack(TestFolder folder, string version, int seed)
|
||||
{
|
||||
// Not an executable: if anything tried to start it, Windows would refuse it at once.
|
||||
|
||||
@@ -116,6 +116,13 @@ public sealed partial class InstallerTests
|
||||
Assert.ThrowsExactly<ArgumentException>(() => CommandLine.Parse(["/D=relativa"]));
|
||||
Assert.ThrowsExactly<ArgumentException>(() => CommandLine.Parse(["/D="]));
|
||||
|
||||
// /PROVA= at the root of a drive: refused here, with its message, not later as an unhandled crash (the name of
|
||||
// the folder is the registry key of the test, and a root has none).
|
||||
var driveRoot = Path.GetPathRoot(Path.GetTempPath())!;
|
||||
var refused = Assert.ThrowsExactly<ArgumentException>(() => CommandLine.Parse(["/S", "/PROVA=" + driveRoot]));
|
||||
StringAssert.Contains(refused.Message, "/PROVA=");
|
||||
Assert.ThrowsExactly<ArgumentException>(() => Locations.ForTest(driveRoot), "what Parse refuses is what ForTest would refuse");
|
||||
|
||||
// The build tool.
|
||||
Assert.AreEqual(ToolCommand.Pack, CommandLine.Parse(["--impacchetta", "a", "b", "1.0.0", "c"]).Tool);
|
||||
Assert.AreEqual(ToolCommand.Verify, CommandLine.Parse(["--verifica", "a", "b"]).Tool);
|
||||
@@ -194,6 +201,104 @@ public sealed partial class InstallerTests
|
||||
Assert.IsEmpty(bed.System.Started, "«Apri Febe adesso» unchecked");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnUpdateWithoutAFolderGoesWhereFebeIsAlreadyInstalled()
|
||||
{
|
||||
using var bed = new SetupBed("dove-era");
|
||||
var folder = Path.Combine(bed.Root, "Altrove", "Febe");
|
||||
var first = bed.Package("0.1.1", seed: 20);
|
||||
Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, CommandLine.Parse(["/D=" + folder])));
|
||||
|
||||
// With the dialogs: the first page names the folder where Febe is, and the update replaces that program.
|
||||
var second = bed.Package("0.2.0", seed: 21);
|
||||
var ui = new ScriptedInterface();
|
||||
Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine()));
|
||||
Assert.AreEqual(folder, ui.Folder);
|
||||
Assert.AreEqual("0.1.1", ui.Version);
|
||||
CollectionAssert.AreEqual(bed.Program(21), File.ReadAllBytes(Path.Combine(folder, "Febe.exe")));
|
||||
Assert.IsFalse(Directory.Exists(bed.Locations.DefaultInstallFolder), "no second Febe in the default folder");
|
||||
Assert.AreEqual(folder, bed.System.String(bed.Locations.UninstallKey, "InstallLocation"));
|
||||
Assert.IsTrue(bed.System.Shortcuts.All(s => s.Target == Path.Combine(folder, "Febe.exe")));
|
||||
|
||||
// Silent too; and a Febe open there is seen there.
|
||||
var third = bed.Package("0.3.0", seed: 22);
|
||||
using (new FileStream(Path.Combine(folder, "Febe.exe"), FileMode.Open, FileAccess.Read, FileShare.None))
|
||||
{
|
||||
var errors = new StringWriter();
|
||||
Assert.AreEqual(ExitCodes.Failed, bed.Flow(new SilentInterface(errors)).Install(third, Package.Read(third)!, CommandLine.Parse(["/S"])));
|
||||
StringAssert.Contains(errors.ToString(), "Febe è aperto");
|
||||
}
|
||||
|
||||
Assert.AreEqual(ExitCodes.Done, bed.Flow(new SilentInterface(TextWriter.Null)).Install(third, Package.Read(third)!, CommandLine.Parse(["/S"])));
|
||||
CollectionAssert.AreEqual(bed.Program(22), File.ReadAllBytes(Path.Combine(folder, "Febe.exe")));
|
||||
Assert.IsFalse(Directory.Exists(bed.Locations.DefaultInstallFolder));
|
||||
|
||||
// /D= still decides when given; an entry whose folder is not a full path counts as none.
|
||||
var actions = new SetupActions(bed.System, bed.Locations);
|
||||
Assert.AreEqual(folder, actions.InstalledFolder());
|
||||
bed.System.WriteUserString(bed.Locations.UninstallKey, "InstallLocation", "Programs\\Febe");
|
||||
Assert.IsNull(actions.InstalledFolder());
|
||||
bed.System.WriteUserString(bed.Locations.UninstallKey, "InstallLocation", folder + Path.DirectorySeparatorChar);
|
||||
Assert.AreEqual(folder, actions.InstalledFolder());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheSizeInAppsInstalledCountsOnlyTheFilesOfTheInstaller()
|
||||
{
|
||||
using var bed = new SetupBed("dimensione");
|
||||
var folder = Path.Combine(bed.Root, "Disco", "Febe");
|
||||
|
||||
// A folder with something else in it, and below it: never walked (a drive root would have folders nobody may read).
|
||||
Directory.CreateDirectory(Path.Combine(folder, "altro", "dentro"));
|
||||
File.WriteAllBytes(Path.Combine(folder, "altro", "dentro", "grande.bin"), new byte[3 * 1024 * 1024]);
|
||||
File.WriteAllBytes(Path.Combine(folder, "accanto.bin"), new byte[1024 * 1024]);
|
||||
var setup = bed.Package("0.1.2", seed: 23);
|
||||
Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, CommandLine.Parse(["/D=" + folder])));
|
||||
|
||||
var ours = new FileInfo(Path.Combine(folder, "Febe.exe")).Length + new FileInfo(Path.Combine(folder, "Disinstalla Febe.exe")).Length;
|
||||
Assert.AreEqual((int)(ours / 1024), bed.System.ReadUserDword(bed.Locations.UninstallKey, "EstimatedSize"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AReadOnlyFebeIsNotAnOpenFebeAndIsReplacedAndRemoved()
|
||||
{
|
||||
using var bed = new SetupBed("sola-lettura");
|
||||
var first = bed.Package("0.1.1", seed: 24);
|
||||
Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, new CommandLine()));
|
||||
var folder = bed.Locations.DefaultInstallFolder;
|
||||
var executable = Path.Combine(folder, "Febe.exe");
|
||||
var uninstaller = Path.Combine(folder, "Disinstalla Febe.exe");
|
||||
try
|
||||
{
|
||||
// Left read-only by a copy or a restore: Windows refuses to open it for writing, but nothing is running.
|
||||
File.SetAttributes(executable, File.GetAttributes(executable) | FileAttributes.ReadOnly);
|
||||
File.SetAttributes(uninstaller, File.GetAttributes(uninstaller) | FileAttributes.ReadOnly);
|
||||
Assert.IsFalse(SetupActions.IsFebeOpen(folder), "«Riprova» could never help: not «Febe è aperto»");
|
||||
|
||||
var second = bed.Package("0.2.0", seed: 25);
|
||||
var ui = new ScriptedInterface { Retries = new Queue<bool>([true, true, false]) };
|
||||
Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine()));
|
||||
CollectionAssert.AreEqual(new[] { "benvenuto", "avanzamento", "installato" }, ui.Calls);
|
||||
CollectionAssert.AreEqual(bed.Program(25), File.ReadAllBytes(executable));
|
||||
|
||||
File.SetAttributes(executable, File.GetAttributes(executable) | FileAttributes.ReadOnly);
|
||||
File.SetAttributes(uninstaller, File.GetAttributes(uninstaller) | FileAttributes.ReadOnly);
|
||||
Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder])));
|
||||
Assert.IsFalse(File.Exists(executable));
|
||||
Assert.IsFalse(File.Exists(uninstaller));
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var file in new[] { executable, uninstaller })
|
||||
{
|
||||
if (File.Exists(file))
|
||||
{
|
||||
File.SetAttributes(file, FileAttributes.Normal);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void AnInstallationOverAnotherReplacesTheProgramAndKeepsTheData()
|
||||
{
|
||||
@@ -290,10 +395,14 @@ public sealed partial class InstallerTests
|
||||
CollectionAssert.AreEqual(new[] { "conferma", "disinstallato" }, ui.Calls);
|
||||
Assert.AreEqual((data.MovedDataFolder, bed.Locations.Library), ui.UninstalledWith);
|
||||
|
||||
// A second time, with the program folder now empty: the folder goes too.
|
||||
// A second time, with the program folder now empty: the folder goes too. Meanwhile a portable Febe with the
|
||||
// default Data folder took «Febe» for itself: it starts another Febe.exe, so it stays.
|
||||
File.Delete(Path.Combine(folder, "appunti.txt"));
|
||||
var portable = Autostart.Command(Path.Combine(bed.Root, "Portabile", "Febe.exe"));
|
||||
bed.System.WriteUserString(run, "Febe", portable);
|
||||
Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder])));
|
||||
Assert.IsFalse(Directory.Exists(folder));
|
||||
Assert.AreEqual(portable, bed.System.String(run, "Febe"), "«Febe» of another Febe.exe is not ours to remove");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
<ProjectReference Include="..\..\src\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\Febe.Installer\Febe.Installer.csproj" />
|
||||
<ProjectReference Include="..\..\tools\Febe.Sonda\Febe.Sonda.csproj" />
|
||||
<ProjectReference Include="..\..\tools\Febe.Schermate\Febe.Schermate.csproj" />
|
||||
<ProjectReference Include="..\..\tools\Febe.SitoDiProva\Febe.SitoDiProva.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -22,9 +22,7 @@ public sealed partial class ImageContentsTests
|
||||
["libstdc++6"] = "loaded by libcoreclr, libclrjit and libhostfxr",
|
||||
["libgcc-s1"] = ".NET and Chromium",
|
||||
["zlib1g"] = "a direct dependency of Chromium",
|
||||
["fonts-dejavu-core"] = "the first font fontconfig asks for",
|
||||
["fonts-liberation"] = "Arial, Helvetica and Times with the same metrics",
|
||||
["fonts-noto-color-emoji"] = "emoji in the remote view",
|
||||
["fonts-dejavu-core"] = "the first font fontconfig asks for: without a font Chromium draws no text",
|
||||
["ca-certificates"] = "certificate authorities for .NET TLS",
|
||||
["tzdata"] = "time zones for the engine and Chromium",
|
||||
["locales"] = "generates it_IT.UTF-8 for the C library Chromium runs with",
|
||||
@@ -40,7 +38,10 @@ public sealed partial class ImageContentsTests
|
||||
private static readonly string[] Required = ["chromium", "chromium-l10n", "xvfb", "libicu76", "libssl3t64", "ca-certificates", "tzdata", "locales"];
|
||||
|
||||
/// <summary>Programs that must not come back: an init of others, privilege tools, downloaders, other runtimes.</summary>
|
||||
private static readonly string[] Forbidden = ["tini", "dumb-init", "gosu", "su-exec", "sudo", "curl", "wget", "nodejs", "npm", "python3"];
|
||||
private static readonly string[] Forbidden =
|
||||
["tini", "dumb-init", "gosu", "su-exec", "sudo", "curl", "wget", "nodejs", "npm", "python3", "jq",
|
||||
// Fonts for looks only: Chromium does not ask for them (Liberation is a Recommends, the emoji font nothing).
|
||||
"fonts-liberation", "fonts-liberation2", "fonts-noto-color-emoji", "fonts-noto-core", "fonts-noto"];
|
||||
|
||||
[TestMethod]
|
||||
public void TheImageInstallsOnlyChromiumWhatItNeedsXvfbAndWhatTheDotNetRuntimeNeeds()
|
||||
@@ -67,6 +68,21 @@ public sealed partial class ImageContentsTests
|
||||
Assert.AreEqual(1, Regex.Matches(Code(dockerfile), @"apt-get install").Count, "a single apt-get install, in the runtime stage");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheTestsOfTheCiDrawWithTheSameFontsAsTheImage()
|
||||
{
|
||||
var environment = Repository.PathOf(".gitea", "scripts", "ambiente-prove.sh");
|
||||
if (!File.Exists(environment))
|
||||
{
|
||||
Assert.Inconclusive("Questa copia del repository non ha .gitea/ (costruzione dell'immagine Docker).");
|
||||
}
|
||||
|
||||
static string[] Fonts(string text) => [.. Regex.Matches(text, @"\bfonts-[a-z0-9-]+").Select(m => m.Value).Distinct().Order(StringComparer.Ordinal)];
|
||||
var image = Fonts(string.Join('\n', InstalledPackages(RuntimeStage())));
|
||||
CollectionAssert.AreEqual(new[] { "fonts-dejavu-core" }, image, "one font, the one fontconfig asks for");
|
||||
CollectionAssert.AreEqual(image, Fonts(Code(File.ReadAllText(environment))), "ambiente-prove.sh installs the fonts of the image, no more");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryInstalledPackageHasItsReasonNextToTheList()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Packaging;
|
||||
|
||||
/// <summary>
|
||||
/// JSON in the CI without third-party programs (decision of 18 November 2026: only gitleaks and Trivy come from
|
||||
/// outside): .gitea/scripts/json.sh reads with json.awk and json-campi.awk and writes strings with json-stringa.awk, in
|
||||
/// place of jq for the release, the summaries of gitleaks and Trivy and the credentials of the registry. The credentials
|
||||
/// go into a client configuration of the publication only, never into the runner's. Every workflow runs its steps with
|
||||
/// bash, and the release tests run like those of the verification, in Debian with Chromium and no test skipped.
|
||||
/// </summary>
|
||||
public sealed partial class PipelineTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void NoJqAnywhereInTheCiNorInTheBuild()
|
||||
{
|
||||
var files = AllCiFiles();
|
||||
foreach (var path in new[] { Repository.PathOf("installer", "costruisci.sh"), Repository.PathOf("docker", "entrypoint.sh") })
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
files.Add((Path.GetFileName(path), Read(path)));
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (name, text) in files)
|
||||
{
|
||||
foreach (var line in Code(text).Split('\n'))
|
||||
{
|
||||
Assert.IsFalse(JqWord().IsMatch(line), $"{name}: «{line.Trim()}» uses jq, a program of others");
|
||||
}
|
||||
}
|
||||
|
||||
// What took its place is ours: the reader and the writer of json.sh, and nothing edits the client configuration
|
||||
// of the runner any more.
|
||||
StringAssert.Contains(Script("json.sh"), "-f \"$qui/json.awk\" -f \"$qui/json-campi.awk\"");
|
||||
StringAssert.Contains(Script("json.sh"), "awk -f \"$qui/json-stringa.awk\"");
|
||||
var release = Step(Job(Workflow("rilascio.yml"), "release"), "Release con installatore");
|
||||
StringAssert.Contains(release, "bash .gitea/scripts/json.sh campi \"\" id \"$RISPOSTA\"");
|
||||
StringAssert.Contains(release, "bash .gitea/scripts/json.sh campi \"*\" name \"$RISPOSTA\"");
|
||||
StringAssert.Contains(release, "bash .gitea/scripts/json.sh stringa \"$NOTE\"");
|
||||
StringAssert.Contains(Script("segreti.sh"), "json.sh\" campi \"*\" RuleID,File,StartLine,Commit,Fingerprint");
|
||||
StringAssert.Contains(Script("scansione-immagine.sh"), "json.sh\" campi \"Results/*/Vulnerabilities/*\" Severity,FixedVersion");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryWorkflowRunsItsStepsWithBash()
|
||||
{
|
||||
foreach (var name in Workflows)
|
||||
{
|
||||
var code = Code(Workflow(name));
|
||||
StringAssert.Contains(code, "\ndefaults:\n run:\n shell: bash\n", $"{name}: bash -e -o pipefail whatever the default shell of the runner or of the container");
|
||||
foreach (Match shell in Regex.Matches(code, @"^\s+shell:[ \t]*(?<shell>\S*)", RegexOptions.Multiline))
|
||||
{
|
||||
Assert.AreEqual("bash", shell.Groups["shell"].Value, $"{name}: no step with another shell");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheReleaseRunsTheTestsLikeTheVerificationWithTheBrowserAndNoneSkipped()
|
||||
{
|
||||
var verification = Job(Workflow("verifica.yml"), "prove");
|
||||
var release = Job(Workflow("rilascio.yml"), "prove");
|
||||
foreach (var rule in new[]
|
||||
{
|
||||
"container:\n image: debian:trixie\n options: --shm-size=1g",
|
||||
"FEBE_CHROMIUM: /usr/bin/chromium",
|
||||
"- name: Git e curl per i sorgenti",
|
||||
"bash .gitea/scripts/ambiente-prove.sh",
|
||||
"bash .gitea/scripts/riepilogo-prove.sh out/prove 0",
|
||||
})
|
||||
{
|
||||
StringAssert.Contains(verification, rule, "verifica.yml: prove");
|
||||
StringAssert.Contains(release, rule, "rilascio.yml: prove: the release gate exercises what the verification does (the login return among them)");
|
||||
}
|
||||
|
||||
var environment = release.IndexOf("bash .gitea/scripts/ambiente-prove.sh", StringComparison.Ordinal);
|
||||
var tests = release.IndexOf("dotnet test tests/Febe.Tests", StringComparison.Ordinal);
|
||||
var summary = release.IndexOf("riepilogo-prove.sh out/prove 0", StringComparison.Ordinal);
|
||||
Assert.IsTrue(environment < tests && tests < summary, "Chromium before the tests, the summary after them");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheJsonOfTheCiIsReadAndWrittenInHouse()
|
||||
{
|
||||
var bash = RequireBash();
|
||||
CiPath("scripts", "json.sh");
|
||||
using var folder = new TempFolder("febe-json");
|
||||
|
||||
async Task<string> FileAsync(string name, string text)
|
||||
{
|
||||
var path = Path.Combine(folder.Path, name);
|
||||
await File.WriteAllTextAsync(path, text, new UTF8Encoding(false), TestContext.CancellationToken);
|
||||
return path.Replace('\\', '/');
|
||||
}
|
||||
|
||||
// The arguments through the environment: Git Bash started from Windows would expand an unquoted «*» itself.
|
||||
async Task<(int Code, string Output, string Errors)> JsonAsync(params string[] arguments) =>
|
||||
await RunProcessAsync(bash, ["-c", "args=(); for ((i = 0; i < ARGOMENTI; i++)); do v=\"ARGOMENTO_$i\"; args+=(\"${!v}\"); done; exec bash .gitea/scripts/json.sh \"${args[@]}\""], start =>
|
||||
{
|
||||
start.Environment["ARGOMENTI"] = arguments.Length.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
for (var i = 0; i < arguments.Length; i++)
|
||||
{
|
||||
start.Environment[$"ARGOMENTO_{i}"] = arguments[i];
|
||||
}
|
||||
});
|
||||
|
||||
// A release of Gitea: the id at the root, a list inside it that is not read.
|
||||
var release = await FileAsync("release.json", """{"id": 4242, "tag_name": "v0.1.2", "assets": [{"id": 7, "name": "dentro.exe"}], "author": {"id": 3}}""");
|
||||
var read = await JsonAsync("campi", "", "id", release);
|
||||
Assert.AreEqual(0, read.Code, read.Errors);
|
||||
Assert.AreEqual("4242\n", read.Output);
|
||||
|
||||
// The assets of a release: one name per line, in order, with spaces; a tab or a line break in a value stays on
|
||||
// its line. A field missing or holding a container is empty; a scalar of the list is not an object.
|
||||
var assets = await FileAsync("assets.json", """[{"name": "Febe-Setup-0.1.2.exe", "size": 9}, {"name": "febe compose.tar.gz", "x": {"name": "no"}}, {"name": "a\tb\nc"}, {"size": [1]}, 3]""");
|
||||
read = await JsonAsync("campi", "*", "name,size", assets);
|
||||
Assert.AreEqual(0, read.Code, read.Errors);
|
||||
Assert.AreEqual("Febe-Setup-0.1.2.exe\t9\nfebe compose.tar.gz\t\na b c\t\n\t\n", read.Output);
|
||||
|
||||
// Trivy: every vulnerability of every result, with its fix (empty, null or missing when there is none).
|
||||
var trivy = await FileAsync("trivy.json", """
|
||||
{"SchemaVersion": 2, "Results": [
|
||||
{"Target": "debian", "Vulnerabilities": [{"VulnerabilityID": "CVE-1", "Severity": "HIGH", "FixedVersion": ""},
|
||||
{"VulnerabilityID": "CVE-2", "Severity": "CRITICAL", "FixedVersion": "1.2-3"}]},
|
||||
{"Target": "Febe.deps.json"},
|
||||
{"Target": "altro", "Vulnerabilities": [{"Severity": "CRITICAL", "FixedVersion": null}, {"Severity": "CRITICAL"}]}]}
|
||||
""");
|
||||
read = await JsonAsync("campi", "Results/*/Vulnerabilities/*", "Severity,FixedVersion", trivy);
|
||||
Assert.AreEqual(0, read.Code, read.Errors);
|
||||
Assert.AreEqual("HIGH\t\nCRITICAL\t1.2-3\nCRITICAL\tnull\nCRITICAL\t\n", read.Output);
|
||||
|
||||
// gitleaks: an empty report is an empty list, no line.
|
||||
read = await JsonAsync("campi", "*", "RuleID,File", await FileAsync("vuoto.json", "[]"));
|
||||
Assert.AreEqual((0, string.Empty), (read.Code, read.Output), read.Errors);
|
||||
|
||||
// Broken JSON: nothing at all on the output (not even what came before the error), the reason, exit 2. A wrong
|
||||
// command line or a missing file too.
|
||||
read = await JsonAsync("campi", "*", "name", await FileAsync("rotto.json", """[{"name": "primo"}, {"name": """));
|
||||
Assert.AreEqual(2, read.Code);
|
||||
Assert.IsEmpty(read.Output);
|
||||
StringAssert.Contains(read.Errors, "rotto.json");
|
||||
foreach (var arguments in new[] { new[] { "campi", "*", "na me", release }, ["campi", "/x", "id", release], ["campi", "", "id", release + ".manca"], ["altro"] })
|
||||
{
|
||||
read = await JsonAsync(arguments);
|
||||
Assert.AreEqual(2, read.Code, string.Join(' ', arguments));
|
||||
Assert.IsEmpty(read.Output, string.Join(' ', arguments));
|
||||
}
|
||||
|
||||
// Writing: any text, as the notes of a release are, comes back identical from a JSON parser.
|
||||
var notes = "## 0.1.2\n\n- «Novità» con \"virgolette\", \\barre\\ e\ttabulazioni, un ritorno\r da solo\n- controllo \u0001 e \u001f, emoji 🙂, ünïcödé\n- fine";
|
||||
var notesFile = await FileAsync("note.txt", notes);
|
||||
var written = await RunProcessAsync(bash, ["-c", "bash .gitea/scripts/json.sh stringa \"$(cat \"$1\")\"", "bash", notesFile]);
|
||||
Assert.AreEqual(0, written.Code, written.Errors);
|
||||
var literal = written.Output.TrimEnd('\n');
|
||||
Assert.DoesNotContain("\n", literal, "one line");
|
||||
Assert.AreEqual(notes, JsonDocument.Parse(literal).RootElement.GetString());
|
||||
written = await JsonAsync("stringa", "");
|
||||
Assert.AreEqual("\"\"\n", written.Output, written.Errors);
|
||||
|
||||
// The body of a release as the step builds it is valid JSON with those values.
|
||||
var body = await RunProcessAsync(bash, ["-c", """
|
||||
NOTE="$(cat "$1")"
|
||||
printf '{"tag_name":%s,"name":%s,"body":%s,"draft":false,"prerelease":%s}' \
|
||||
"$(bash .gitea/scripts/json.sh stringa "v0.1.2")" "$(bash .gitea/scripts/json.sh stringa "Febe 0.1.2")" \
|
||||
"$(bash .gitea/scripts/json.sh stringa "$NOTE")" true
|
||||
""", "bash", notesFile]);
|
||||
Assert.AreEqual(0, body.Code, body.Errors);
|
||||
using var parsed = JsonDocument.Parse(body.Output);
|
||||
Assert.AreEqual("v0.1.2", parsed.RootElement.GetProperty("tag_name").GetString());
|
||||
Assert.AreEqual(notes, parsed.RootElement.GetProperty("body").GetString());
|
||||
Assert.IsTrue(parsed.RootElement.GetProperty("prerelease").GetBoolean());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(120_000, CooperativeCancellation = true)]
|
||||
public async Task TheCredentialsOfTheRegistryLiveOnlyInAConfigurationOfThePublicationAndGoAway()
|
||||
{
|
||||
var bash = RequireBash();
|
||||
CiPath("scripts", "costruisci-immagine.sh");
|
||||
using var folder = new TempFolder("febe-credenziali");
|
||||
var bin = folder.Combine("bin");
|
||||
var world = folder.Combine("mondo");
|
||||
var temp = folder.Combine("temp");
|
||||
var client = folder.Combine("client");
|
||||
foreach (var made in new[] { bin, world, temp, Path.Combine(client, "cli-plugins"), Path.Combine(client, "buildx") })
|
||||
{
|
||||
Directory.CreateDirectory(made);
|
||||
}
|
||||
|
||||
// The runner's own client configuration: another registry, a context; it must come out byte for byte the same.
|
||||
var original = "{\"currentContext\": \"casa\", \"auths\": {\"altro.invalid\": {\"auth\": \"" + Convert.ToBase64String(Encoding.UTF8.GetBytes("altro:altro")) + "\"}}}\n";
|
||||
await File.WriteAllTextAsync(Path.Combine(client, "config.json"), original, TestContext.CancellationToken);
|
||||
|
||||
// A docker that records the configuration it is given while it runs.
|
||||
var docker = Path.Combine(bin, "docker");
|
||||
await File.WriteAllTextAsync(docker, """
|
||||
#!/usr/bin/env bash
|
||||
world="$FAKE_WORLD"
|
||||
printf 'docker %s\n' "$*" >> "$world/calls"
|
||||
printf '%s\n' "${DOCKER_CONFIG:-}" > "$world/config-dir"
|
||||
printf '%s\n' "${BUILDX_CONFIG:-}" > "$world/buildx-config"
|
||||
if [[ -f "${DOCKER_CONFIG:-/nessuna}/config.json" ]]; then cp "$DOCKER_CONFIG/config.json" "$world/config.json"; fi
|
||||
if [[ -e "${DOCKER_CONFIG:-/nessuna}/cli-plugins" ]]; then echo si > "$world/plugins"; fi
|
||||
exit "${FAKE_EXIT:-0}"
|
||||
""".Replace("\r\n", "\n", StringComparison.Ordinal), TestContext.CancellationToken);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(docker, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
|
||||
async Task<(int Code, string Output, string Errors)> PublishAsync(string? token, string exit = "0")
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(world))
|
||||
{
|
||||
File.Delete(file);
|
||||
}
|
||||
|
||||
string[] script = ["-c", "bin=\"$FAKE_BIN\"; if command -v cygpath > /dev/null; then bin=\"$(cygpath -u \"$bin\")\"; fi; PATH=\"$bin:$PATH\"; exec bash \"$@\"", "bash", ".gitea/scripts/costruisci-immagine.sh", "pubblica", "registro.invalid:3000/alby96/febe:0.1.2"];
|
||||
var run = await RunProcessAsync(bash, script, start =>
|
||||
{
|
||||
start.Environment["FAKE_BIN"] = bin;
|
||||
start.Environment["FAKE_WORLD"] = world.Replace('\\', '/');
|
||||
start.Environment["FAKE_EXIT"] = exit;
|
||||
start.Environment["RUNNER_TEMP"] = temp.Replace('\\', '/');
|
||||
start.Environment["DOCKER_CONFIG"] = client.Replace('\\', '/');
|
||||
start.Environment.Remove("BUILDX_CONFIG");
|
||||
start.Environment["REGISTRY"] = "registro.invalid:3000";
|
||||
start.Environment["REGISTRO_UTENTE"] = "Alby96";
|
||||
start.Environment.Remove("REGISTRO_TOKEN");
|
||||
if (token is not null)
|
||||
{
|
||||
start.Environment["REGISTRO_TOKEN"] = token;
|
||||
}
|
||||
|
||||
foreach (var (key, value) in new[] { ("BUILDER", "febe-ci-7"), ("VERSIONE", "0.1.2"), ("GIT_COMMIT", "abc"), ("FLUSSO", "rilascio"), ("ESECUZIONE", "7") })
|
||||
{
|
||||
start.Environment[key] = value;
|
||||
}
|
||||
});
|
||||
Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log");
|
||||
return run;
|
||||
}
|
||||
|
||||
var published = await PublishAsync(RegistryToken);
|
||||
Assert.AreEqual(0, published.Code, published.Output + published.Errors);
|
||||
var calls = await ReadLinesAsync(Path.Combine(world, "calls"));
|
||||
Assert.HasCount(1, calls);
|
||||
StringAssert.Contains(calls[0], "docker buildx build --builder febe-ci-7 ");
|
||||
StringAssert.Contains(calls[0], "-t registro.invalid:3000/alby96/febe:0.1.2 --push .");
|
||||
|
||||
// While buildx ran: a configuration of its own, with only this registry and the context of the runner kept.
|
||||
var directory = (await File.ReadAllTextAsync(Path.Combine(world, "config-dir"), TestContext.CancellationToken)).Trim();
|
||||
Assert.AreEqual(temp.Replace('\\', '/') + "/febe-docker-7", directory);
|
||||
Assert.AreEqual(client.Replace('\\', '/') + "/buildx", (await File.ReadAllTextAsync(Path.Combine(world, "buildx-config"), TestContext.CancellationToken)).Trim(), "the builders of the run are still found");
|
||||
Assert.IsTrue(File.Exists(Path.Combine(world, "plugins")), "the plugins of the client (buildx) are still there");
|
||||
using (var used = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(world, "config.json"), TestContext.CancellationToken)))
|
||||
{
|
||||
var auths = used.RootElement.GetProperty("auths");
|
||||
Assert.AreEqual(1, auths.EnumerateObject().Count(), "only the registry of Febe");
|
||||
Assert.AreEqual(Convert.ToBase64String(Encoding.UTF8.GetBytes("Alby96:" + RegistryToken)), auths.GetProperty("registro.invalid:3000").GetProperty("auth").GetString());
|
||||
Assert.AreEqual("casa", used.RootElement.GetProperty("currentContext").GetString());
|
||||
}
|
||||
|
||||
// After it: gone, and the runner's configuration untouched.
|
||||
Assert.IsFalse(Directory.Exists(Path.Combine(temp, "febe-docker-7")));
|
||||
Assert.AreEqual(original, await File.ReadAllTextAsync(Path.Combine(client, "config.json"), TestContext.CancellationToken));
|
||||
|
||||
// A failed push leaves nothing behind either; without the token nothing is attempted.
|
||||
var failed = await PublishAsync(RegistryToken, exit: "1");
|
||||
Assert.AreNotEqual(0, failed.Code);
|
||||
Assert.IsFalse(Directory.Exists(Path.Combine(temp, "febe-docker-7")));
|
||||
var refused = await PublishAsync(token: null);
|
||||
Assert.AreEqual(2, refused.Code, refused.Output);
|
||||
Assert.IsFalse(File.Exists(Path.Combine(world, "calls")));
|
||||
Assert.AreEqual(original, await File.ReadAllTextAsync(Path.Combine(client, "config.json"), TestContext.CancellationToken));
|
||||
|
||||
// The steps leave the credentials to the script, and the cleanup that always runs removes its folder.
|
||||
foreach (var (name, job, step) in new[] { ("verifica.yml", "immagine", "Pubblicazione come :main e :sha-<commit>"), ("rilascio.yml", "immagine", "Pubblicazione sul registro di Gitea") })
|
||||
{
|
||||
var text = Job(Workflow(name), job);
|
||||
var publish = Step(text, step);
|
||||
StringAssert.Contains(publish, "REGISTRO_TOKEN: ${{ secrets.REGISTRY_TOKEN }}", name);
|
||||
Assert.DoesNotContain("config.json", Code(publish), $"{name}: the runner's client configuration is never edited");
|
||||
StringAssert.Contains(Step(text, "Pulizia (sempre)"), "rm -rf \"${RUNNER_TEMP:-/tmp}/febe-docker-$ESECUZIONE\"", name);
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"\bjq\b")]
|
||||
private static partial Regex JqWord();
|
||||
}
|
||||
@@ -129,7 +129,7 @@ public sealed partial class PipelineTests
|
||||
var cleanup = Step(image, "Pulizia (sempre)");
|
||||
StringAssert.Contains(cleanup, "if: always()");
|
||||
StringAssert.Contains(cleanup, "bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\"");
|
||||
StringAssert.Contains(cleanup, ".auths |= del(.[$r])", "the credentials leave the client configuration");
|
||||
StringAssert.Contains(cleanup, "rm -rf \"${RUNNER_TEMP:-/tmp}/febe-docker-$ESECUZIONE\"", "the client configuration with the credentials goes, even after an interruption");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -92,34 +92,491 @@ public sealed partial class InHouseAssetsTests
|
||||
Assert.IsFalse(shape.HasElements, $"{path}: forme annidate");
|
||||
foreach (var attribute in shape.Attributes())
|
||||
{
|
||||
Assert.IsTrue(Geometry.Contains(attribute.Name.LocalName), $"{path}: attributo «{attribute.Name.LocalName}» (spessore, colore e riempimento vengono dal foglio di stile)");
|
||||
if (attribute.Name.LocalName is not ("d" or "points" or "stroke-dasharray" or "stroke-dashoffset"))
|
||||
var name = attribute.Name.LocalName;
|
||||
Assert.IsTrue(Geometry.Contains(name), $"{path}: attributo «{name}» (spessore, colore e riempimento vengono dal foglio di stile)");
|
||||
var where = $"{path}: <{shape.Name.LocalName} {name}=\"{attribute.Value}\">";
|
||||
switch (name)
|
||||
{
|
||||
var value = double.Parse(attribute.Value, System.Globalization.CultureInfo.InvariantCulture);
|
||||
Assert.IsTrue(value is >= 0 and <= 24, $"{path}: {attribute.Name.LocalName}={attribute.Value} fuori dalla griglia");
|
||||
case "d":
|
||||
foreach (var (x, y) in PathPoints(attribute.Value, where)!)
|
||||
{
|
||||
AssertOnGrid(x, where);
|
||||
AssertOnGrid(y, where);
|
||||
}
|
||||
|
||||
break;
|
||||
case "points":
|
||||
var numbers = Numbers(attribute.Value, where);
|
||||
Assert.IsTrue(numbers.Count >= 4 && numbers.Count % 2 == 0, $"{where}: coppie di coordinate, almeno due punti");
|
||||
numbers.ForEach(value => AssertOnGrid(value, where));
|
||||
break;
|
||||
case "stroke-dasharray" or "stroke-dashoffset":
|
||||
Numbers(attribute.Value, where).ForEach(value => Assert.IsTrue(value is >= 0 and <= 100, where));
|
||||
break;
|
||||
default:
|
||||
AssertOnGrid(Number(attribute.Value, where), where);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheGridCheckReadsPathsAndPointsAndFindsWhatIsOffTheGrid()
|
||||
{
|
||||
// Absolute and relative commands, repeated arguments, arcs with packed flags, curves, closing.
|
||||
var points = PathPoints("M4.5 12a7.5 7.5 0 0 1 13-5.1l2 2.1M3 3h18v18H3zM6 9c0-2 1-3 3-3s3 1 3 3q2 2 4 0t4 0", "prova");
|
||||
Assert.IsNotNull(points);
|
||||
Assert.IsTrue(points.Any(p => Math.Abs(p.X - 19.5) < 1e-9 && Math.Abs(p.Y - 9) < 1e-9), "a relative line after a relative arc");
|
||||
Assert.IsTrue(points.Any(p => p == (21.0, 21.0)), "h and v, then H");
|
||||
Assert.IsTrue(points.Any(p => p == (20.0, 9.0)), "c, s, q and t");
|
||||
Assert.IsTrue(points.All(p => p.X is >= 0 and <= 24 && p.Y is >= 0 and <= 24));
|
||||
Assert.IsTrue(PathPoints("M2 12a10 10 0 1012 0", "prova")!.Any(p => p.Y > 12 + 5), "the arc is followed, not only its ends");
|
||||
|
||||
// What the test must refuse: off the grid by an end, by a curve or by an arc that bulges, broken numbers.
|
||||
foreach (var bad in new[] { "M30 30L-5 40", "M2 2l30 0", "M2 12C2 -10 22 -10 22 12", "M2 2a20 20 0 0 1 20 0", "M2 2L3", "M2,x 3", "L2 2", "M2 2a1 1 0 2 1 3 3" })
|
||||
{
|
||||
var off = PathPoints(bad, bad, failQuietly: true);
|
||||
Assert.IsTrue(off is null || off.Any(p => p.X is < 0 or > 24 || p.Y is < 0 or > 24), $"«{bad}» passerebbe");
|
||||
}
|
||||
|
||||
Assert.ThrowsExactly<FormatException>(() => Numbers("0,0 99,x", "prova", failQuietly: true));
|
||||
CollectionAssert.AreEqual(new[] { 0.5, 0.5, -3.0, 1e-1 }, Numbers("0.5.5-3,1e-1", "prova"));
|
||||
}
|
||||
|
||||
private static void AssertOnGrid(double value, string where) =>
|
||||
Assert.IsTrue(value is >= -1e-6 and <= 24 + 1e-6, $"{where}: {value.ToString(System.Globalization.CultureInfo.InvariantCulture)} fuori dalla griglia 0–24");
|
||||
|
||||
private static double Number(string text, string where)
|
||||
{
|
||||
Assert.IsTrue(double.TryParse(text, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var value), $"{where}: «{text}» non è un numero");
|
||||
return value;
|
||||
}
|
||||
|
||||
private static List<double> Numbers(string text, string where, bool failQuietly = false)
|
||||
{
|
||||
var numbers = new List<double>();
|
||||
var at = 0;
|
||||
while (SkipSeparators(text, ref at) < text.Length)
|
||||
{
|
||||
if (ReadNumber(text, ref at) is not { } value)
|
||||
{
|
||||
if (failQuietly)
|
||||
{
|
||||
throw new FormatException(where);
|
||||
}
|
||||
|
||||
Assert.Fail($"{where}: «{text[at..]}» non è un numero");
|
||||
}
|
||||
else
|
||||
{
|
||||
numbers.Add(value);
|
||||
}
|
||||
}
|
||||
|
||||
return numbers;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every point the outline of an SVG path goes through (SVG 1.1 §8.3): the ends of each segment, the control points
|
||||
/// of the curves and points along each curve and arc, all made absolute. A path that does not start with a move,
|
||||
/// a command with too few numbers or a number that does not parse fails the test (or gives null with
|
||||
/// <paramref name="failQuietly"/>).
|
||||
/// </summary>
|
||||
private static List<(double X, double Y)>? PathPoints(string d, string where, bool failQuietly = false)
|
||||
{
|
||||
var points = new List<(double X, double Y)>();
|
||||
double x = 0, y = 0, startX = 0, startY = 0;
|
||||
var at = 0;
|
||||
var command = '\0';
|
||||
void Refuse(string why)
|
||||
{
|
||||
if (!failQuietly)
|
||||
{
|
||||
Assert.Fail($"{where}: {why}");
|
||||
}
|
||||
}
|
||||
|
||||
while (SkipSeparators(d, ref at) < d.Length)
|
||||
{
|
||||
if (char.IsAsciiLetter(d[at]))
|
||||
{
|
||||
command = d[at++];
|
||||
if (points.Count == 0 && command is not ('M' or 'm'))
|
||||
{
|
||||
Refuse("il percorso deve cominciare con M");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (command is 'Z' or 'z')
|
||||
{
|
||||
(x, y) = (startX, startY);
|
||||
points.Add((x, y));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (command is '\0' or 'Z' or 'z')
|
||||
{
|
||||
Refuse($"numero senza comando: «{d[at..]}»");
|
||||
return null;
|
||||
}
|
||||
|
||||
var relative = char.IsAsciiLetterLower(command);
|
||||
var arguments = char.ToUpperInvariant(command) switch
|
||||
{
|
||||
'M' or 'L' or 'T' => 2,
|
||||
'H' or 'V' => 1,
|
||||
'C' => 6,
|
||||
'S' or 'Q' => 4,
|
||||
'A' => 7,
|
||||
_ => -1,
|
||||
};
|
||||
if (arguments < 0)
|
||||
{
|
||||
Refuse($"comando «{command}» sconosciuto");
|
||||
return null;
|
||||
}
|
||||
|
||||
var values = new double[arguments];
|
||||
for (var i = 0; i < arguments; i++)
|
||||
{
|
||||
SkipSeparators(d, ref at);
|
||||
double? value = char.ToUpperInvariant(command) == 'A' && i is 3 or 4 ? ReadFlag(d, ref at) : ReadNumber(d, ref at);
|
||||
if (value is null)
|
||||
{
|
||||
Refuse($"comando «{command}» con argomenti mancanti o non validi: «{d[at..]}»");
|
||||
return null;
|
||||
}
|
||||
|
||||
values[i] = value.Value;
|
||||
}
|
||||
|
||||
(double X, double Y) Absolute(int index) => relative ? (x + values[index], y + values[index + 1]) : (values[index], values[index + 1]);
|
||||
var from = (X: x, Y: y);
|
||||
switch (char.ToUpperInvariant(command))
|
||||
{
|
||||
case 'M':
|
||||
(x, y) = Absolute(0);
|
||||
(startX, startY) = (x, y);
|
||||
points.Add((x, y));
|
||||
command = relative ? 'l' : 'L';
|
||||
break;
|
||||
case 'L' or 'T':
|
||||
(x, y) = Absolute(0);
|
||||
points.Add((x, y));
|
||||
break;
|
||||
case 'H':
|
||||
x = relative ? x + values[0] : values[0];
|
||||
points.Add((x, y));
|
||||
break;
|
||||
case 'V':
|
||||
y = relative ? y + values[0] : values[0];
|
||||
points.Add((x, y));
|
||||
break;
|
||||
case 'C':
|
||||
{
|
||||
var (c1, c2, end) = (Absolute(0), Absolute(2), Absolute(4));
|
||||
points.AddRange([c1, c2, end]);
|
||||
for (var t = 0.0625; t < 1; t += 0.0625)
|
||||
{
|
||||
var u = 1 - t;
|
||||
points.Add(((u * u * u * from.X) + (3 * u * u * t * c1.X) + (3 * u * t * t * c2.X) + (t * t * t * end.X),
|
||||
(u * u * u * from.Y) + (3 * u * u * t * c1.Y) + (3 * u * t * t * c2.Y) + (t * t * t * end.Y)));
|
||||
}
|
||||
|
||||
(x, y) = end;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'S' or 'Q':
|
||||
{
|
||||
var (control, end) = (Absolute(0), Absolute(2));
|
||||
points.AddRange([control, end]);
|
||||
(x, y) = end;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'A':
|
||||
{
|
||||
var end = Absolute(5);
|
||||
points.Add(end);
|
||||
points.AddRange(ArcPoints(from, values[0], values[1], values[2], values[3] != 0, values[4] != 0, end));
|
||||
(x, y) = end;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (points.Count == 0)
|
||||
{
|
||||
Refuse("percorso vuoto");
|
||||
return null;
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
/// <summary>Points along an elliptical arc, from its end points to its centre as in SVG 1.1 appendix F.6.5.</summary>
|
||||
private static IEnumerable<(double X, double Y)> ArcPoints((double X, double Y) from, double rx, double ry, double rotation, bool large, bool sweep, (double X, double Y) to)
|
||||
{
|
||||
rx = Math.Abs(rx);
|
||||
ry = Math.Abs(ry);
|
||||
if (rx == 0 || ry == 0 || from == to)
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
var phi = rotation * Math.PI / 180;
|
||||
var (cos, sin) = (Math.Cos(phi), Math.Sin(phi));
|
||||
var dx = (from.X - to.X) / 2;
|
||||
var dy = (from.Y - to.Y) / 2;
|
||||
var x1 = (cos * dx) + (sin * dy);
|
||||
var y1 = (-sin * dx) + (cos * dy);
|
||||
var lambda = (x1 * x1 / (rx * rx)) + (y1 * y1 / (ry * ry));
|
||||
if (lambda > 1)
|
||||
{
|
||||
rx *= Math.Sqrt(lambda);
|
||||
ry *= Math.Sqrt(lambda);
|
||||
}
|
||||
|
||||
var numerator = (rx * rx * ry * ry) - (rx * rx * y1 * y1) - (ry * ry * x1 * x1);
|
||||
var factor = Math.Sqrt(Math.Max(0, numerator / ((rx * rx * y1 * y1) + (ry * ry * x1 * x1)))) * (large == sweep ? -1 : 1);
|
||||
var cx1 = factor * rx * y1 / ry;
|
||||
var cy1 = -factor * ry * x1 / rx;
|
||||
var cx = (cos * cx1) - (sin * cy1) + ((from.X + to.X) / 2);
|
||||
var cy = (sin * cx1) + (cos * cy1) + ((from.Y + to.Y) / 2);
|
||||
static double Angle(double ux, double uy, double vx, double vy) => Math.Atan2((ux * vy) - (uy * vx), (ux * vx) + (uy * vy));
|
||||
var start = Angle(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry);
|
||||
var delta = Angle((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry);
|
||||
if (!sweep && delta > 0)
|
||||
{
|
||||
delta -= 2 * Math.PI;
|
||||
}
|
||||
else if (sweep && delta < 0)
|
||||
{
|
||||
delta += 2 * Math.PI;
|
||||
}
|
||||
|
||||
for (var step = 1; step < 32; step++)
|
||||
{
|
||||
var angle = start + (delta * step / 32);
|
||||
var (ex, ey) = (rx * Math.Cos(angle), ry * Math.Sin(angle));
|
||||
yield return ((cos * ex) - (sin * ey) + cx, (sin * ex) + (cos * ey) + cy);
|
||||
}
|
||||
}
|
||||
|
||||
private static int SkipSeparators(string text, ref int at)
|
||||
{
|
||||
while (at < text.Length && (char.IsWhiteSpace(text[at]) || text[at] == ','))
|
||||
{
|
||||
at++;
|
||||
}
|
||||
|
||||
return at;
|
||||
}
|
||||
|
||||
private static double? ReadNumber(string text, ref int at)
|
||||
{
|
||||
var match = SvgNumber().Match(text, at);
|
||||
if (!match.Success || match.Index != at)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
at += match.Length;
|
||||
return double.Parse(match.Value, System.Globalization.CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <summary>An arc flag: one digit, 0 or 1, which may touch the next number («0 01 3 3»).</summary>
|
||||
private static double? ReadFlag(string text, ref int at)
|
||||
{
|
||||
if (at < text.Length && text[at] is '0' or '1')
|
||||
{
|
||||
return text[at++] - '0';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryIconThePagesAskForIsDrawn()
|
||||
{
|
||||
var files = new EmbeddedWwwroot();
|
||||
var drawn = files.Files.Where(f => f.StartsWith("icone/", StringComparison.Ordinal))
|
||||
.Select(f => f["icone/".Length..^".svg".Length]).ToHashSet(StringComparer.Ordinal);
|
||||
var asked = 0;
|
||||
var asked = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var path in files.Files.Where(f => f.EndsWith(".js", StringComparison.Ordinal)))
|
||||
{
|
||||
foreach (Match match in IconCall().Matches(files.ReadText(path)!))
|
||||
foreach (var name in IconNamesAskedIn(files.ReadText(path)!))
|
||||
{
|
||||
asked++;
|
||||
Assert.Contains(match.Groups[1].Value, drawn, $"{path} chiede l'icona «{match.Groups[1].Value}»");
|
||||
asked.TryAdd(name, path);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsGreaterThan(20, asked, "le pagine usano le icone");
|
||||
foreach (var (name, path) in asked)
|
||||
{
|
||||
Assert.Contains(name, drawn, $"{path} chiede l'icona «{name}»");
|
||||
}
|
||||
|
||||
// Every form the pages use is read, not only icon('…'): names held in data (icon: '…', a map of icons, the
|
||||
// third argument of label), chosen with a condition, or taken from a list a function returns. One name for each
|
||||
// form, as the pages have them today.
|
||||
foreach (var (name, form) in new[]
|
||||
{
|
||||
("layout-grid", "icon: '…' (shell.js)"), ("sun", "icon: '…' (settings-general.js)"), ("gauge", "PLAN_ICONS e icon: '…'"),
|
||||
("trash-2", "icon: '…' (accounts.js)"), ("circle-check", "icon(on ? '…' : '…')"), ("at-sign", "icon(cond ? '…' : '…')"),
|
||||
("octagon-alert", "[colore, '…'] in outcome"), ("shield-alert", "return ['…', …] di placeholderFor"),
|
||||
("user-check", "label(testo, '', '…')"), ("hourglass", "icon(a ? '…' : b ? '…' : '…')"),
|
||||
})
|
||||
{
|
||||
Assert.IsTrue(asked.ContainsKey(name), $"la prova non legge più la forma {form}: manca «{name}»");
|
||||
}
|
||||
|
||||
Assert.IsGreaterThan(50, asked.Count, "le pagine usano le icone");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheReadingOfTheIconNamesSeesEveryFormAndNotTheConditions()
|
||||
{
|
||||
const string script = """
|
||||
const MENU = [{ path: '/', icon: 'uno' }, { icon: x ? 'due' : 'tre', label: 'non-icona' }];
|
||||
const STATE_ICONS = { a: 'quattro', b: 'cinque' };
|
||||
h('b', icon(s.kind === 'video' ? 'sei' : 'sette', 's'), icon('otto'), label(t('x'), 'ambra', 'nove'));
|
||||
const outcome = { ok: ['verde', 'dieci'], ko: ['rosso', 'undici'] }[k] || ['', 'dodici'];
|
||||
h('td', icon(outcome[1]));
|
||||
function placeholderFor(m) {
|
||||
if (m === 'Off') return ['tredici', t('a'), null];
|
||||
return ['quattordici', t('b'), 'about:blank'];
|
||||
}
|
||||
const [name, text] = placeholderFor(mode);
|
||||
fill(icon(name, 'l'));
|
||||
""";
|
||||
CollectionAssert.AreEquivalent(
|
||||
new[] { "uno", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove", "dieci", "undici", "dodici", "tredici", "quattordici" },
|
||||
IconNamesAskedIn(script).Distinct().ToArray(),
|
||||
"not «video» (a condition), not «non-icona», «verde» or «about:blank»");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The icon names a script asks for: the literals that reach <c>icon(…)</c> directly or through data.
|
||||
/// <list type="bullet">
|
||||
/// <item>the first argument of <c>icon(…)</c>, the value of <c>icon: …</c> and the third argument of <c>label(…)</c>,
|
||||
/// with the literals of a condition left out (those before a <c>?</c> or after <c>===</c>);</item>
|
||||
/// <item>the values of an object assigned to a name with ICON in it (<c>PLAN_ICONS</c>);</item>
|
||||
/// <item><c>icon(v[n])</c>: element n of the lists in <c>const v = …</c>;</item>
|
||||
/// <item><c>icon(v)</c> with <c>const [.., v, ..] = f(…)</c>: that element of the lists <c>f</c> returns.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
private static IEnumerable<string> IconNamesAskedIn(string script)
|
||||
{
|
||||
foreach (Match call in IconArgument().Matches(script))
|
||||
{
|
||||
foreach (var name in NamesIn(FirstArgument(script, call.Index + call.Length)))
|
||||
{
|
||||
yield return name;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (Match property in IconProperty().Matches(script))
|
||||
{
|
||||
foreach (var name in NamesIn(FirstArgument(script, property.Index + property.Length)))
|
||||
{
|
||||
yield return name;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (Match label in LabelIcon().Matches(script))
|
||||
{
|
||||
yield return label.Groups[1].Value;
|
||||
}
|
||||
|
||||
foreach (Match map in IconMap().Matches(script))
|
||||
{
|
||||
foreach (Match value in QuotedValue().Matches(map.Groups["body"].Value))
|
||||
{
|
||||
yield return value.Groups[1].Value;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (Match indexed in IndexedIcon().Matches(script))
|
||||
{
|
||||
var definition = Regex.Match(script, $@"const {Regex.Escape(indexed.Groups["list"].Value)} = (?<value>[^;\n]+)");
|
||||
var index = int.Parse(indexed.Groups["index"].Value, System.Globalization.CultureInfo.InvariantCulture);
|
||||
foreach (Match list in ListLiteral().Matches(definition.Groups["value"].Value))
|
||||
{
|
||||
var items = list.Groups["items"].Value.Split(',', StringSplitOptions.TrimEntries);
|
||||
if (index < items.Length && Quoted().Match(items[index]) is { Success: true } item)
|
||||
{
|
||||
yield return item.Groups[1].Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (Match variable in VariableIcon().Matches(script))
|
||||
{
|
||||
var name = variable.Groups["name"].Value;
|
||||
foreach (Match destructured in Regex.Matches(script, @"const \[(?<names>[^\]]+)\] = (?<function>\w+)\("))
|
||||
{
|
||||
var names = destructured.Groups["names"].Value.Split(',', StringSplitOptions.TrimEntries);
|
||||
var position = Array.IndexOf(names, name);
|
||||
if (position < 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var body = Regex.Match(script, $@"function {Regex.Escape(destructured.Groups["function"].Value)}\([^)]*\) \{{(?<body>.*?)\n\s*\}}", RegexOptions.Singleline);
|
||||
foreach (Match returned in Regex.Matches(body.Groups["body"].Value, @"return \[(?<items>[^\]]*)\]"))
|
||||
{
|
||||
var items = returned.Groups["items"].Value.Split(',', StringSplitOptions.TrimEntries);
|
||||
if (position < items.Length && Quoted().Match(items[position]) is { Success: true } item)
|
||||
{
|
||||
yield return item.Groups[1].Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The text of an argument or a value from <paramref name="start"/> to the comma, parenthesis or brace that ends it.</summary>
|
||||
private static string FirstArgument(string script, int start)
|
||||
{
|
||||
var depth = 0;
|
||||
for (var i = start; i < script.Length; i++)
|
||||
{
|
||||
var c = script[i];
|
||||
if (c is '(' or '[' or '{')
|
||||
{
|
||||
depth++;
|
||||
}
|
||||
else if (c is ')' or ']' or '}' || (c is ',' or ';' or '\n' && depth == 0))
|
||||
{
|
||||
if (depth == 0)
|
||||
{
|
||||
return script[start..i];
|
||||
}
|
||||
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
|
||||
return script[start..];
|
||||
}
|
||||
|
||||
/// <summary>The quoted names of an expression, without the operands of a condition.</summary>
|
||||
private static IEnumerable<string> NamesIn(string expression)
|
||||
{
|
||||
foreach (Match literal in Quoted().Matches(expression))
|
||||
{
|
||||
var after = expression[(literal.Index + literal.Length)..].TrimStart();
|
||||
var before = expression[..literal.Index].TrimEnd();
|
||||
if (after.StartsWith('?') || before.EndsWith("===", StringComparison.Ordinal) || before.EndsWith("!==", StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
yield return literal.Groups[1].Value;
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -167,8 +624,35 @@ public sealed partial class InHouseAssetsTests
|
||||
[GeneratedRegex(@"--carattere:([^;]+);")]
|
||||
private static partial Regex CharacterToken();
|
||||
|
||||
[GeneratedRegex(@"\bicon\('([a-z0-9-]+)'")]
|
||||
private static partial Regex IconCall();
|
||||
[GeneratedRegex(@"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?")]
|
||||
private static partial Regex SvgNumber();
|
||||
|
||||
[GeneratedRegex(@"(?<![\w.])icon\((?!name, size)")]
|
||||
private static partial Regex IconArgument();
|
||||
|
||||
[GeneratedRegex(@"\bicon:\s*")]
|
||||
private static partial Regex IconProperty();
|
||||
|
||||
[GeneratedRegex(@"\blabel\([^;\n]*?,\s*'[^']*',\s*'([a-z0-9-]+)'\)")]
|
||||
private static partial Regex LabelIcon();
|
||||
|
||||
[GeneratedRegex(@"const \w*ICON\w* = \{(?<body>[^}]*)\}", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex IconMap();
|
||||
|
||||
[GeneratedRegex(@":\s*'([a-z0-9-]+)'")]
|
||||
private static partial Regex QuotedValue();
|
||||
|
||||
[GeneratedRegex(@"\bicon\((?<list>\w+)\[(?<index>\d)\]\)")]
|
||||
private static partial Regex IndexedIcon();
|
||||
|
||||
[GeneratedRegex(@"\bicon\((?<name>[A-Za-z_]\w*)[,)]")]
|
||||
private static partial Regex VariableIcon();
|
||||
|
||||
[GeneratedRegex(@"\[(?<items>[^\[\]]*)\]")]
|
||||
private static partial Regex ListLiteral();
|
||||
|
||||
[GeneratedRegex(@"'([a-z0-9]+(?:-[a-z0-9]+)*)'")]
|
||||
private static partial Regex Quoted();
|
||||
|
||||
// The font and the icon set Febe carried until 18 November 2026.
|
||||
[GeneratedRegex(@"\b(archivo|lucide)\b", RegexOptions.IgnoreCase)]
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Schermate;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The screenshot tool of spec §10.7 (tools/Febe.Schermate), written in C# like the rest (Alberto's decision of
|
||||
/// 18 November 2026: no Node, no third-party programs): only Febe's own interface on this computer, every screenshot of
|
||||
/// docs/schermate and nothing else.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed partial class ScreenshotToolTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void OnlyFebeOnThisComputerIsPhotographed()
|
||||
{
|
||||
foreach (var address in new[] { "http://127.0.0.1:8490/libreria", "http://localhost:8480/", "http://[::1]:8480/account", "https://127.0.0.1:8443/" })
|
||||
{
|
||||
Assert.IsTrue(Shots.IsOnThisComputer(new Uri(address)), address);
|
||||
}
|
||||
|
||||
foreach (var address in new[]
|
||||
{
|
||||
"https://www.instagram.com/", "http://127.0.0.2:8480/", "http://localhost.example.com/", "file:///etc/passwd",
|
||||
"http://user:pw@127.0.0.1:8480/", "http://192.168.1.10:8480/", "ws://127.0.0.1:8480/",
|
||||
})
|
||||
{
|
||||
Assert.IsFalse(Shots.IsOnThisComputer(new Uri(address)), address);
|
||||
}
|
||||
|
||||
var ex = Assert.ThrowsExactly<ArgumentException>(() => Request.Parse(["una", "https://www.instagram.com/", "x.png"], Path.GetTempPath()));
|
||||
StringAssert.Contains(ex.Message, "questo computer");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheListTakesEveryScreenshotOfTheFolderOnceWithItsStep()
|
||||
{
|
||||
var folder = Repository.PathOf("docs", "schermate");
|
||||
var steps = Repository.PathOf("tools", "Febe.Schermate", "passi");
|
||||
var files = Shots.All.Select(s => s.File).ToList();
|
||||
CollectionAssert.AllItemsAreUnique(files);
|
||||
CollectionAssert.AreEquivalent(Directory.GetFiles(folder, "*.png").Select(Path.GetFileName).ToList(), files, "every screenshot of docs/schermate, no other");
|
||||
foreach (var shot in Shots.All)
|
||||
{
|
||||
Assert.IsTrue(shot.Page.StartsWith('/'), shot.File);
|
||||
Assert.IsTrue(shot.Width is >= 390 and <= 1440 && shot.Height is >= 844 and <= 1470, shot.File);
|
||||
if (shot.Step is not null)
|
||||
{
|
||||
Assert.IsTrue(File.Exists(Path.Combine(steps, shot.Step)), $"manca il passo {shot.Step}");
|
||||
}
|
||||
}
|
||||
|
||||
// The steps go next to the program, where it looks for them.
|
||||
var project = File.ReadAllText(Repository.PathOf("tools", "Febe.Schermate", "Febe.Schermate.csproj"));
|
||||
StringAssert.Contains(project, "<None Include=\"passi\\*.js\" CopyToOutputDirectory=\"PreserveNewest\" />");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCommandLineGivesTheDemoTheFolderAndASingleShot()
|
||||
{
|
||||
var root = Repository.PathOf();
|
||||
var all = Request.Parse([], Path.Combine(root, "src"));
|
||||
Assert.AreEqual(new Uri("http://127.0.0.1:8480/"), all.Base);
|
||||
Assert.AreEqual(Path.Combine(root, "docs", "schermate"), all.Folder);
|
||||
Assert.HasCount(Shots.All.Count, all.Shots);
|
||||
Assert.AreEqual(new Uri("http://127.0.0.1:8480/libreria?tema=chiaro"), all.AddressOf(all.Shots[0]));
|
||||
|
||||
var other = Request.Parse(["8490", "uscita"], root);
|
||||
Assert.AreEqual(8490, other.Base.Port);
|
||||
Assert.AreEqual(Path.Combine(root, "uscita"), other.Folder);
|
||||
|
||||
var one = Request.Parse(["una", "http://localhost:8490/attivita?scena=fermo", "prova.png", "390", "844", "500", "passo.js"], root);
|
||||
var shot = one.Shots.Single();
|
||||
Assert.AreEqual(new Uri("http://localhost:8490/attivita?scena=fermo"), one.AddressOf(shot));
|
||||
Assert.AreEqual(root, one.Folder);
|
||||
Assert.AreEqual(new Shot(string.Empty, "prova.png", 390, 844, 500, Path.Combine(root, "passo.js")), shot);
|
||||
Assert.AreEqual(Path.Combine(root, "passo.js"), one.StepPath(shot.Step!));
|
||||
|
||||
foreach (var wrong in new[] { new[] { "porta" }, ["0"], ["70000"], ["8480", "a", "b"], ["una", "http://127.0.0.1/"], ["una", "http://127.0.0.1/", "x.jpg"],
|
||||
["una", "http://127.0.0.1/", "x.png", "10"], ["una", "http://127.0.0.1/", "x.png", "800", "600", "-1"] })
|
||||
{
|
||||
Assert.ThrowsExactly<ArgumentException>(() => Request.Parse(wrong, root), string.Join(' ', wrong));
|
||||
}
|
||||
|
||||
Assert.IsNull(Request.RepositoryRoot(Path.GetPathRoot(Path.GetTempPath())!));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheBrowserHasNoWindowAPrivateProfileAndTheDebugPortOnlyHere()
|
||||
{
|
||||
var arguments = Screenshotter.Arguments("profilo", 390, 844, noSandbox: false);
|
||||
CollectionAssert.Contains(arguments, "--headless");
|
||||
CollectionAssert.Contains(arguments, "--user-data-dir=profilo");
|
||||
CollectionAssert.Contains(arguments, "--remote-debugging-port=0");
|
||||
CollectionAssert.Contains(arguments, "--remote-debugging-address=127.0.0.1");
|
||||
CollectionAssert.Contains(arguments, "--no-proxy-server");
|
||||
CollectionAssert.Contains(arguments, "--window-size=390,844");
|
||||
CollectionAssert.DoesNotContain(arguments, "--no-sandbox");
|
||||
Assert.AreEqual("about:blank", arguments[^1]);
|
||||
CollectionAssert.Contains(Screenshotter.Arguments("profilo", 1440, 900, noSandbox: true), "--no-sandbox");
|
||||
|
||||
// Only a page target on 127.0.0.1 is driven.
|
||||
Assert.AreEqual(
|
||||
"ws://127.0.0.1:9333/devtools/page/A",
|
||||
Screenshotter.PageDebugger("""[{"type":"service_worker","webSocketDebuggerUrl":"ws://127.0.0.1:9333/devtools/page/W"},{"type":"page","webSocketDebuggerUrl":"ws://127.0.0.1:9333/devtools/page/A"}]"""));
|
||||
Assert.IsNull(Screenshotter.PageDebugger("""[{"type":"page","webSocketDebuggerUrl":"ws://10.0.0.5:9333/devtools/page/A"}]"""));
|
||||
Assert.IsNull(Screenshotter.PageDebugger("[]"));
|
||||
|
||||
using var hover = JsonDocument.Parse("""{"hover":[640,212.5],"label":"x"}""");
|
||||
Assert.AreEqual((640d, 212.5d), Screenshotter.HoverPoint(hover.RootElement));
|
||||
using var none = JsonDocument.Parse("""{"hover":[1]}""");
|
||||
Assert.IsNull(Screenshotter.HoverPoint(none.RootElement));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void NoToolNeedsNode()
|
||||
{
|
||||
var tools = Repository.PathOf("tools");
|
||||
foreach (var file in Directory.EnumerateFiles(tools, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var relative = Path.GetRelativePath(tools, file);
|
||||
if (relative.Split(Path.DirectorySeparatorChar).Any(part => part is "bin" or "obj"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
Assert.IsFalse(Path.GetExtension(file) is ".mjs" or ".cjs" or ".ts", $"script Node: {relative}");
|
||||
Assert.AreNotEqual("package.json", Path.GetFileName(file), relative);
|
||||
if (Path.GetExtension(file) is ".sh" or ".ps1" or ".cmd" or ".bat" or ".cs" or ".csproj")
|
||||
{
|
||||
Assert.IsFalse(NodeCommand().IsMatch(File.ReadAllText(file)), $"comando node in {relative}");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsFalse(Directory.Exists(Path.Combine(tools, "schermate")), "tools/schermate became tools/Febe.Schermate");
|
||||
StringAssert.Contains(File.ReadAllText(Repository.PathOf("Febe.slnx")), "<Project Path=\"tools/Febe.Schermate/Febe.Schermate.csproj\" />");
|
||||
}
|
||||
|
||||
/// <summary>«node» or «npx» run as a command (at the start of a line or after a separator), not inside a word.</summary>
|
||||
[GeneratedRegex(@"(?m)(?:^|[;&|(`]\s*|\bexec\s+|\btimeout\s+\d+\s+)(?:node|npx|npm)\s")]
|
||||
private static partial Regex NodeCommand();
|
||||
}
|
||||
@@ -9,7 +9,7 @@ using Febe.Tests.Browser.TestSupport;
|
||||
namespace Febe.Tests.Web.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A headless Chromium that drives Febe's own interface, like <c>tools/schermate</c>: only addresses on 127.0.0.1, never
|
||||
/// A headless Chromium that drives Febe's own interface, like <c>tools/Febe.Schermate</c>: only addresses on 127.0.0.1, never
|
||||
/// Instagram (spec §2). It speaks the DevTools protocol directly, without the command policy of Febe's own client,
|
||||
/// because here the tests click, type and run scripts in Febe's pages. Inconclusive when Chromium is missing.
|
||||
/// </summary>
|
||||
|
||||
Reference in new issue
Block a user