Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.7"/>
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="9.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="9.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="9.0.3"/>
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="9.0.3"/>
</ItemGroup>

</Project>
15 changes: 8 additions & 7 deletions src/AStar.Dev.Testing.Dashboard.Server/Controllers/TrxParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,18 @@ public static List<TestResult> ParseTrx(string filePath)
const string initialSearchString = "../../test/";
const string secondSearchString = ".Tests.Unit/TestResults/results.trx";
var index = filePath.LastIndexOf(initialSearchString, StringComparison.Ordinal) + initialSearchString.Length;
var index2 = filePath.LastIndexOf(secondSearchString, StringComparison.Ordinal) -index;
var index2 = filePath.LastIndexOf(secondSearchString, StringComparison.Ordinal) - index;
var root = filePath.Substring(index, index2);

var results = doc.Descendants(ns + "UnitTestResult")
.Select(x => new TestResult
{
ProjectName = root,
Name = x.Attribute("testName")?.Value,
Outcome = x.Attribute("outcome")?.Value,
Duration = x.Attribute("duration")?.Value,
StartTime = x.Attribute("startTime")?.Value,
EndTime = x.Attribute("endTime")?.Value
ProjectName = root,
Name = x.Attribute("testName")?.Value,
Outcome = x.Attribute("outcome")?.Value,
Duration = x.Attribute("duration")?.Value,
StartTime = x.Attribute("startTime")?.Value,
EndTime = x.Attribute("endTime")?.Value
})
.ToList();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ public class TestResult
public DateTime Timestamp { get; set; }
public string? StartTime { get ; set ; }
public string? EndTime { get ; set ; }
public string ProjectName { get ; set ; }
public string ProjectName { get ; set ; }
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Xml.Linq;
using AStar.Dev.Testing.Dashboard.Server.Controllers;
using AStar.Dev.Testing.Dashboard.Server.Models;

namespace AStar.Dev.Testing.Dashboard.Server.TestCoverage;

Expand All @@ -18,87 +14,87 @@ public static WebApplication MapCodeCoverageEndpoints(this WebApplication app)

// IMPORTANT: Update this to the root directory where your projects are located.
// This is the starting point for the script to find the test results.
string path = Directory.GetCurrentDirectory();
string rootDirectoryToScan = Path.Combine(path, "../../../");
var path = Directory.GetCurrentDirectory();
var rootDirectoryToScan = Path.Combine(path, "../../../");
Console.WriteLine(rootDirectoryToScan);


// ------------------------------------------------------------------------------------------------
// API Endpoints
// ------------------------------------------------------------------------------------------------

// Endpoint for Code Coverage Results
IResult FindAndProcessFiles(string filePattern, Func<string, JsonNode> processFile)
{
// Check if the root directory exists
if (!Directory.Exists(rootDirectoryToScan))
{
return Results.NotFound($"The root directory '{rootDirectoryToScan}' does not exist.");
}

// Find all test result files recursively.
// The `testresults.trx` and `coverage.json` files are nested within
// a GUID-named folder inside the `TestResults` directory.
var files = Directory.EnumerateFiles(
rootDirectoryToScan,
filePattern,
SearchOption.AllDirectories).ToList();
IResult FindAndProcessFiles(string filePattern, Func<string, JsonNode> processFile)
{
// Check if the root directory exists
if (!Directory.Exists(rootDirectoryToScan))
{
return Results.NotFound($"The root directory '{rootDirectoryToScan}' does not exist.");
}

if (files.Count == 0)
{
return Results.NotFound($"No files matching '{filePattern}' were found in '{rootDirectoryToScan}'.");
}
// Find all test result files recursively.
// The `testresults.trx` and `coverage.json` files are nested within
// a GUID-named folder inside the `TestResults` directory.
var files = Directory.EnumerateFiles(
rootDirectoryToScan,
filePattern,
SearchOption.AllDirectories).ToList();

var groupedData = new Dictionary<string, JsonNode>();
if (files.Count == 0)
{
return Results.NotFound($"No files matching '{filePattern}' were found in '{rootDirectoryToScan}'.");
}

foreach (var file in files)
{
try
{
// Infer the project name from the file path.
// A common pattern is that the project directory is two levels up from the file itself.
var projectDirectory = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(file)));
var groupedData = new Dictionary<string, JsonNode>();

if (projectDirectory == null)
foreach (var file in files)
{
continue;
}
try
{
// Infer the project name from the file path.
// A common pattern is that the project directory is two levels up from the file itself.
var projectDirectory = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(file)));

var projectName = Path.GetFileName(projectDirectory);
if (projectDirectory == null)
{
continue;
}

// Process the file and add to the dictionary.
groupedData[projectName] = processFile(file);
}
catch (Exception ex)
{
Console.WriteLine($"Error processing file '{file}': {ex.Message}");
var projectName = Path.GetFileName(projectDirectory);

// Process the file and add to the dictionary.
groupedData[projectName] = processFile(file);
}
catch (Exception ex)
{
Console.WriteLine($"Error processing file '{file}': {ex.Message}");
}
}

return Results.Ok(groupedData);
}
}

return Results.Ok(groupedData);
}
app.MapGet("/api/coverage", () =>
{
return FindAndProcessFiles("coverage.json", file =>
{
var jsonContent = File.ReadAllText(file);
var jsonObject = JsonNode.Parse(jsonContent);

app.MapGet("/api/coverage", () =>
{
return FindAndProcessFiles("coverage.json", file =>
{
var jsonContent = File.ReadAllText(file);
var jsonObject = JsonNode.Parse(jsonContent);
if (jsonObject?["files"] is not JsonObject filesNode)
{
return JsonNode.Parse("{}")!;
}

if (jsonObject?["files"] is not JsonObject filesNode)
{
return JsonNode.Parse("{}")!;
}
var summary = new Dictionary<string, FileCoverageSummary>();

var summary = new Dictionary<string, FileCoverageSummary>();
CalculateFileCoverageSummary(filesNode, summary);

CalculateFileCoverageSummary(filesNode, summary);
return JsonNode.Parse(JsonSerializer.Serialize(summary))!;
});
})
.WithName("GetCoverageResults")
.WithOpenApi();

return JsonNode.Parse(JsonSerializer.Serialize(summary))!;
});
})
.WithName("GetCoverageResults")
.WithOpenApi();
return app;
}

Expand Down Expand Up @@ -135,6 +131,7 @@ private static void CalculateFileCoverageSummary(JsonObject filesNode, Dictionar
if (branch is JsonArray branchData && branchData.Count >= 2)
{
var coverageCount = branchData[1]?.GetValue<int>() ?? 0;

if (coverageCount > 0)
{
branchesCovered++;
Expand All @@ -152,13 +149,13 @@ private static void CalculateFileCoverageSummary(JsonObject filesNode, Dictionar
var totalBranches = branchesCovered + branchesNotCovered;
var branchPercentage = totalBranches > 0 ? (double)branchesCovered / totalBranches * 100 : 100.0;

summary[filePathKey] = new FileCoverageSummary(
linesCovered,
linesNotCovered,
branchesCovered,
branchesNotCovered,
linePercentage,
branchPercentage);
summary[filePathKey] = new (
linesCovered,
linesNotCovered,
branchesCovered,
branchesNotCovered,
linePercentage,
branchPercentage);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public static WebApplication MapTestResultsEndpoint(this WebApplication app)
{
var filePath = Path.Combine(dir, "TestResults", "results.trx");

if (!System.IO.File.Exists(filePath))
if (!File.Exists(filePath))
{
continue;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
@namespace AStar.Dev.Testing.Dashboard.Components.Layout
@inherits Microsoft.AspNetCore.Components.LayoutComponentBase
@inject Services.ThemeService ThemeService
@using AStar.Dev.Testing.Dashboard.Services
@inherits LayoutComponentBase
@inject ThemeService ThemeService

<div class="page">
<div class="sidebar">
Expand All @@ -9,7 +10,7 @@

<main>
<div class="top-row px-4">
<ThemeToggle />
<ThemeToggle/>
<a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
</div>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
line-height: 3rem;
width: 100%;
transition: color var(--transition-duration) ease,
background-color var(--transition-duration) ease;
background-color var(--transition-duration) ease;
}

.nav-item ::deep a.active {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
private int currentCount = 0;
private int currentCount ;

private void IncrementCount()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,3 @@ public partial class Dashboard : ComponentBase

protected override async Task OnInitializedAsync() => Results = await ResultsService.GetAllResultsAsync();
}

5 changes: 3 additions & 2 deletions src/AStar.Dev.Testing.Dashboard/Components/Pages/Error.razor
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
@page "/Error"
@using System.Diagnostics
@using Microsoft.AspNetCore.Components

<PageTitle>Error</PageTitle>

Expand Down Expand Up @@ -33,7 +32,9 @@
private string? RequestId { get; set; }
private bool ShowRequestId => !string.IsNullOrEmpty(RequestId);

protected override void OnInitialized() =>
protected override void OnInitialized()
{
RequestId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier;
}

}
5 changes: 3 additions & 2 deletions src/AStar.Dev.Testing.Dashboard/Components/Routes.razor
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<Router AppAssembly="typeof(Program).Assembly">
@using AStar.Dev.Testing.Dashboard.Components.Layout
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)"/>
<RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)"/>
<FocusOnNavigate RouteData="routeData" Selector="h1"/>
</Found>
</Router>
3 changes: 2 additions & 1 deletion src/AStar.Dev.Testing.Dashboard/Components/ThemeToggle.razor
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
@using AStar.Dev.Testing.Dashboard.Services
@namespace AStar.Dev.Testing.Dashboard.Components
@inject Services.ThemeService ThemeService
@inject ThemeService ThemeService
@inject IJSRuntime JsRuntime

<div class="theme-toggle">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,3 @@ namespace AStar.Dev.Testing.Dashboard.Components;
public partial class ThemeToggle : ComponentBase
{
}

3 changes: 1 addition & 2 deletions src/AStar.Dev.Testing.Dashboard/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using AStar.Dev.Test.Dashboard.Ui.Services;
using AStar.Dev.Testing.Dashboard;
using AStar.Dev.Testing.Dashboard.Components;
using AStar.Dev.Testing.Dashboard.Services;

Expand All @@ -22,7 +21,7 @@
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseExceptionHandler("/Error", true);

// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
Expand Down
18 changes: 9 additions & 9 deletions src/AStar.Dev.Testing.Dashboard/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7057",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7057",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
3 changes: 2 additions & 1 deletion src/AStar.Dev.Testing.Dashboard/Services/ThemeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ namespace AStar.Dev.Testing.Dashboard.Services;

public class ThemeService
{
public event Action? OnThemeChange;
private string currentTheme = "dark";

public string CurrentTheme
Expand All @@ -19,4 +18,6 @@ public string CurrentTheme
OnThemeChange?.Invoke();
}
}

public event Action? OnThemeChange;
}
Loading
Loading