using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using CommandForge.Application;
using CommandForge.Application.Ports;
using CommandForge.Desktop.Services;
using CommandForge.Desktop.ViewModels;
namespace CommandForge.Tests;
///
/// Tests the pure bug-report builders: the environment block, the "What happened?" text and the
/// address that opens a new issue on the GitLab mirror with the Bug template answered.
///
public sealed partial class ReportBugTemplateTests
{
[Fact]
public void BuildEnvironment_IncludesVersionOsAndArchitecture()
{
var env = ReportBugViewModel.BuildEnvironment("1.2.3", "Windows 11", Architecture.X64);
Assert.Contains("1.2.3", env, StringComparison.Ordinal);
Assert.Contains("Windows 11", env, StringComparison.Ordinal);
Assert.Contains("X64", env, StringComparison.Ordinal);
}
[Fact]
public void WhatHappened_IsTheDescriptionAndTheCrashCode()
{
var text = ReportBugViewModel.BuildWhatHappened(" it broke ", "240101-000000-ABCD");
Assert.StartsWith("it broke", text, StringComparison.Ordinal);
Assert.EndsWith("Error code: 240101-000000-ABCD", text, StringComparison.Ordinal);
Assert.Equal("_Describe what happened._", ReportBugViewModel.BuildWhatHappened(" ", errorCode: null));
}
[Fact]
public void IssueUrl_OpensANewGitLabIssueWithTitleAndDescription()
{
var url = ReportBugViewModel.BuildIssueUrl("[Crash 240101-000000-ABCD] ", "2.3.0", "Microsoft Windows 10.0.26100 (X64)", "spaces and #hash & more", "240101-000000-ABCD");
var fields = Query(url);
Assert.StartsWith("https://gitlab.com/poli0981/CommandForge/-/issues/new?", url, StringComparison.Ordinal);
Assert.Equal(["issue[title]", "issue[description]"], fields.Keys);
Assert.Equal("[Crash 240101-000000-ABCD] ", fields["issue[title]"]);
var body = fields["issue[description]"];
Assert.Contains(ReportBugViewModel.BuildWhatHappened("spaces and #hash & more", "240101-000000-ABCD"), body, StringComparison.Ordinal);
Assert.Contains("\n2.3.0\n", body, StringComparison.Ordinal);
Assert.Contains("\nMicrosoft Windows 10.0.26100 (X64)\n", body, StringComparison.Ordinal);
Assert.Contains("exported .zip", body, StringComparison.Ordinal);
}
[Fact]
public void IssueBody_AnswersTheBugTemplateSectionBySection()
{
var template = File.ReadAllText(Path.Combine(FindRepositoryRoot(), ".gitlab", "issue_templates", ReportBugViewModel.BugReportTemplate + ".md"));
var body = ReportBugViewModel.BuildIssueBody("2.3.0", "Windows", null, null);
// The same headings in the same order, and the same checklist, as the template on GitLab.
Assert.Equal(Heading().Matches(template).Select(match => match.Value.TrimEnd()), Heading().Matches(body).Select(match => match.Value.TrimEnd()));
Assert.Equal(CheckBox().Matches(template).Select(match => match.Value.TrimEnd()), ReportBugViewModel.Confirmations);
Assert.All(ReportBugViewModel.Confirmations, line => Assert.Contains(line, body, StringComparison.Ordinal));
}
[Fact]
public void IssueUrl_KeepsALongDescriptionWithinUrlLimits()
{
var url = ReportBugViewModel.BuildIssueUrl("[Bug] ", "2.3.0", "Windows", new string('x', 20_000), null);
Assert.Contains("truncated", Query(url)["issue[description]"], StringComparison.Ordinal);
Assert.True(url.Length < 16_000, "URL length " + url.Length);
}
[Fact]
public void ReportingACrashOpensTheBugFormForThisAppAndWindows()
{
var shell = new RecordingShell();
var report = new ReportBugViewModel(new NoLogs(), new NoDialogs(), new NoFiles(), shell, errorCode: "240101-000000-ABCD", errorDetails: "it broke");
report.OpenIssueCommand.Execute(null);
var url = Assert.Single(shell.Opened);
var fields = Query(url);
Assert.StartsWith(ProductLinks.NewIssue + "?", url, StringComparison.Ordinal);
Assert.Equal("[Crash 240101-000000-ABCD] ", fields["issue[title]"]);
var body = fields["issue[description]"];
Assert.Contains(ReportBugViewModel.BuildWhatHappened("it broke", "240101-000000-ABCD"), body, StringComparison.Ordinal);
Assert.Contains(RuntimeInformation.OSDescription, body, StringComparison.Ordinal);
var appVersion = report.EnvironmentText.Split('\n')[0].Replace("App version: ", string.Empty, StringComparison.Ordinal).Trim();
Assert.Contains("\n" + appVersion + "\n", body, StringComparison.Ordinal);
}
private static Dictionary Query(string url)
=> new Uri(url).Query.TrimStart('?').Split('&')
.Select(pair => pair.Split('=', 2))
.ToDictionary(pair => Uri.UnescapeDataString(pair[0]), pair => Uri.UnescapeDataString(pair[1]), StringComparer.Ordinal);
private static string FindRepositoryRoot()
{
for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent)
{
if (File.Exists(Path.Combine(directory.FullName, "CommandForge.slnx")))
{
return directory.FullName;
}
}
throw new InvalidOperationException("Could not find the repository root (CommandForge.slnx) above " + AppContext.BaseDirectory);
}
[GeneratedRegex(@"^## .+$", RegexOptions.Multiline | RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 2000)]
private static partial Regex Heading();
[GeneratedRegex(@"^- \[ \] .+$", RegexOptions.Multiline | RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 2000)]
private static partial Regex CheckBox();
private sealed class RecordingShell : IShellService
{
public List Opened { get; } = [];
public bool TryOpen(string target)
{
Opened.Add(target);
return true;
}
public bool TryRestartWindows() => false;
}
private sealed class NoLogs : ILogMaintenance
{
public string LogsDirectoryPath => string.Empty;
public long GetLogsSizeBytes() => 0;
public Task ExportZipAsync(string destinationZipPath, CancellationToken cancellationToken = default) => Task.CompletedTask;
public void DeleteRolledLogFiles()
{
}
}
private sealed class NoDialogs : IDialogService
{
public Task ConfirmAsync(string title, string message, DialogKind kind = DialogKind.Warning) => Task.FromResult(false);
public Task ShowMessageAsync(string title, string message, DialogKind kind = DialogKind.Information) => Task.CompletedTask;
}
private sealed class NoFiles : IFileDialogService
{
public string? PickSaveFile(string title, string filter, string defaultFileName) => null;
public string? PickOpenFile(string title, string filter) => null;
}
}