refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,262 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Chronos.Testing;
|
||||
|
||||
/// <summary>Assertions with messages that state expected and actual values.</summary>
|
||||
public static class Assert
|
||||
{
|
||||
public static void True([System.Diagnostics.CodeAnalysis.DoesNotReturnIf(false)] bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null)
|
||||
{
|
||||
if (!condition) Fail(message ?? $"Expected true: {expression}");
|
||||
}
|
||||
|
||||
public static void False([System.Diagnostics.CodeAnalysis.DoesNotReturnIf(true)] bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null)
|
||||
{
|
||||
if (condition) Fail(message ?? $"Expected false: {expression}");
|
||||
}
|
||||
|
||||
public static void Null(object? value, [CallerArgumentExpression(nameof(value))] string? expression = null)
|
||||
{
|
||||
if (value is not null) Fail($"Expected null: {expression} was {Format(value)}");
|
||||
}
|
||||
|
||||
public static T NotNull<T>([System.Diagnostics.CodeAnalysis.NotNull] T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class
|
||||
{
|
||||
if (value is null) Fail($"Expected non-null: {expression}");
|
||||
return value!;
|
||||
}
|
||||
|
||||
public static T NotNull<T>([System.Diagnostics.CodeAnalysis.NotNull] T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : struct
|
||||
{
|
||||
if (value is null) Fail($"Expected non-null: {expression}");
|
||||
return value!.Value;
|
||||
}
|
||||
|
||||
public static void Equal<T>(T expected, T actual, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (!EqualityComparer<T>.Default.Equals(expected, actual))
|
||||
Fail(Prefix(message) + $"{expression}: expected {Format(expected)}, actual {Format(actual)}");
|
||||
}
|
||||
|
||||
public static void NotEqual<T>(T unexpected, T actual, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (EqualityComparer<T>.Default.Equals(unexpected, actual))
|
||||
Fail(Prefix(message) + $"{expression}: did not expect {Format(unexpected)}");
|
||||
}
|
||||
|
||||
public static void Same(object? expected, object? actual, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (!ReferenceEquals(expected, actual)) Fail($"{expression}: expected the same instance");
|
||||
}
|
||||
|
||||
/// <summary>|expected − actual| ≤ tolerance.</summary>
|
||||
public static void Approximately(double expected, double actual, double tolerance, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (double.IsNaN(actual) || Math.Abs(expected - actual) > tolerance)
|
||||
Fail(Prefix(message) + $"{expression}: expected {F(expected)} ± {F(tolerance)}, actual {F(actual)} (diff {F(Math.Abs(expected - actual))})");
|
||||
}
|
||||
|
||||
/// <summary>Distance between two points ≤ <paramref name="pixels"/>.</summary>
|
||||
public static void Within(double expectedX, double expectedY, double actualX, double actualY, double pixels, string? message = null)
|
||||
{
|
||||
var d = Math.Sqrt((expectedX - actualX) * (expectedX - actualX) + (expectedY - actualY) * (expectedY - actualY));
|
||||
if (!(d <= pixels))
|
||||
Fail(Prefix(message) + $"expected ({F(expectedX)}, {F(expectedY)}) within {F(pixels)} px, actual ({F(actualX)}, {F(actualY)}) at {F(d)} px");
|
||||
}
|
||||
|
||||
public static void InRange(double actual, double min, double max, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (!(actual >= min && actual <= max))
|
||||
Fail(Prefix(message) + $"{expression}: expected in [{F(min)}, {F(max)}], actual {F(actual)}");
|
||||
}
|
||||
|
||||
public static void Greater(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (!(actual > bound)) Fail(Prefix(message) + $"{expression}: expected > {F(bound)}, actual {F(actual)}");
|
||||
}
|
||||
|
||||
public static void GreaterOrEqual(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (!(actual >= bound)) Fail(Prefix(message) + $"{expression}: expected ≥ {F(bound)}, actual {F(actual)}");
|
||||
}
|
||||
|
||||
public static void Less(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (!(actual < bound)) Fail(Prefix(message) + $"{expression}: expected < {F(bound)}, actual {F(actual)}");
|
||||
}
|
||||
|
||||
public static void LessOrEqual(double actual, double bound, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (!(actual <= bound)) Fail(Prefix(message) + $"{expression}: expected ≤ {F(bound)}, actual {F(actual)}");
|
||||
}
|
||||
|
||||
public static void SequenceEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, string? message = null, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
var e = expected.ToList();
|
||||
var a = actual.ToList();
|
||||
var n = Math.Min(e.Count, a.Count);
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
if (!EqualityComparer<T>.Default.Equals(e[i], a[i]))
|
||||
Fail(Prefix(message) + $"{expression}: first difference at [{i}]: expected {Format(e[i])}, actual {Format(a[i])}");
|
||||
}
|
||||
if (e.Count != a.Count)
|
||||
Fail(Prefix(message) + $"{expression}: expected {e.Count} items, actual {a.Count}");
|
||||
}
|
||||
|
||||
public static void BytesEqual(ReadOnlySpan<byte> expected, ReadOnlySpan<byte> actual, string? message = null)
|
||||
{
|
||||
var n = Math.Min(expected.Length, actual.Length);
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
if (expected[i] != actual[i])
|
||||
Fail(Prefix(message) + $"bytes differ at offset {i}: expected 0x{expected[i]:X2}, actual 0x{actual[i]:X2}");
|
||||
}
|
||||
if (expected.Length != actual.Length)
|
||||
Fail(Prefix(message) + $"expected {expected.Length} bytes, actual {actual.Length}");
|
||||
}
|
||||
|
||||
/// <summary>Every element is ≥ (or > when strict) the previous one.</summary>
|
||||
public static void Monotonic(IEnumerable<double> values, bool strict = false, bool decreasing = false, string? message = null)
|
||||
{
|
||||
var i = 0;
|
||||
double? previous = null;
|
||||
foreach (var v in values)
|
||||
{
|
||||
if (previous is { } p)
|
||||
{
|
||||
var ok = decreasing
|
||||
? (strict ? v < p : v <= p)
|
||||
: (strict ? v > p : v >= p);
|
||||
if (!ok) Fail(Prefix(message) + $"not monotonic at [{i}]: {F(p)} then {F(v)}");
|
||||
}
|
||||
previous = v;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Contains<T>(T expected, IEnumerable<T> collection, [CallerArgumentExpression(nameof(collection))] string? expression = null)
|
||||
{
|
||||
if (!collection.Contains(expected)) Fail($"{expression}: does not contain {Format(expected)}");
|
||||
}
|
||||
|
||||
/// <summary>At least one element satisfies <paramref name="predicate"/>.</summary>
|
||||
public static T Contains<T>(IEnumerable<T> collection, Func<T, bool> predicate, [CallerArgumentExpression(nameof(predicate))] string? expression = null)
|
||||
{
|
||||
foreach (var item in collection)
|
||||
{
|
||||
if (predicate(item)) return item;
|
||||
}
|
||||
Fail($"No element matches {expression}");
|
||||
return default!;
|
||||
}
|
||||
|
||||
public static void DoesNotContain<T>(T unexpected, IEnumerable<T> collection, [CallerArgumentExpression(nameof(collection))] string? expression = null)
|
||||
{
|
||||
if (collection.Contains(unexpected)) Fail($"{expression}: unexpectedly contains {Format(unexpected)}");
|
||||
}
|
||||
|
||||
public static void Contains(string expected, string? actual, [CallerArgumentExpression(nameof(actual))] string? expression = null)
|
||||
{
|
||||
if (actual is null || !actual.Contains(expected, StringComparison.Ordinal))
|
||||
Fail($"{expression}: expected to contain \"{expected}\", actual {Format(actual)}");
|
||||
}
|
||||
|
||||
public static void Empty(IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null)
|
||||
{
|
||||
foreach (var item in collection) Fail($"{expression}: expected empty, first item {Format(item)}");
|
||||
}
|
||||
|
||||
public static void NotEmpty(IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null)
|
||||
{
|
||||
foreach (var _ in collection) return;
|
||||
Fail($"{expression}: expected at least one item");
|
||||
}
|
||||
|
||||
public static void Count(int expected, IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null)
|
||||
{
|
||||
var n = 0;
|
||||
foreach (var _ in collection) n++;
|
||||
if (n != expected) Fail($"{expression}: expected {expected} items, actual {n}");
|
||||
}
|
||||
|
||||
public static TException Throws<TException>(Action action, [CallerArgumentExpression(nameof(action))] string? expression = null) where TException : Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
action();
|
||||
}
|
||||
catch (TException ex)
|
||||
{
|
||||
return ex;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Fail($"{expression}: expected {typeof(TException).Name}, got {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
Fail($"{expression}: expected {typeof(TException).Name}, nothing was thrown");
|
||||
return null!;
|
||||
}
|
||||
|
||||
public static async Task<TException> ThrowsAsync<TException>(Func<Task> action, [CallerArgumentExpression(nameof(action))] string? expression = null) where TException : Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
await action().ConfigureAwait(false);
|
||||
}
|
||||
catch (TException ex)
|
||||
{
|
||||
return ex;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Fail($"{expression}: expected {typeof(TException).Name}, got {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
Fail($"{expression}: expected {typeof(TException).Name}, nothing was thrown");
|
||||
return null!;
|
||||
}
|
||||
|
||||
public static void DoesNotThrow(Action action, [CallerArgumentExpression(nameof(action))] string? expression = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
action();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Fail($"{expression}: unexpected {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static void FileExists(string path)
|
||||
{
|
||||
if (!File.Exists(path)) Fail($"File not found: {path}");
|
||||
}
|
||||
|
||||
public static void FileMissing(string path)
|
||||
{
|
||||
if (File.Exists(path)) Fail($"File should not exist: {path}");
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.DoesNotReturn]
|
||||
public static void Fail(string message) => throw new AssertionException(message);
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.DoesNotReturn]
|
||||
public static void Inconclusive(string reason) => throw new SkipException(reason);
|
||||
|
||||
private static string Prefix(string? message) => string.IsNullOrEmpty(message) ? string.Empty : message + ": ";
|
||||
|
||||
private static string F(double v) => v.ToString("G6", CultureInfo.InvariantCulture);
|
||||
|
||||
internal static string Format(object? value) => value switch
|
||||
{
|
||||
null => "null",
|
||||
string s => "\"" + s + "\"",
|
||||
double d => F(d),
|
||||
float f => F(f),
|
||||
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
|
||||
_ => value.ToString() ?? value.GetType().Name,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace Chronos.Testing;
|
||||
|
||||
/// <summary>Raised by <see cref="Assert"/> when an expectation is not met.</summary>
|
||||
public sealed class AssertionException(string message) : Exception(message);
|
||||
|
||||
/// <summary>Raised by <see cref="Assert.Inconclusive"/> or <see cref="TestContext.Skip"/> to skip at run time.</summary>
|
||||
public sealed class SkipException(string reason) : Exception(reason);
|
||||
@@ -0,0 +1,55 @@
|
||||
namespace Chronos.Testing;
|
||||
|
||||
/// <summary>Marks a public method as a test. The method may be sync or return <see cref="Task"/>/<see cref="ValueTask"/>.</summary>
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
|
||||
public sealed class TestAttribute : Attribute;
|
||||
|
||||
/// <summary>Marks a parameterised test; each <see cref="CaseAttribute"/> is one execution.</summary>
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
|
||||
public sealed class TheoryAttribute : Attribute;
|
||||
|
||||
/// <summary>One set of arguments for a <see cref="TheoryAttribute"/> test.</summary>
|
||||
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
|
||||
public sealed class CaseAttribute(params object?[] arguments) : Attribute
|
||||
{
|
||||
public object?[] Arguments { get; } = arguments ?? [null];
|
||||
|
||||
/// <summary>Optional display name for the case.</summary>
|
||||
public string? Name { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Skips a test (or every test of a class) with a reason.</summary>
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
|
||||
public sealed class SkipAttribute(string reason) : Attribute
|
||||
{
|
||||
public string Reason { get; } = reason;
|
||||
}
|
||||
|
||||
/// <summary>Fails the test when it runs longer than the given number of milliseconds.</summary>
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
|
||||
public sealed class TimeoutAttribute(int milliseconds) : Attribute
|
||||
{
|
||||
public int Milliseconds { get; } = milliseconds;
|
||||
}
|
||||
|
||||
/// <summary>Tags a test or class; filters accept <c>category:name</c>.</summary>
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
|
||||
public sealed class CategoryAttribute(string name) : Attribute
|
||||
{
|
||||
public string Name { get; } = name;
|
||||
}
|
||||
|
||||
/// <summary>Runs only on Windows; skipped elsewhere.</summary>
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
|
||||
public sealed class WindowsOnlyAttribute : Attribute;
|
||||
|
||||
/// <summary>Runs only when the environment variable is set and non-empty; skipped otherwise.</summary>
|
||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
|
||||
public sealed class RequiresEnvironmentAttribute(string variable) : Attribute
|
||||
{
|
||||
public string Variable { get; } = variable;
|
||||
}
|
||||
|
||||
/// <summary>Tests of this class never run concurrently with any other test.</summary>
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
|
||||
public sealed class SerialAttribute : Attribute;
|
||||
@@ -0,0 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>Chronos.Testing</RootNamespace>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,72 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Chronos.Testing;
|
||||
|
||||
internal sealed class ConsoleReporter(bool verbose) : IDisposable
|
||||
{
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
public void Report(TestResult r)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
switch (r.Outcome)
|
||||
{
|
||||
case TestOutcome.Failed:
|
||||
if (WorkflowRun)
|
||||
Console.WriteLine($"::error title=Test failed::{Escape(r.Test.FullName)}: {Escape(r.Message ?? "failed")}");
|
||||
Write(ConsoleColor.Red, "FAIL ");
|
||||
Console.WriteLine($"{r.Test.FullName} ({Ms(r.Duration)})");
|
||||
Console.WriteLine(" " + r.Message);
|
||||
if (r.StackTrace is not null) Console.WriteLine(Indent(r.StackTrace));
|
||||
if (r.Log.Length > 0) Console.WriteLine(Indent(r.Log));
|
||||
break;
|
||||
case TestOutcome.Skipped when verbose:
|
||||
Write(ConsoleColor.Yellow, "SKIP ");
|
||||
Console.WriteLine($"{r.Test.FullName} — {r.Message}");
|
||||
break;
|
||||
case TestOutcome.Passed when verbose:
|
||||
Write(ConsoleColor.Green, "PASS ");
|
||||
Console.WriteLine($"{r.Test.FullName} ({Ms(r.Duration)})");
|
||||
if (r.Log.Length > 0) Console.WriteLine(Indent(r.Log));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Summary(string suite, int passed, int failed, int skipped, TimeSpan elapsed, IReadOnlyList<TestResult> results)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
Console.WriteLine();
|
||||
var slowest = results.Where(r => r.Outcome == TestOutcome.Passed).OrderByDescending(r => r.Duration).Take(3).ToList();
|
||||
if (verbose && slowest.Count > 0)
|
||||
{
|
||||
Console.WriteLine("Slowest:");
|
||||
foreach (var r in slowest) Console.WriteLine($" {Ms(r.Duration),9} {r.Test.FullName}");
|
||||
}
|
||||
Write(failed > 0 ? ConsoleColor.Red : ConsoleColor.Green, failed > 0 ? "FAILED" : "PASSED");
|
||||
Console.WriteLine($" {suite}: {passed} passed, {failed} failed, {skipped} skipped in {elapsed.TotalSeconds.ToString("F1", CultureInfo.InvariantCulture)} s");
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => Console.Out.Flush();
|
||||
|
||||
/// <summary>Running in Gitea Actions, which sets GITHUB_ACTIONS and keeps the GitHub-compatible workflow commands.</summary>
|
||||
private static bool WorkflowRun { get; } = Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true";
|
||||
|
||||
/// <summary>Workflow-command escaping: % and line breaks become %25, %0D and %0A.</summary>
|
||||
private static string Escape(string s) => s.Replace("%", "%25", StringComparison.Ordinal).Replace("\r", "%0D", StringComparison.Ordinal).Replace("\n", "%0A", StringComparison.Ordinal);
|
||||
|
||||
private static string Ms(TimeSpan t) => t.TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture) + " ms";
|
||||
|
||||
private static string Indent(string s) => string.Join(Environment.NewLine, s.TrimEnd().Split('\n').Select(l => " " + l.TrimEnd('\r')));
|
||||
|
||||
private static void Write(ConsoleColor color, string text)
|
||||
{
|
||||
var redirected = Console.IsOutputRedirected;
|
||||
if (!redirected) Console.ForegroundColor = color;
|
||||
Console.Write(text);
|
||||
if (!redirected) Console.ResetColor();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace Chronos.Testing;
|
||||
|
||||
/// <summary>One discovered executable test (a method, or one case of a theory).</summary>
|
||||
public sealed class TestCase
|
||||
{
|
||||
internal TestCase(Type type, MethodInfo method, object?[]? arguments, string? caseName)
|
||||
{
|
||||
Type = type;
|
||||
Method = method;
|
||||
Arguments = arguments;
|
||||
var suffix = arguments is null ? string.Empty : "(" + (caseName ?? string.Join(", ", arguments.Select(Assert.Format))) + ")";
|
||||
FullName = $"{type.FullName}.{method.Name}{suffix}";
|
||||
Categories = type.GetCustomAttributes<CategoryAttribute>()
|
||||
.Concat(method.GetCustomAttributes<CategoryAttribute>())
|
||||
.Select(c => c.Name)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
TimeoutMs = method.GetCustomAttribute<TimeoutAttribute>()?.Milliseconds
|
||||
?? type.GetCustomAttribute<TimeoutAttribute>()?.Milliseconds
|
||||
?? 300_000;
|
||||
Serial = type.GetCustomAttribute<SerialAttribute>() is not null;
|
||||
StaticSkipReason = ComputeSkipReason(type, method);
|
||||
}
|
||||
|
||||
public Type Type { get; }
|
||||
public MethodInfo Method { get; }
|
||||
public object?[]? Arguments { get; }
|
||||
public string FullName { get; }
|
||||
public IReadOnlyList<string> Categories { get; }
|
||||
public int TimeoutMs { get; }
|
||||
public bool Serial { get; }
|
||||
public string? StaticSkipReason { get; }
|
||||
|
||||
private static string? ComputeSkipReason(Type type, MethodInfo method)
|
||||
{
|
||||
var skip = method.GetCustomAttribute<SkipAttribute>() ?? type.GetCustomAttribute<SkipAttribute>();
|
||||
if (skip is not null) return skip.Reason;
|
||||
if ((method.GetCustomAttribute<WindowsOnlyAttribute>() ?? type.GetCustomAttribute<WindowsOnlyAttribute>()) is not null
|
||||
&& !OperatingSystem.IsWindows())
|
||||
return "Windows only";
|
||||
foreach (var env in type.GetCustomAttributes<RequiresEnvironmentAttribute>().Concat(method.GetCustomAttributes<RequiresEnvironmentAttribute>()))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(env.Variable)))
|
||||
return $"{env.Variable} not set";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public enum TestOutcome
|
||||
{
|
||||
Passed,
|
||||
Failed,
|
||||
Skipped,
|
||||
}
|
||||
|
||||
public sealed record TestResult(TestCase Test, TestOutcome Outcome, TimeSpan Duration, string? Message, string? StackTrace, string Log);
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
|
||||
namespace Chronos.Testing;
|
||||
|
||||
/// <summary>
|
||||
/// Per-test services. A test class may take a <see cref="TestContext"/> in its constructor;
|
||||
/// one context is created for every test execution and disposed after it.
|
||||
/// </summary>
|
||||
public sealed class TestContext : IDisposable
|
||||
{
|
||||
private static readonly AsyncLocal<TestContext?> CurrentTest = new();
|
||||
private readonly ConcurrentQueue<string> _log = new();
|
||||
private readonly List<string> _tempDirectories = [];
|
||||
private readonly Lock _gate = new();
|
||||
|
||||
internal TestContext(string testName, bool isSerial, CancellationToken cancellation)
|
||||
{
|
||||
TestName = testName;
|
||||
IsSerial = isSerial;
|
||||
Cancellation = cancellation;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The test running on this flow of execution (its constructor, body and the tasks it starts); null outside tests.
|
||||
/// Lets a test program guard process-wide state, which only a serial test may change.
|
||||
/// </summary>
|
||||
public static TestContext? Current
|
||||
{
|
||||
get => CurrentTest.Value;
|
||||
internal set => CurrentTest.Value = value;
|
||||
}
|
||||
|
||||
public string TestName { get; }
|
||||
|
||||
/// <summary>True when the test's class is <see cref="SerialAttribute"/>: no other test runs beside it.</summary>
|
||||
public bool IsSerial { get; }
|
||||
|
||||
/// <summary>Signalled when the test times out or the run is aborted.</summary>
|
||||
public CancellationToken Cancellation { get; }
|
||||
|
||||
/// <summary>Repository root (the directory that holds <c>Chronos.slnx</c>), or the working directory.</summary>
|
||||
public static string RepositoryRoot { get; } = FindRepositoryRoot();
|
||||
|
||||
/// <summary><c>tests/fixtures</c> under the repository root.</summary>
|
||||
public static string FixturesDirectory => Path.Combine(RepositoryRoot, "tests", "fixtures");
|
||||
|
||||
/// <summary>Creates an empty directory that is deleted when the test ends.</summary>
|
||||
public string CreateTempDirectory(string? hint = null)
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), "chronos-tests", $"{Sanitize(hint ?? TestName)}-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(path);
|
||||
lock (_gate) _tempDirectories.Add(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>Lines written here are printed only when the test fails or in verbose mode.</summary>
|
||||
public void Log(string message) => _log.Enqueue(message);
|
||||
|
||||
public string LogText
|
||||
{
|
||||
get
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
foreach (var line in _log) sb.AppendLine(line);
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.DoesNotReturn]
|
||||
public static void Skip(string reason) => throw new SkipException(reason);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
foreach (var dir in _tempDirectories)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Best effort: a file still open by the OS indexer must not fail the test.
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
_tempDirectories.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
private static string Sanitize(string s)
|
||||
{
|
||||
var chars = s.Select(c => char.IsLetterOrDigit(c) ? c : '-').Take(48).ToArray();
|
||||
return new string(chars);
|
||||
}
|
||||
|
||||
private static string FindRepositoryRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir is not null)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir.FullName, "Chronos.slnx"))) return dir.FullName;
|
||||
dir = dir.Parent;
|
||||
}
|
||||
return Directory.GetCurrentDirectory();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Text;
|
||||
using System.Xml;
|
||||
|
||||
namespace Chronos.Testing;
|
||||
|
||||
/// <summary>
|
||||
/// Discovers and runs tests in an assembly. Test projects are console apps whose entry point is
|
||||
/// <c>return await TestRunner.RunAsync(args, typeof(Program).Assembly);</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Arguments: <c>--filter text</c> (substring of the full name, or <c>category:name</c>; repeatable, OR-combined),
|
||||
/// <c>--exclude text</c>, <c>--junit path</c>, <c>--parallel n</c>, <c>--list</c>, <c>--verbose</c>.
|
||||
/// Exit codes: 0 all passed, 1 failures, 2 usage error or no tests matched.
|
||||
/// </remarks>
|
||||
public static class TestRunner
|
||||
{
|
||||
public static async Task<int> RunAsync(string[] args, Assembly assembly)
|
||||
{
|
||||
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
|
||||
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
|
||||
|
||||
Options options;
|
||||
try
|
||||
{
|
||||
options = Options.Parse(args);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
Console.Error.WriteLine(ex.Message);
|
||||
return 2;
|
||||
}
|
||||
|
||||
var all = Discover(assembly);
|
||||
var selected = all.Where(options.Matches).ToList();
|
||||
if (options.List)
|
||||
{
|
||||
foreach (var t in selected) Console.WriteLine(t.FullName);
|
||||
return 0;
|
||||
}
|
||||
if (selected.Count == 0)
|
||||
{
|
||||
// An empty project is not a failure; a filter that matches nothing is a usage error.
|
||||
var filtered = options.HasFilters;
|
||||
Console.Error.WriteLine(filtered ? "No tests matched." : "No tests discovered.");
|
||||
return filtered ? 2 : 0;
|
||||
}
|
||||
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
var results = new List<TestResult>(selected.Count);
|
||||
var resultsGate = new Lock();
|
||||
using var console = new ConsoleReporter(options.Verbose);
|
||||
|
||||
void Record(TestResult r)
|
||||
{
|
||||
lock (resultsGate) results.Add(r);
|
||||
console.Report(r);
|
||||
}
|
||||
|
||||
var parallel = selected.Where(t => !t.Serial).GroupBy(t => t.Type).ToList();
|
||||
var serial = selected.Where(t => t.Serial).ToList();
|
||||
|
||||
// Classes run in parallel; tests inside a class run in declaration order.
|
||||
await Parallel.ForEachAsync(
|
||||
parallel,
|
||||
new ParallelOptions { MaxDegreeOfParallelism = options.Parallelism },
|
||||
async (group, _) =>
|
||||
{
|
||||
foreach (var test in group) Record(await ExecuteAsync(test).ConfigureAwait(false));
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
foreach (var test in serial) Record(await ExecuteAsync(test).ConfigureAwait(false));
|
||||
|
||||
stopwatch.Stop();
|
||||
var passed = results.Count(r => r.Outcome == TestOutcome.Passed);
|
||||
var failed = results.Count(r => r.Outcome == TestOutcome.Failed);
|
||||
var skipped = results.Count(r => r.Outcome == TestOutcome.Skipped);
|
||||
console.Summary(assembly.GetName().Name ?? "tests", passed, failed, skipped, stopwatch.Elapsed, results);
|
||||
|
||||
if (options.JUnitPath is { } junit)
|
||||
WriteJUnit(junit, assembly.GetName().Name ?? "tests", results, stopwatch.Elapsed);
|
||||
|
||||
return failed > 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<TestCase> Discover(Assembly assembly)
|
||||
{
|
||||
var list = new List<TestCase>();
|
||||
Type[] types;
|
||||
try
|
||||
{
|
||||
types = assembly.GetTypes();
|
||||
}
|
||||
catch (ReflectionTypeLoadException ex)
|
||||
{
|
||||
types = ex.Types.Where(t => t is not null).ToArray()!;
|
||||
}
|
||||
|
||||
foreach (var type in types.Where(t => t is { IsClass: true, IsPublic: true } && !t.IsAbstract).OrderBy(t => t.FullName, StringComparer.Ordinal))
|
||||
list.AddRange(Discover(type));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The tests of one class, in declaration order. Assembly discovery takes top-level classes only, so a class nested
|
||||
/// in a test class is a fixture that runs only when a test hands it to <see cref="ExecuteAsync"/>.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<TestCase> Discover(Type type)
|
||||
{
|
||||
var list = new List<TestCase>();
|
||||
foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).OrderBy(m => m.MetadataToken))
|
||||
{
|
||||
if (method.GetCustomAttribute<TestAttribute>() is not null)
|
||||
{
|
||||
list.Add(new TestCase(type, method, null, null));
|
||||
}
|
||||
else if (method.GetCustomAttribute<TheoryAttribute>() is not null)
|
||||
{
|
||||
foreach (var c in method.GetCustomAttributes<CaseAttribute>())
|
||||
list.Add(new TestCase(type, method, c.Arguments, c.Name));
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>Runs one test (constructor, body, disposal) under its timeout and returns its outcome.</summary>
|
||||
public static async Task<TestResult> ExecuteAsync(TestCase test)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(test);
|
||||
if (test.StaticSkipReason is { } reason)
|
||||
return new TestResult(test, TestOutcome.Skipped, TimeSpan.Zero, reason, null, string.Empty);
|
||||
|
||||
using var cts = new CancellationTokenSource();
|
||||
using var context = new TestContext(test.FullName, test.Serial, cts.Token);
|
||||
var sw = Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
var run = Task.Run(() => InvokeAsync(test, context), CancellationToken.None);
|
||||
var finished = await Task.WhenAny(run, Task.Delay(test.TimeoutMs, CancellationToken.None)).ConfigureAwait(false);
|
||||
if (finished != run)
|
||||
{
|
||||
await cts.CancelAsync().ConfigureAwait(false);
|
||||
// Give cooperative code a moment to observe cancellation before reporting.
|
||||
await Task.WhenAny(run, Task.Delay(2000, CancellationToken.None)).ConfigureAwait(false);
|
||||
return new TestResult(test, TestOutcome.Failed, sw.Elapsed, $"Timed out after {test.TimeoutMs} ms", null, context.LogText);
|
||||
}
|
||||
await run.ConfigureAwait(false);
|
||||
return new TestResult(test, TestOutcome.Passed, sw.Elapsed, null, null, context.LogText);
|
||||
}
|
||||
catch (SkipException ex)
|
||||
{
|
||||
return new TestResult(test, TestOutcome.Skipped, sw.Elapsed, ex.Message, null, context.LogText);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var message = ex is AssertionException ? ex.Message : $"{ex.GetType().FullName}: {ex.Message}";
|
||||
return new TestResult(test, TestOutcome.Failed, sw.Elapsed, message, ex.StackTrace, context.LogText);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task InvokeAsync(TestCase test, TestContext context)
|
||||
{
|
||||
TestContext.Current = context;
|
||||
object? instance = null;
|
||||
try
|
||||
{
|
||||
if (!test.Method.IsStatic)
|
||||
{
|
||||
var ctor = test.Type.GetConstructor([typeof(TestContext)]);
|
||||
instance = Unwrapped(() => ctor is not null
|
||||
? ctor.Invoke([context])
|
||||
: Activator.CreateInstance(test.Type));
|
||||
}
|
||||
|
||||
var parameters = test.Method.GetParameters();
|
||||
var args = BuildArguments(test, parameters, context);
|
||||
var returned = Unwrapped(() => test.Method.Invoke(instance, args));
|
||||
|
||||
switch (returned)
|
||||
{
|
||||
case Task task:
|
||||
await task.ConfigureAwait(false);
|
||||
break;
|
||||
case ValueTask valueTask:
|
||||
await valueTask.ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
switch (instance)
|
||||
{
|
||||
case IAsyncDisposable ad:
|
||||
await ad.DisposeAsync().ConfigureAwait(false);
|
||||
break;
|
||||
case IDisposable d:
|
||||
d.Dispose();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes a reflection call and rethrows what the constructor or method threw, so a skip stays a skip and a failure
|
||||
/// carries its own message and stack trace instead of "Exception has been thrown by the target of an invocation".
|
||||
/// </summary>
|
||||
private static object? Unwrapped(Func<object?> call)
|
||||
{
|
||||
try
|
||||
{
|
||||
return call();
|
||||
}
|
||||
catch (TargetInvocationException tie) when (tie.InnerException is not null)
|
||||
{
|
||||
ExceptionDispatchInfo.Capture(tie.InnerException).Throw();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static object?[] BuildArguments(TestCase test, ParameterInfo[] parameters, TestContext context)
|
||||
{
|
||||
var supplied = test.Arguments ?? [];
|
||||
var result = new object?[parameters.Length];
|
||||
var next = 0;
|
||||
for (var i = 0; i < parameters.Length; i++)
|
||||
{
|
||||
var p = parameters[i];
|
||||
if (p.ParameterType == typeof(TestContext))
|
||||
{
|
||||
result[i] = context;
|
||||
continue;
|
||||
}
|
||||
if (p.ParameterType == typeof(CancellationToken))
|
||||
{
|
||||
result[i] = context.Cancellation;
|
||||
continue;
|
||||
}
|
||||
if (next >= supplied.Length)
|
||||
throw new InvalidOperationException($"{test.FullName}: missing argument for parameter '{p.Name}'");
|
||||
result[i] = Convert(supplied[next++], p.ParameterType);
|
||||
}
|
||||
if (next != supplied.Length)
|
||||
throw new InvalidOperationException($"{test.FullName}: {supplied.Length - next} unused case argument(s)");
|
||||
return result;
|
||||
}
|
||||
|
||||
private static object? Convert(object? value, Type target)
|
||||
{
|
||||
if (value is null) return null;
|
||||
var underlying = Nullable.GetUnderlyingType(target) ?? target;
|
||||
if (underlying.IsInstanceOfType(value)) return value;
|
||||
if (underlying.IsEnum) return Enum.ToObject(underlying, value);
|
||||
return System.Convert.ChangeType(value, underlying, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
private static void WriteJUnit(string path, string suiteName, IReadOnlyList<TestResult> results, TimeSpan elapsed)
|
||||
{
|
||||
var dir = Path.GetDirectoryName(Path.GetFullPath(path));
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
var settings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding(false) };
|
||||
using var w = XmlWriter.Create(path, settings);
|
||||
w.WriteStartDocument();
|
||||
w.WriteStartElement("testsuites");
|
||||
w.WriteStartElement("testsuite");
|
||||
w.WriteAttributeString("name", suiteName);
|
||||
w.WriteAttributeString("tests", results.Count.ToString(CultureInfo.InvariantCulture));
|
||||
w.WriteAttributeString("failures", results.Count(r => r.Outcome == TestOutcome.Failed).ToString(CultureInfo.InvariantCulture));
|
||||
w.WriteAttributeString("skipped", results.Count(r => r.Outcome == TestOutcome.Skipped).ToString(CultureInfo.InvariantCulture));
|
||||
w.WriteAttributeString("time", elapsed.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture));
|
||||
foreach (var r in results.OrderBy(r => r.Test.FullName, StringComparer.Ordinal))
|
||||
{
|
||||
w.WriteStartElement("testcase");
|
||||
w.WriteAttributeString("classname", Clean(r.Test.Type.FullName!));
|
||||
w.WriteAttributeString("name", Clean(r.Test.FullName[(r.Test.Type.FullName!.Length + 1)..]));
|
||||
w.WriteAttributeString("time", r.Duration.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture));
|
||||
if (r.Outcome == TestOutcome.Failed)
|
||||
{
|
||||
w.WriteStartElement("failure");
|
||||
w.WriteAttributeString("message", Clean(r.Message ?? "failed"));
|
||||
w.WriteString(Clean((r.StackTrace ?? string.Empty) + Environment.NewLine + r.Log));
|
||||
w.WriteEndElement();
|
||||
}
|
||||
else if (r.Outcome == TestOutcome.Skipped)
|
||||
{
|
||||
w.WriteStartElement("skipped");
|
||||
w.WriteAttributeString("message", Clean(r.Message ?? string.Empty));
|
||||
w.WriteEndElement();
|
||||
}
|
||||
w.WriteEndElement();
|
||||
}
|
||||
w.WriteEndElement();
|
||||
w.WriteEndElement();
|
||||
w.WriteEndDocument();
|
||||
}
|
||||
|
||||
/// <summary>Escapes characters XML cannot carry (theory cases may contain control characters) as <c>\uXXXX</c>.</summary>
|
||||
private static string Clean(string s)
|
||||
{
|
||||
StringBuilder? sb = null;
|
||||
for (var i = 0; i < s.Length; i++)
|
||||
{
|
||||
var c = s[i];
|
||||
if (XmlConvert.IsXmlChar(c))
|
||||
{
|
||||
sb?.Append(c);
|
||||
continue;
|
||||
}
|
||||
if (char.IsHighSurrogate(c) && i + 1 < s.Length && XmlConvert.IsXmlSurrogatePair(s[i + 1], c))
|
||||
{
|
||||
sb?.Append(c).Append(s[i + 1]);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
sb ??= new StringBuilder(s, 0, i, s.Length + 8);
|
||||
sb.Append(CultureInfo.InvariantCulture, $"\\u{(int)c:X4}");
|
||||
}
|
||||
return sb?.ToString() ?? s;
|
||||
}
|
||||
|
||||
private sealed class Options
|
||||
{
|
||||
public List<string> Filters { get; } = [];
|
||||
public List<string> Excludes { get; } = [];
|
||||
public string? JUnitPath { get; private set; }
|
||||
public int Parallelism { get; private set; } = Math.Max(1, Environment.ProcessorCount);
|
||||
public bool List { get; private set; }
|
||||
public bool Verbose { get; private set; }
|
||||
public bool HasFilters => Filters.Count > 0 || Excludes.Count > 0;
|
||||
|
||||
public static Options Parse(string[] args)
|
||||
{
|
||||
var o = new Options();
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
string Next() => i + 1 < args.Length ? args[++i] : throw new ArgumentException($"Missing value after {args[i]}");
|
||||
switch (args[i])
|
||||
{
|
||||
case "--filter": o.Filters.Add(Next()); break;
|
||||
case "--exclude": o.Excludes.Add(Next()); break;
|
||||
case "--junit": o.JUnitPath = Next(); break;
|
||||
case "--parallel": o.Parallelism = Math.Max(1, int.Parse(Next(), CultureInfo.InvariantCulture)); break;
|
||||
case "--list": o.List = true; break;
|
||||
case "--verbose": o.Verbose = true; break;
|
||||
default: throw new ArgumentException($"Unknown argument {args[i]}. Use --filter, --exclude, --junit, --parallel, --list, --verbose.");
|
||||
}
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
public bool Matches(TestCase t)
|
||||
{
|
||||
if (Excludes.Any(f => Match(t, f))) return false;
|
||||
return Filters.Count == 0 || Filters.Any(f => Match(t, f));
|
||||
}
|
||||
|
||||
private static bool Match(TestCase t, string filter) =>
|
||||
filter.StartsWith("category:", StringComparison.OrdinalIgnoreCase)
|
||||
? t.Categories.Contains(filter["category:".Length..], StringComparer.OrdinalIgnoreCase)
|
||||
: t.FullName.Contains(filter, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Chronos.Testing;
|
||||
|
||||
/// <summary>
|
||||
/// Time budgets of timed tests. <c>CHRONOS_TEST_TIME_FACTOR</c> (at least 1, default 1) stretches them on a CI runner
|
||||
/// that shares its CPU and disks with other services (the Gitea runner on the owner's server, amended 2026-10-23, R3);
|
||||
/// on a development PC the budgets apply as written, and the performance gates of <c>perf.yml</c> never set it.
|
||||
/// </summary>
|
||||
public static class TestTiming
|
||||
{
|
||||
public const string Variable = "CHRONOS_TEST_TIME_FACTOR";
|
||||
|
||||
/// <summary>The factor from <see cref="Variable"/>; 1 when unset, unreadable or below 1.</summary>
|
||||
public static double Factor { get; } = Parse(Environment.GetEnvironmentVariable(Variable));
|
||||
|
||||
/// <summary><paramref name="seconds"/> stretched by <see cref="Factor"/>.</summary>
|
||||
public static double Budget(double seconds) => seconds * Factor;
|
||||
|
||||
/// <summary>The factor a value of <see cref="Variable"/> gives.</summary>
|
||||
public static double Parse(string? value) =>
|
||||
double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var factor) && factor >= 1 && double.IsFinite(factor) ? factor : 1;
|
||||
}
|
||||
Reference in new issue
Block a user