feat: complete GraphTUI standalone graphing terminal application in .NET 10
This commit is contained in:
commit
d70b0390b7
41 changed files with 5131 additions and 0 deletions
94
tests/GraphTUI.Tests/BrailleCanvasTests.cs
Normal file
94
tests/GraphTUI.Tests/BrailleCanvasTests.cs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
using GraphTUI.Core.Models;
|
||||
using GraphTUI.Rendering;
|
||||
|
||||
namespace GraphTUI.Tests;
|
||||
|
||||
public static class BrailleCanvasTests
|
||||
{
|
||||
public static void Register(TestRunner runner)
|
||||
{
|
||||
runner.Add("BrailleCanvas: 2x4 Subpixel Dot Mapping", () =>
|
||||
{
|
||||
var canvas = new BrailleCanvas(1, 1); // 1 cell = 2x4 subpixels
|
||||
|
||||
// Test dot (0, 0) -> bit 0 -> 0x01
|
||||
canvas.Clear(ColorRgb.Background);
|
||||
canvas.SetPixel(0, 0, ColorRgb.White);
|
||||
var (ch0, _, _) = canvas.GetCell(0, 0);
|
||||
Assert.Equal((char)(0x2800 | 0x01), ch0);
|
||||
|
||||
// Test dot (1, 0) -> bit 3 -> 0x08
|
||||
canvas.Clear(ColorRgb.Background);
|
||||
canvas.SetPixel(1, 0, ColorRgb.White);
|
||||
var (ch1, _, _) = canvas.GetCell(0, 0);
|
||||
Assert.Equal((char)(0x2800 | 0x08), ch1);
|
||||
|
||||
// Test dot (0, 3) -> bit 6 -> 0x40
|
||||
canvas.Clear(ColorRgb.Background);
|
||||
canvas.SetPixel(0, 3, ColorRgb.White);
|
||||
var (ch2, _, _) = canvas.GetCell(0, 0);
|
||||
Assert.Equal((char)(0x2800 | 0x40), ch2);
|
||||
|
||||
// Test dot (1, 3) -> bit 7 -> 0x80
|
||||
canvas.Clear(ColorRgb.Background);
|
||||
canvas.SetPixel(1, 3, ColorRgb.White);
|
||||
var (ch3, _, _) = canvas.GetCell(0, 0);
|
||||
Assert.Equal((char)(0x2800 | 0x80), ch3);
|
||||
|
||||
// Test all dots on -> 0xFF
|
||||
canvas.Clear(ColorRgb.Background);
|
||||
for (int y = 0; y < 4; y++)
|
||||
{
|
||||
for (int x = 0; x < 2; x++)
|
||||
{
|
||||
canvas.SetPixel(x, y, ColorRgb.White);
|
||||
}
|
||||
}
|
||||
var (chAll, _, _) = canvas.GetCell(0, 0);
|
||||
Assert.Equal((char)(0x2800 | 0xFF), chAll);
|
||||
});
|
||||
|
||||
runner.Add("BrailleCanvas: Bresenham Line Rasterization", () =>
|
||||
{
|
||||
var canvas = new BrailleCanvas(10, 10);
|
||||
canvas.Clear(ColorRgb.Background);
|
||||
|
||||
// Draw line from (0, 0) to (19, 39)
|
||||
canvas.DrawLine(0, 0, 19, 39, ColorRgb.Cyan);
|
||||
|
||||
// Ensure start and end are set
|
||||
var (startCell, _, _) = canvas.GetCell(0, 0);
|
||||
Assert.True(startCell != ' ', "Start cell should not be empty");
|
||||
|
||||
var (endCell, _, _) = canvas.GetCell(9, 9);
|
||||
Assert.True(endCell != ' ', "End cell should not be empty");
|
||||
});
|
||||
|
||||
runner.Add("Viewport: Math to Subpixel Transformation", () =>
|
||||
{
|
||||
var vp = new Viewport
|
||||
{
|
||||
XMin = -10,
|
||||
XMax = 10,
|
||||
YMin = -5,
|
||||
YMax = 5
|
||||
};
|
||||
|
||||
// (0, 0) should be at center: subW = 20, subH = 20 -> center is (10, 10)
|
||||
bool mapped = vp.MathToSubpixel(0, 0, 21, 21, out int sx, out int sy);
|
||||
Assert.True(mapped);
|
||||
Assert.Equal(10, sx);
|
||||
Assert.Equal(10, sy);
|
||||
|
||||
// Top-left (-10, 5) -> (0, 0)
|
||||
vp.MathToSubpixel(-10, 5, 21, 21, out int sx0, out int sy0);
|
||||
Assert.Equal(0, sx0);
|
||||
Assert.Equal(0, sy0);
|
||||
|
||||
// Bottom-right (10, -5) -> (20, 20)
|
||||
vp.MathToSubpixel(10, -5, 21, 21, out int sx1, out int sy1);
|
||||
Assert.Equal(20, sx1);
|
||||
Assert.Equal(20, sy1);
|
||||
});
|
||||
}
|
||||
}
|
||||
78
tests/GraphTUI.Tests/CalculusTests.cs
Normal file
78
tests/GraphTUI.Tests/CalculusTests.cs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
using GraphTUI.Core.Math;
|
||||
|
||||
namespace GraphTUI.Tests;
|
||||
|
||||
public static class CalculusTests
|
||||
{
|
||||
public static void Register(TestRunner runner)
|
||||
{
|
||||
runner.Add("Calculus: Numerical Derivative", () =>
|
||||
{
|
||||
// d/dx sin(x) at x=0 is cos(0) = 1
|
||||
double dSin0 = Calculus.Derivative(System.Math.Sin, 0.0);
|
||||
Assert.Within(1.0, dSin0, 1e-4);
|
||||
|
||||
// d/dx sin(x) at x=pi/3 is cos(pi/3) = 0.5
|
||||
double dSinPi3 = Calculus.Derivative(System.Math.Sin, System.Math.PI / 3.0);
|
||||
Assert.Within(0.5, dSinPi3, 1e-4);
|
||||
|
||||
// d/dx (x^3) at x=2 is 3*(2^2) = 12
|
||||
double dX3 = Calculus.Derivative(x => x * x * x, 2.0);
|
||||
Assert.Within(12.0, dX3, 1e-4);
|
||||
});
|
||||
|
||||
runner.Add("Calculus: Tangent Line Equation", () =>
|
||||
{
|
||||
// f(x) = x^2 at x0 = 3: slope = 6, y0 = 9
|
||||
// Line: y = 9 + 6*(x - 3) = 6x - 9
|
||||
var (slope, y0, line) = Calculus.TangentLine(x => x * x, 3.0);
|
||||
Assert.Within(6.0, slope, 1e-4);
|
||||
Assert.Within(9.0, y0, 1e-4);
|
||||
Assert.Within(9.0, line(3.0), 1e-4);
|
||||
Assert.Within(15.0, line(4.0), 1e-4);
|
||||
});
|
||||
|
||||
runner.Add("Calculus: Definite Integral (Simpson's Rule)", () =>
|
||||
{
|
||||
// Integral of sin(x) from 0 to pi is 2.0
|
||||
double intSin = Calculus.DefiniteIntegral(System.Math.Sin, 0.0, System.Math.PI, 100);
|
||||
Assert.Within(2.0, intSin, 1e-4);
|
||||
|
||||
// Integral of x^2 from 0 to 1 is 1/3 ~ 0.333333
|
||||
double intX2 = Calculus.DefiniteIntegral(x => x * x, 0.0, 1.0, 100);
|
||||
Assert.Within(1.0 / 3.0, intX2, 1e-4);
|
||||
});
|
||||
|
||||
runner.Add("Calculus: Root Finding", () =>
|
||||
{
|
||||
// Roots of x^2 - 4 on [-5, 5] should be -2 and 2
|
||||
var roots = Calculus.FindRoots(x => x * x - 4.0, -5.0, 5.0, 200);
|
||||
Assert.Equal(2, roots.Count);
|
||||
Assert.Within(-2.0, roots[0], 1e-3);
|
||||
Assert.Within(2.0, roots[1], 1e-3);
|
||||
|
||||
// Roots of x^3 - 3x^2 - x + 3 = (x-1)(x+1)(x-3)
|
||||
var cubicRoots = Calculus.FindRoots(x => x * x * x - 3 * x * x - x + 3, -4.0, 4.0, 300);
|
||||
Assert.Equal(3, cubicRoots.Count);
|
||||
Assert.Within(-1.0, cubicRoots[0], 1e-3);
|
||||
Assert.Within(1.0, cubicRoots[1], 1e-3);
|
||||
Assert.Within(3.0, cubicRoots[2], 1e-3);
|
||||
});
|
||||
|
||||
runner.Add("Calculus: Extrema Detection", () =>
|
||||
{
|
||||
// f(x) = x^3 - 3x on [-2, 2]:
|
||||
// f'(x) = 3x^2 - 3 = 0 -> x = -1 (local max, y=2), x = 1 (local min, y=-2)
|
||||
var extrema = Calculus.FindExtrema(x => x * x * x - 3 * x, -2.0, 2.0, 300);
|
||||
Assert.Equal(2, extrema.Count);
|
||||
|
||||
Assert.Equal(ExtremumType.LocalMaximum, extrema[0].Type);
|
||||
Assert.Within(-1.0, extrema[0].X, 1e-3);
|
||||
Assert.Within(2.0, extrema[0].Y, 1e-3);
|
||||
|
||||
Assert.Equal(ExtremumType.LocalMinimum, extrema[1].Type);
|
||||
Assert.Within(1.0, extrema[1].X, 1e-3);
|
||||
Assert.Within(-2.0, extrema[1].Y, 1e-3);
|
||||
});
|
||||
}
|
||||
}
|
||||
64
tests/GraphTUI.Tests/EvaluatorTests.cs
Normal file
64
tests/GraphTUI.Tests/EvaluatorTests.cs
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
using GraphTUI.Core.Math;
|
||||
|
||||
namespace GraphTUI.Tests;
|
||||
|
||||
public static class EvaluatorTests
|
||||
{
|
||||
public static void Register(TestRunner runner)
|
||||
{
|
||||
runner.Add("Evaluator: Standard Trig and Identity sin^2(x) + cos^2(x) = 1", () =>
|
||||
{
|
||||
var sinEval = Evaluator.Compile("sin(x)");
|
||||
var cosEval = Evaluator.Compile("cos(x)");
|
||||
|
||||
for (double x = -10.0; x <= 10.0; x += 0.5)
|
||||
{
|
||||
double s = sinEval.Evaluate(x);
|
||||
double c = cosEval.Evaluate(x);
|
||||
Assert.Within(System.Math.Sin(x), s, 1e-9);
|
||||
Assert.Within(System.Math.Cos(x), c, 1e-9);
|
||||
Assert.Within(1.0, s * s + c * c, 1e-9);
|
||||
}
|
||||
});
|
||||
|
||||
runner.Add("Evaluator: Hyperbolic and Exponential Functions", () =>
|
||||
{
|
||||
var expEval = Evaluator.Compile("exp(x)");
|
||||
var lnEval = Evaluator.Compile("ln(x)");
|
||||
var sinhEval = Evaluator.Compile("sinh(x)");
|
||||
|
||||
Assert.Within(System.Math.E, expEval.Evaluate(1.0), 1e-9);
|
||||
Assert.Within(1.0, lnEval.Evaluate(System.Math.E), 1e-9);
|
||||
Assert.Within(System.Math.Sinh(2.5), sinhEval.Evaluate(2.5), 1e-9);
|
||||
});
|
||||
|
||||
runner.Add("Evaluator: Dynamic Parameters a, b, c", () =>
|
||||
{
|
||||
var eval = Evaluator.Compile("a*x^2 + b*x + c");
|
||||
|
||||
var lookup = new Dictionary<string, double>
|
||||
{
|
||||
["a"] = 2.0,
|
||||
["b"] = 3.0,
|
||||
["c"] = 1.0
|
||||
};
|
||||
|
||||
// For x = 4: 2*(16) + 3*(4) + 1 = 32 + 12 + 1 = 45
|
||||
double result = eval.Evaluate(4.0, name => lookup[name]);
|
||||
Assert.Equal(45.0, result);
|
||||
});
|
||||
|
||||
runner.Add("Evaluator: Parametric and Polar Evaluation", () =>
|
||||
{
|
||||
var paramX = Evaluator.Compile("cos(t)");
|
||||
var paramY = Evaluator.Compile("sin(t)");
|
||||
double t = System.Math.PI / 4.0;
|
||||
Assert.Within(System.Math.Cos(t), paramX.EvaluateParametricX(t), 1e-9);
|
||||
Assert.Within(System.Math.Sin(t), paramY.EvaluateParametricY(t), 1e-9);
|
||||
|
||||
var polar = Evaluator.Compile("1 + cos(theta)");
|
||||
double th = System.Math.PI / 2.0;
|
||||
Assert.Within(1.0, polar.EvaluatePolar(th), 1e-9);
|
||||
});
|
||||
}
|
||||
}
|
||||
74
tests/GraphTUI.Tests/ExportSessionTests.cs
Normal file
74
tests/GraphTUI.Tests/ExportSessionTests.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
using GraphTUI.Core.Models;
|
||||
using GraphTUI.Rendering;
|
||||
|
||||
namespace GraphTUI.Tests;
|
||||
|
||||
public static class ExportSessionTests
|
||||
{
|
||||
public static void Register(TestRunner runner)
|
||||
{
|
||||
runner.Add("Session: Save & Load Roundtrip", () =>
|
||||
{
|
||||
var original = new SessionData
|
||||
{
|
||||
Viewport = new ViewportDto { XMin = -5, XMax = 5, YMin = -2, YMax = 2 },
|
||||
Parameters =
|
||||
[
|
||||
new ParameterDto { Name = "a", Value = 2.5, Min = -10, Max = 10, Step = 0.1 }
|
||||
],
|
||||
Functions =
|
||||
[
|
||||
new FunctionDto
|
||||
{
|
||||
Id = 1,
|
||||
Type = "Cartesian",
|
||||
Expression = "sin(a*x)",
|
||||
ColorR = 0,
|
||||
ColorG = 220,
|
||||
ColorB = 255,
|
||||
IsVisible = true
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
string json = SessionData.ToJson(original);
|
||||
Assert.True(!string.IsNullOrEmpty(json), "JSON should not be empty");
|
||||
|
||||
var loaded = SessionData.FromJson(json);
|
||||
Assert.True(loaded != null, "Loaded session should not be null");
|
||||
Assert.Equal(-5.0, loaded!.Viewport.XMin);
|
||||
Assert.Equal(5.0, loaded.Viewport.XMax);
|
||||
Assert.Equal(1, loaded.Functions.Count);
|
||||
Assert.Equal("sin(a*x)", loaded.Functions[0].Expression);
|
||||
Assert.Equal(1, loaded.Parameters.Count);
|
||||
Assert.Equal(2.5, loaded.Parameters[0].Value);
|
||||
});
|
||||
|
||||
runner.Add("Export: SVG Output Format", () =>
|
||||
{
|
||||
var vp = new Viewport { XMin = -10, XMax = 10, YMin = -5, YMax = 5 };
|
||||
var fns = new List<GraphFunction>
|
||||
{
|
||||
new(1, "sin(x)", ColorRgb.Cyan),
|
||||
new(2, "cos(t)", ColorRgb.Magenta, FunctionType.Parametric, "sin(2t)")
|
||||
};
|
||||
|
||||
string svg = SvgExporter.Export(vp, fns, _ => 1.0, 800, 500);
|
||||
|
||||
Assert.True(svg.Contains("<svg"), "SVG should have <svg root tag");
|
||||
Assert.True(svg.Contains("</svg>"), "SVG should have </svg> closing tag");
|
||||
Assert.True(svg.Contains("path fill=\"none\" stroke=\"rgb(0,220,255)\""), "SVG should contain path with function color");
|
||||
});
|
||||
|
||||
runner.Add("Export: Text Braille Output", () =>
|
||||
{
|
||||
var canvas = new BrailleCanvas(10, 5);
|
||||
canvas.DrawLine(0, 0, 19, 19, ColorRgb.White);
|
||||
string txt = TextExporter.Export(canvas);
|
||||
|
||||
Assert.True(!string.IsNullOrEmpty(txt), "Text export should not be empty");
|
||||
string[] lines = txt.Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
||||
Assert.Equal(5, lines.Length);
|
||||
});
|
||||
}
|
||||
}
|
||||
16
tests/GraphTUI.Tests/GraphTUI.Tests.csproj
Normal file
16
tests/GraphTUI.Tests/GraphTUI.Tests.csproj
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<LangVersion>preview</LangVersion>
|
||||
<RootNamespace>GraphTUI.Tests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\GraphTUI\GraphTUI.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
113
tests/GraphTUI.Tests/LexerParserTests.cs
Normal file
113
tests/GraphTUI.Tests/LexerParserTests.cs
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
using GraphTUI.Core.Math;
|
||||
|
||||
namespace GraphTUI.Tests;
|
||||
|
||||
public static class LexerParserTests
|
||||
{
|
||||
public static void Register(TestRunner runner)
|
||||
{
|
||||
runner.Add("Lexer: Numbers and Decimals", () =>
|
||||
{
|
||||
var lexer = new Lexer("123 3.14 0.5 1e-3");
|
||||
var tokens = lexer.Tokenize();
|
||||
|
||||
Assert.Equal(TokenType.Number, tokens[0].Type);
|
||||
Assert.Equal(123.0, tokens[0].NumberValue);
|
||||
|
||||
Assert.Equal(TokenType.Number, tokens[1].Type);
|
||||
Assert.Equal(3.14, tokens[1].NumberValue);
|
||||
|
||||
Assert.Equal(TokenType.Number, tokens[2].Type);
|
||||
Assert.Equal(0.5, tokens[2].NumberValue);
|
||||
|
||||
Assert.Equal(TokenType.Number, tokens[3].Type);
|
||||
Assert.Equal(0.001, tokens[3].NumberValue);
|
||||
});
|
||||
|
||||
runner.Add("Lexer: Implicit Multiplication (2x, 3sin(x), (x+1)(x-1))", () =>
|
||||
{
|
||||
// 2x -> 2 * x
|
||||
var tokens1 = new Lexer("2x").Tokenize();
|
||||
Assert.Equal(TokenType.Number, tokens1[0].Type);
|
||||
Assert.Equal(TokenType.Multiply, tokens1[1].Type);
|
||||
Assert.Equal(TokenType.Identifier, tokens1[2].Type);
|
||||
|
||||
// 3sin(x) -> 3 * sin(x)
|
||||
var tokens2 = new Lexer("3sin(x)").Tokenize();
|
||||
Assert.Equal(TokenType.Number, tokens2[0].Type);
|
||||
Assert.Equal(TokenType.Multiply, tokens2[1].Type);
|
||||
Assert.Equal(TokenType.Identifier, tokens2[2].Type);
|
||||
Assert.Equal("sin", tokens2[2].Text);
|
||||
Assert.Equal(TokenType.LParen, tokens2[3].Type);
|
||||
|
||||
// (x+1)(x-1) -> (x+1) * (x-1)
|
||||
var tokens3 = new Lexer("(x+1)(x-1)").Tokenize();
|
||||
Assert.Equal(TokenType.RParen, tokens3[4].Type);
|
||||
Assert.Equal(TokenType.Multiply, tokens3[5].Type);
|
||||
Assert.Equal(TokenType.LParen, tokens3[6].Type);
|
||||
|
||||
// 2pi -> 2 * pi
|
||||
var tokens4 = new Lexer("2pi").Tokenize();
|
||||
Assert.Equal(TokenType.Multiply, tokens4[1].Type);
|
||||
Assert.Equal("pi", tokens4[2].Text);
|
||||
});
|
||||
|
||||
runner.Add("Parser: Precedence of Operators", () =>
|
||||
{
|
||||
// 2 + 3 * 4 == 14
|
||||
var ast1 = Parser.Parse("2 + 3 * 4");
|
||||
var ctx = new EvaluationContext();
|
||||
Assert.Equal(14.0, ast1.Evaluate(in ctx));
|
||||
|
||||
// (2 + 3) * 4 == 20
|
||||
var ast2 = Parser.Parse("(2 + 3) * 4");
|
||||
Assert.Equal(20.0, ast2.Evaluate(in ctx));
|
||||
|
||||
// Power right-associativity: 2^3^2 = 2^(3^2) = 2^9 = 512
|
||||
var ast3 = Parser.Parse("2^3^2");
|
||||
Assert.Equal(512.0, ast3.Evaluate(in ctx));
|
||||
|
||||
// Unary minus: -3^2 should evaluate to -(3^2) = -9
|
||||
var ast4 = Parser.Parse("-3^2");
|
||||
Assert.Equal(-9.0, ast4.Evaluate(in ctx));
|
||||
});
|
||||
|
||||
runner.Add("Parser: Mathematical Constants (pi, e, tau, phi)", () =>
|
||||
{
|
||||
var ctx = new EvaluationContext();
|
||||
|
||||
var astPi = Parser.Parse("pi");
|
||||
Assert.Within(System.Math.PI, astPi.Evaluate(in ctx), 1e-9);
|
||||
|
||||
var astE = Parser.Parse("e");
|
||||
Assert.Within(System.Math.E, astE.Evaluate(in ctx), 1e-9);
|
||||
|
||||
var astTau = Parser.Parse("tau");
|
||||
Assert.Within(System.Math.Tau, astTau.Evaluate(in ctx), 1e-9);
|
||||
|
||||
var astPhi = Parser.Parse("phi");
|
||||
Assert.Within(1.6180339887, astPhi.Evaluate(in ctx), 1e-5);
|
||||
});
|
||||
|
||||
runner.Add("Parser: Multi-argument Functions (min, max, clamp)", () =>
|
||||
{
|
||||
var ctx = new EvaluationContext();
|
||||
|
||||
var astMin = Parser.Parse("min(10, 20)");
|
||||
Assert.Equal(10.0, astMin.Evaluate(in ctx));
|
||||
|
||||
var astMax = Parser.Parse("max(10, 20)");
|
||||
Assert.Equal(20.0, astMax.Evaluate(in ctx));
|
||||
|
||||
var astClamp = Parser.Parse("clamp(25, 0, 10)");
|
||||
Assert.Equal(10.0, astClamp.Evaluate(in ctx));
|
||||
});
|
||||
|
||||
runner.Add("Parser: Syntax Errors", () =>
|
||||
{
|
||||
Assert.Throws<FormatException>(() => Parser.Parse("2 + * 3"));
|
||||
Assert.Throws<FormatException>(() => Parser.Parse("(2 + 3"));
|
||||
Assert.Throws<FormatException>(() => Parser.Parse("sin(x, )"));
|
||||
});
|
||||
}
|
||||
}
|
||||
17
tests/GraphTUI.Tests/Program.cs
Normal file
17
tests/GraphTUI.Tests/Program.cs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
namespace GraphTUI.Tests;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
public static int Main()
|
||||
{
|
||||
var runner = new TestRunner();
|
||||
|
||||
LexerParserTests.Register(runner);
|
||||
EvaluatorTests.Register(runner);
|
||||
CalculusTests.Register(runner);
|
||||
BrailleCanvasTests.Register(runner);
|
||||
ExportSessionTests.Register(runner);
|
||||
|
||||
return runner.RunAll();
|
||||
}
|
||||
}
|
||||
110
tests/GraphTUI.Tests/TestFramework.cs
Normal file
110
tests/GraphTUI.Tests/TestFramework.cs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
namespace GraphTUI.Tests;
|
||||
|
||||
public static class Assert
|
||||
{
|
||||
public static void True(bool condition, string? message = null)
|
||||
{
|
||||
if (!condition)
|
||||
throw new Exception(message ?? "Assertion failed: expected true, got false.");
|
||||
}
|
||||
|
||||
public static void False(bool condition, string? message = null)
|
||||
{
|
||||
if (condition)
|
||||
throw new Exception(message ?? "Assertion failed: expected false, got true.");
|
||||
}
|
||||
|
||||
public static void Equal<T>(T expected, T actual, string? message = null)
|
||||
{
|
||||
if (!EqualityComparer<T>.Default.Equals(expected, actual))
|
||||
throw new Exception(message ?? $"Assertion failed: expected '{expected}', got '{actual}'.");
|
||||
}
|
||||
|
||||
public static void Within(double expected, double actual, double tolerance, string? message = null)
|
||||
{
|
||||
double diff = System.Math.Abs(expected - actual);
|
||||
if (diff > tolerance || double.IsNaN(actual))
|
||||
throw new Exception(message ?? $"Assertion failed: expected '{expected}' +/- {tolerance}, got '{actual}' (diff={diff}).");
|
||||
}
|
||||
|
||||
public static void Throws<TException>(Action action, string? message = null) where TException : Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
action();
|
||||
}
|
||||
catch (TException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception(message ?? $"Assertion failed: expected {typeof(TException).Name}, but got {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
|
||||
throw new Exception(message ?? $"Assertion failed: expected {typeof(TException).Name}, but no exception was thrown.");
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TestRunner
|
||||
{
|
||||
private readonly List<(string Name, Action TestAction)> _tests = [];
|
||||
|
||||
public void Add(string name, Action testAction)
|
||||
{
|
||||
_tests.Add((name, testAction));
|
||||
}
|
||||
|
||||
public int RunAll()
|
||||
{
|
||||
int passed = 0;
|
||||
int failed = 0;
|
||||
var failedTests = new List<(string Name, Exception Error)>();
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Cyan;
|
||||
Console.WriteLine($"\n================ Running {_tests.Count} Unit Tests ================");
|
||||
Console.ResetColor();
|
||||
|
||||
foreach (var (name, action) in _tests)
|
||||
{
|
||||
try
|
||||
{
|
||||
action();
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Console.Write(" [PASS] ");
|
||||
Console.ResetColor();
|
||||
Console.WriteLine(name);
|
||||
passed++;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.Write(" [FAIL] ");
|
||||
Console.ResetColor();
|
||||
Console.WriteLine(name);
|
||||
failedTests.Add((name, ex));
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine("\n-------------------------------------------------------------");
|
||||
if (failed == 0)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Console.WriteLine($"All tests passed! ({passed}/{_tests.Count})");
|
||||
Console.ResetColor();
|
||||
return 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine($"FAILED {failed} test(s):");
|
||||
foreach (var (name, error) in failedTests)
|
||||
{
|
||||
Console.WriteLine($" - {name}: {error.Message}");
|
||||
}
|
||||
Console.ResetColor();
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue