Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions Harp.Toolkit/Benchmark/BenchmarkCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
using System.CommandLine;
using Spectre.Console;

namespace Harp.Toolkit;
public class BenchmarkCommand : Command
{
public BenchmarkCommand()
: base("benchmark", "Run benchmark tests on the device.")
{
PortNameOption portNameOption = new();
Option<FileInfo?> fileOption = new("--report")
{
Description = "Path to the HTML report generated after running tests.",
Required = false,
};

Option<bool> verboseOption = new("--verbose")
{
Description = "Show detailed results for each test.",
Required = false,
};
Options.Add(portNameOption);
Options.Add(fileOption);
Options.Add(verboseOption);
SetAction(parsedResult =>
{
string portName = parsedResult.GetRequiredValue(portNameOption);
FileInfo? reportFile = parsedResult.GetValue(fileOption);
bool verbose = parsedResult.GetValue(verboseOption);
return RunBenchmarks(portName, reportFile, verbose, CancellationToken.None);
});
}

static async Task RunBenchmarks(string portName, FileInfo? reportFile, bool verbose, CancellationToken cancellationToken)
{
AnsiConsole.MarkupLine($"Running tests on [bold]{portName}[/]...");

var runner = new CoreRunner();
var report = new Report
{
DeviceName = $"Harp Device ({portName})",
RunDate = DateTime.Now
};

await AnsiConsole.Progress()
.StartAsync(async ctx =>
{
var task = ctx.AddTask("[green]Running tests...[/]", true, runner.TestCount);

await foreach (var (suite, result) in runner.RunAllAsync(portName, cancellationToken))
{
task.Increment(1);
AnsiConsole.MarkupLine($"[grey]{suite.GetType().Name}::{result.Name}[/] .... {GetResultMarkup(result.Result)}");

var suiteResult = report.Suites.FirstOrDefault(s => s.Name == suite.GetType().Name);
if (suiteResult == null)
{
suiteResult = new SuiteResult
{
Name = suite.GetType().Name,
Description = suite.Description
};
report.Suites.Add(suiteResult);
}
suiteResult.Results.Add(result);
}
});

if (verbose)
{
AnsiConsole.WriteLine();
AnsiConsole.Write(new Rule("[yellow]Detailed Results[/]"));
foreach (var suite in report.Suites)
{
AnsiConsole.MarkupLine($"[bold underline]{suite.Name}[/]");
AnsiConsole.MarkupLine($"[dim]{suite.Description}[/]");

var table = new Table();
table.AddColumn("Test Case");
table.AddColumn("Status");
table.AddColumn("Details");
table.AddColumn("Message");

foreach (var test in suite.Results)
{
string details = "";
string message = test.Result.Message ?? "";

if (test.Result is NumericBenchmarkResult bsr)
{
details = $"Mean: {bsr.Summary.Mean:F4}\nMedian: {bsr.Summary.Median:F4}\nStdDev: {bsr.Summary.StdDev:F4}\nMin: {bsr.Summary.Min:F4}\nMax: {bsr.Summary.Max:F4}\nPercentiles: 99th={bsr.Summary.Percentile99:F4}, 01th={bsr.Summary.Percentile01:F4}";
}
else if (test.Result is ErrorResult er)
{
details = $"{er.Exception.GetType().Name}";
}
else
{
var valProp = test.Result?.GetType().GetProperty("Value");
if (valProp != null)
{
var val = valProp.GetValue(test.Result);
details = val?.ToString() ?? "";
}
}

table.AddRow(
new Markup($"[bold]{test.Name}[/]\n[dim]{test.Description}[/]"),
new Markup(GetResultMarkup(test.Result)),
new Markup(details),
new Markup(message)
);
}
AnsiConsole.Write(table);
AnsiConsole.WriteLine();
}
}

if (reportFile != null)
{
AnsiConsole.Markup("Generating HTML report...");
string html = await HtmlReportGenerator.GenerateAsync(report);
string fileName = reportFile?.FullName ?? $"TestReport_{DateTime.Now:yyyyMMdd_HHmmss}.html";
await File.WriteAllTextAsync(fileName, html, cancellationToken);
AnsiConsole.MarkupLine($"[green]Done![/] Report generated: [link]{fileName}[/]");
}
}

static string GetResultMarkup(IResult result)
{
return result.Status switch
{
Status.Passed => "[green]Passed[/]",
Status.Failed => "[red]Failed[/]",
Status.Error => "[red]Error[/]",
Status.Skipped => "[yellow]Skipped[/]",
_ => $"[white]{result.Status}[/]"
};
}

class CoreRunner : Runner
{
public CoreRunner() : base()
{
AddSuite(new WhoAmISuite());
AddSuite(new RoundTripTestSuite());
AddSuite(new TimestampSecondsSuite());
}
}
}


7 changes: 7 additions & 0 deletions Harp.Toolkit/Benchmark/HarpTestAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Harp.Toolkit;

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class HarpTestAttribute : Attribute
{
public string? Description { get; set; }
}
21 changes: 21 additions & 0 deletions Harp.Toolkit/Benchmark/HtmlReportGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Reflection;
using RazorLight;

namespace Harp.Toolkit;

public static class HtmlReportGenerator
{
public static async Task<string> GenerateAsync(Report report)
{
var engine = new RazorLightEngineBuilder()
.UseFileSystemProject(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))
.UseMemoryCachingProvider()
.Build();

// The template is copied to the output directory under Reporting/ReportTemplate.cshtml
// RazorLight expects the path relative to the project root (which we set to the assembly location)
string templatePath = Path.Combine("Benchmark", "ReportTemplate.cshtml");

return await engine.CompileRenderAsync(templatePath, report);
}
}
8 changes: 8 additions & 0 deletions Harp.Toolkit/Benchmark/Report.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Harp.Toolkit;

public class Report
{
public string DeviceName { get; set; } = "Unknown Device";
public DateTime RunDate { get; set; } = DateTime.Now;
public List<SuiteResult> Suites { get; set; } = new();
}
116 changes: 116 additions & 0 deletions Harp.Toolkit/Benchmark/ReportTemplate.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
@using Harp.Toolkit
@model Harp.Toolkit.Report

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Report - @Model.DeviceName</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body { background-color: #f8f9fa; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
.card { border: none; box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); margin-bottom: 2rem; }
.card-header { background-color: #fff; border-bottom: 1px solid rgba(0,0,0,.125); padding: 1.25rem; }
.status-passed { color: #198754; font-weight: bold; }
.status-failed { color: #dc3545; font-weight: bold; }
.status-error { color: #fd7e14; font-weight: bold; }
.status-skipped { color: #6c757d; font-weight: bold; }
.benchmark-stats { font-size: 0.85rem; color: #495057; }
.table th { font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.05em; }
</style>
</head>
<body>
<div class="container py-5">
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="display-5 mb-0">@Model.DeviceName</h1>
<p class="text-muted mb-0">Test Execution Report &bull; @Model.RunDate.ToString("MMMM dd, yyyy HH:mm:ss")</p>
</div>
<div class="text-end">
<span class="badge bg-primary">Harp Toolkit Test</span>
</div>
</div>

@foreach (var suite in Model.Suites)
{
<div class="card">
<div class="card-header">
<h2 class="h4 mb-1">@suite.Name</h2>
<p class="text-muted mb-0 small">@suite.Description</p>
</div>
<div class="card-body p-0">
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<thead class="table-light">
<tr>
<th style="width: 25%">Test Case</th>
<th style="width: 10%">Status</th>
<th style="width: 35%">Result Details</th>
<th style="width: 30%">Message</th>
</tr>
</thead>
<tbody>
@foreach (var test in suite.Results)
{
<tr>
<td>
<div class="fw-bold">@test.Name</div>
<div class="text-muted small">@test.Description</div>
</td>
<td>
<span class="status-@(test.Result?.Status.ToString().ToLower() ?? "skipped")">
@(test.Result?.Status.ToString().ToUpper() ?? "SKIPPED")
</span>
</td>
<td>
@if (test.Result is NumericBenchmarkResult bsr)
{
<div class="benchmark-stats">
<div class="row">
<div class="col-sm-4"><strong>Mean:</strong> @bsr.Summary.Mean.ToString("F4")</div>
<div class="col-sm-4"><strong>Median:</strong> @bsr.Summary.Median.ToString("F4")</div>
<div class="col-sm-4"><strong>StdDev:</strong> @bsr.Summary.StdDev.ToString("F4")</div>
</div>
<div class="row mt-1">
<div class="col-sm-4"><strong>Min:</strong> @bsr.Summary.Min.ToString("F4")</div>
<div class="col-sm-4"><strong>Max:</strong> @bsr.Summary.Max.ToString("F4")</div>
</div>
</div>
}
else
{
var valProp = test.Result?.GetType().GetProperty("Value");
object? val = null;
if (valProp != null)
{
val = valProp.GetValue(test.Result);
}

if (val != null)
{
<code class="text-dark">@val</code>
}
}

@if (test.Result is ErrorResult er && er.Exception != null)
{
<div class="mt-2">
<pre class="bg-light p-2 small mb-0"><code>@er.Exception.ToString()</code></pre>
</div>
}
</td>
<td>
<span class="small text-muted">@test.Result?.Message</span>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
}
</div>
</body>
</html>
Loading