F0: fondamenta della soluzione, script, documenti e harness di test

- ViaFerrea.sln con Core e Protocol (net10.0 + net8.0), Server, Tools, Tests
- Directory.Build.props con versione unica e warning come errori
- Script build/test/check-nuget/publish-image (+ build.ps1)
- Documenti: GUIDA, GDD, ARCHITECTURE, PROTOCOL (bozza), STATE, ADR 0001
- Harness di test interno con i primi test su Rng (xoshiro256**)
- Immagini di riferimento 01-05

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-01 21:50:41 +00:00
1 parent 63a7a460d3
commit 290a1d886c
36 files changed
+1647 -2

No files matched your search

+66
View File
@@ -0,0 +1,66 @@
using ViaFerrea.Core.Common;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Core;
public static class RngTests
{
[Test(Description = "Vettore di riferimento di xoshiro256** con stato {1,2,3,4}")]
public static void Xoshiro256StarStarMatchesReferenceVector()
{
var rng = Rng.FromState(1, 2, 3, 4);
Assert.Equal(11520UL, rng.NextU64());
Assert.Equal(0UL, rng.NextU64());
Assert.Equal(1509978240UL, rng.NextU64());
Assert.Equal(1215971899390074240UL, rng.NextU64());
}
[Test]
public static void SameSeedGivesSameSequence()
{
var a = new Rng(42);
var b = new Rng(42);
for (int i = 0; i < 1000; i++) Assert.Equal(a.NextU64(), b.NextU64());
}
[Test]
public static void ForkIsStableAndDoesNotConsumeParent()
{
var root = new Rng(7);
var before = root.State;
var f1 = root.Fork("industries");
var f2 = root.Fork("industries");
var f3 = root.Fork("towns");
Assert.Equal(before, root.State);
Assert.Equal(f1.NextU64(), f2.NextU64());
Assert.NotEqual(new Rng(7).Fork("industries").NextU64(), f3.NextU64());
}
[Test]
public static void NextIntIsInRangeAndRoughlyUniform()
{
var rng = new Rng(123);
var counts = new int[10];
for (int i = 0; i < 100_000; i++)
{
int v = rng.NextInt(10);
Assert.True(v is >= 0 and < 10);
counts[v]++;
}
foreach (int c in counts) Assert.InRange(c, 9_500, 10_500);
}
[Test]
public static void NextDoubleIsInUnitInterval()
{
var rng = new Rng(99);
double sum = 0;
for (int i = 0; i < 100_000; i++)
{
double d = rng.NextDouble();
Assert.True(d >= 0 && d < 1);
sum += d;
}
Assert.Approx(0.5, sum / 100_000, 0.01);
}
}
+99
View File
@@ -0,0 +1,99 @@
using System.Runtime.CompilerServices;
namespace ViaFerrea.Tests.Harness;
/// <summary>Fallimento di un'asserzione, con posizione nel sorgente.</summary>
public sealed class AssertionException(string message) : Exception(message);
/// <summary>Asserzioni minime del harness interno.</summary>
public static class Assert
{
public static void Equal<T>(T expected, T actual, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (!EqualityComparer<T>.Default.Equals(expected, actual))
Fail($"atteso <{expected}> ma ottenuto <{actual}>", message, file, line);
}
public static void NotEqual<T>(T notExpected, T actual, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (EqualityComparer<T>.Default.Equals(notExpected, actual))
Fail($"valore diverso da <{notExpected}> atteso", message, file, line);
}
public static void SequenceEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
var e = expected.ToList();
var a = actual.ToList();
if (e.Count != a.Count)
Fail($"lunghezze diverse: attese {e.Count}, ottenute {a.Count}", message, file, line);
for (int i = 0; i < e.Count; i++)
{
if (!EqualityComparer<T>.Default.Equals(e[i], a[i]))
Fail($"elemento {i}: atteso <{e[i]}> ma ottenuto <{a[i]}>", message, file, line);
}
}
public static void True(bool condition, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (!condition) Fail("condizione falsa", message, file, line);
}
public static void False(bool condition, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (condition) Fail("condizione vera", message, file, line);
}
public static void NotNull(object? value, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (value is null) Fail("valore nullo", message, file, line);
}
/// <summary>Confronto tra reali con tolleranza assoluta.</summary>
public static void Approx(double expected, double actual, double tolerance, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (double.IsNaN(actual) || Math.Abs(expected - actual) > tolerance)
Fail($"atteso {expected} ± {tolerance} ma ottenuto {actual}", message, file, line);
}
/// <summary>Verifica che value sia nell'intervallo chiuso [min, max].</summary>
public static void InRange(double value, double min, double max, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
if (double.IsNaN(value) || value < min || value > max)
Fail($"valore {value} fuori da [{min}, {max}]", message, file, line);
}
public static TException Throws<TException>(Action action, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0) where TException : Exception
{
try
{
action();
}
catch (TException ex)
{
return ex;
}
catch (Exception ex)
{
Fail($"attesa {typeof(TException).Name} ma lanciata {ex.GetType().Name}: {ex.Message}", message, file, line);
}
Fail($"attesa {typeof(TException).Name} ma nessuna eccezione", message, file, line);
return null!;
}
[System.Diagnostics.CodeAnalysis.DoesNotReturn]
public static void Fail(string reason, string? message = null,
[CallerFilePath] string file = "", [CallerLineNumber] int line = 0)
{
string where = $"{Path.GetFileName(file)}:{line}";
throw new AssertionException(message is null ? $"{reason} ({where})" : $"{message}: {reason} ({where})");
}
}
@@ -0,0 +1,18 @@
namespace ViaFerrea.Tests.Harness;
/// <summary>
/// Marca un metodo come test. Il metodo può essere statico o d'istanza (classe con costruttore
/// senza parametri), restituire void o Task.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public sealed class TestAttribute : Attribute
{
/// <summary>Test lungo (simulazioni pluriennali): escluso con --skip-slow.</summary>
public bool Slow { get; init; }
/// <summary>Test che non può girare in parallelo con altri (porte di rete, processi figli).</summary>
public bool Isolated { get; init; }
/// <summary>Descrizione facoltativa mostrata in --list.</summary>
public string? Description { get; init; }
}
+120
View File
@@ -0,0 +1,120 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Reflection;
namespace ViaFerrea.Tests.Harness;
/// <summary>
/// Scopre i metodi [Test] per reflection e li esegue. Opzioni:
/// filtri liberi (sottostringa del nome), --list, --serial, --skip-slow.
/// Il codice di uscita è 0 solo se tutti i test selezionati passano.
/// </summary>
public static class TestRunner
{
private sealed record TestCase(string Name, MethodInfo Method, TestAttribute Attribute);
private sealed record TestOutcome(string Name, bool Passed, long Millis, string? Error);
public static int Run(string[] args, Assembly assembly)
{
bool list = args.Contains("--list");
bool serial = args.Contains("--serial");
bool skipSlow = args.Contains("--skip-slow");
var filters = args.Where(a => !a.StartsWith("--", StringComparison.Ordinal)).ToArray();
var tests = Discover(assembly)
.Where(t => filters.Length == 0 || filters.Any(f => t.Name.Contains(f, StringComparison.OrdinalIgnoreCase)))
.Where(t => !(skipSlow && t.Attribute.Slow))
.OrderBy(t => t.Name, StringComparer.Ordinal)
.ToList();
if (list)
{
foreach (var t in tests)
Console.WriteLine($"{t.Name}{(t.Attribute.Slow ? " [lento]" : "")}{(t.Attribute.Description is { } d ? " — " + d : "")}");
return 0;
}
Console.WriteLine($"Via Ferrea — {tests.Count} test selezionati");
var total = Stopwatch.StartNew();
var outcomes = new ConcurrentBag<TestOutcome>();
var parallel = tests.Where(t => !serial && !t.Attribute.Isolated).ToList();
var sequential = tests.Where(t => serial || t.Attribute.Isolated).ToList();
Parallel.ForEach(parallel, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount) },
t =>
{
var o = Execute(t);
Report(o);
outcomes.Add(o);
});
foreach (var t in sequential)
{
var o = Execute(t);
Report(o);
outcomes.Add(o);
}
var failed = outcomes.Where(o => !o.Passed).OrderBy(o => o.Name, StringComparer.Ordinal).ToList();
Console.WriteLine();
Console.WriteLine($"Eseguiti {outcomes.Count}, superati {outcomes.Count - failed.Count}, falliti {failed.Count} in {total.Elapsed.TotalSeconds:F1} s");
foreach (var f in failed)
Console.WriteLine($" FALLITO {f.Name}: {f.Error}");
return failed.Count == 0 && tests.Count > 0 ? 0 : 1;
}
private static readonly Lock ConsoleLock = new();
private static void Report(TestOutcome o)
{
lock (ConsoleLock)
{
if (o.Passed)
Console.WriteLine($" ok {o.Name} ({o.Millis} ms)");
else
Console.WriteLine($" FALLITO {o.Name} ({o.Millis} ms)\n {o.Error}");
}
}
private static IEnumerable<TestCase> Discover(Assembly assembly)
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
foreach (var type in assembly.GetTypes())
{
foreach (var method in type.GetMethods(flags))
{
var attr = method.GetCustomAttribute<TestAttribute>();
if (attr is null) continue;
if (method.GetParameters().Length != 0)
throw new InvalidOperationException($"Il test {type.Name}.{method.Name} non deve avere parametri");
yield return new TestCase($"{type.Name}.{method.Name}", method, attr);
}
}
}
private static TestOutcome Execute(TestCase t)
{
var sw = Stopwatch.StartNew();
try
{
object? instance = t.Method.IsStatic ? null : Activator.CreateInstance(t.Method.DeclaringType!);
object? result = t.Method.Invoke(instance, null);
if (result is Task task) task.GetAwaiter().GetResult();
(instance as IDisposable)?.Dispose();
return new TestOutcome(t.Name, true, sw.ElapsedMilliseconds, null);
}
catch (TargetInvocationException ex) when (ex.InnerException is not null)
{
return new TestOutcome(t.Name, false, sw.ElapsedMilliseconds, Describe(ex.InnerException));
}
catch (Exception ex)
{
return new TestOutcome(t.Name, false, sw.ElapsedMilliseconds, Describe(ex));
}
}
private static string Describe(Exception ex) => ex is AssertionException
? ex.Message
: $"{ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}";
}
+11
View File
@@ -0,0 +1,11 @@
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests;
/// <summary>
/// Punto d'ingresso unico: dotnet run --project tests/ViaFerrea.Tests [-- filtri] [--list] [--serial] [--skip-slow].
/// </summary>
public static class TestProgram
{
public static int Main(string[] args) => TestRunner.Run(args, typeof(TestProgram).Assembly);
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Harness di test interno: nessun framework esterno, si esegue con dotnet run. -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>ViaFerrea.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\ViaFerrea.Core\ViaFerrea.Core.csproj" />
<ProjectReference Include="..\..\src\ViaFerrea.Protocol\ViaFerrea.Protocol.csproj" />
<ProjectReference Include="..\..\src\ViaFerrea.Server\ViaFerrea.Server.csproj" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\data\**\*.json" LinkBase="data" CopyToOutputDirectory="PreserveNewest" />
<Content Include="scenarios\**\*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>