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
69 changes: 69 additions & 0 deletions src/TestFramework/TestFramework/Assertions/Assert.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,75 @@ static bool ShouldLaunchDebugger()
private static AssertFailedException CreateAssertFailedException(string assertionName, string? message)
=> new(FormatAssertionFailed(assertionName, message));

private static AssertFailedException CreateAssertFailedException(StructuredAssertionMessage structuredMessage)
{
AssertFailedException exception = new(structuredMessage.Format())
{
ExpectedText = structuredMessage.ExpectedText,
ActualText = structuredMessage.ActualText,
};
Comment thread
Evangelink marked this conversation as resolved.

if (structuredMessage.ExpectedText is not null)
{
exception.Data["assert.expected"] = structuredMessage.ExpectedText;
}

if (structuredMessage.ActualText is not null)
{
exception.Data["assert.actual"] = structuredMessage.ActualText;
}

return exception;
Comment thread
Evangelink marked this conversation as resolved.
}

/// <summary>
/// Reports an assertion failure using a structured message. Within an <see cref="AssertScope"/>,
/// the failure is collected and execution continues. Outside a scope, the failure is thrown immediately.
/// </summary>
/// <param name="structuredMessage">
/// The structured assertion failure message.
/// </param>
#pragma warning disable CS8763 // A method marked [DoesNotReturn] should not return - Deliberately keeping [DoesNotReturn] annotation while using soft assertions. Within an AssertScope, the postcondition is not enforced (same as all other assertion postconditions in scoped mode).
[DoesNotReturn]
[StackTraceHidden]
internal static void ReportAssertFailed(StructuredAssertionMessage structuredMessage)
{
LaunchDebuggerIfNeeded();
AssertFailedException assertionFailedException = CreateAssertFailedException(structuredMessage);
if (AssertScope.Current is { } scope)
{
try
{
throw assertionFailedException;
}
catch (AssertFailedException ex)
{
assertionFailedException = ex;
}

scope.AddError(assertionFailedException);
return;
}

throw assertionFailedException;
}
#pragma warning restore CS8763 // A method marked [DoesNotReturn] should not return

/// <summary>
/// Reports an assertion failure using a structured message and always throws,
/// even within an <see cref="AssertScope"/>.
/// </summary>
/// <param name="structuredMessage">
/// The structured assertion failure message.
/// </param>
[DoesNotReturn]
[StackTraceHidden]
internal static void ThrowAssertFailed(StructuredAssertionMessage structuredMessage)
{
LaunchDebuggerIfNeeded();
throw CreateAssertFailedException(structuredMessage);
}

private static string FormatAssertionFailed(string assertionName, string? message)
{
string failedMessage = string.Format(CultureInfo.CurrentCulture, FrameworkMessages.AssertionFailed, assertionName);
Expand Down
109 changes: 109 additions & 0 deletions src/TestFramework/TestFramework/Assertions/AssertionValueRenderer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.VisualStudio.TestTools.UnitTesting;

/// <summary>
/// Renders values for display in structured assertion messages following the RFC 012 value rendering rules.
/// </summary>
internal static class AssertionValueRenderer
{
/// <summary>
/// Renders a value as a string suitable for display in the evidence block.
/// </summary>
internal static string RenderValue(object? value)
=> value switch
{
null => "null",
string s => RenderString(s),
bool b => b ? "true" : "false",
char c => RenderChar(c),
IEnumerable enumerable => RenderCollection(enumerable),
_ => value.ToString() ?? value.GetType().FullName ?? value.GetType().Name,
};

/// <summary>
/// Renders a string value with double quotes and escape sequences for control characters.
/// </summary>
private static string RenderString(string value)
{
StringBuilder sb = new(value.Length + 2);
sb.Append('"');
foreach (char c in value)
{
switch (c)
{
case '"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
case '\0':
sb.Append("\\0");
break;
default:
if (char.IsControl(c))
{
sb.Append("\\u");
sb.Append(((int)c).ToString("X4", CultureInfo.InvariantCulture));
}
else
{
sb.Append(c);
}

break;
}
}

sb.Append('"');
return sb.ToString();
}

/// <summary>
/// Renders a char value with single quotes and escape sequences.
/// </summary>
private static string RenderChar(char value) =>
value switch
{
'\n' => "'\\n'",
'\r' => "'\\r'",
'\t' => "'\\t'",
'\0' => "'\\0'",
_ when char.IsControl(value) => $"'\\u{(int)value:X4}'",
_ => $"'{value}'",
};

/// <summary>
/// Renders a collection in JSON-style array notation.
/// </summary>
private static string RenderCollection(IEnumerable enumerable)
{
StringBuilder sb = new();
sb.Append('[');
bool first = true;
foreach (object? item in enumerable)
{
if (!first)
{
sb.Append(", ");
}

sb.Append(RenderValue(item));
first = false;
}

sb.Append(']');
return sb.ToString();
}
}
62 changes: 62 additions & 0 deletions src/TestFramework/TestFramework/Assertions/EvidenceBlock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.VisualStudio.TestTools.UnitTesting;

/// <summary>
/// Represents the evidence block of a structured assertion message, containing labeled value lines
/// such as expected/actual values and assertion-specific details.
/// </summary>
internal sealed class EvidenceBlock
{
private readonly List<EvidenceLine> _lines = [];

internal static EvidenceBlock Create() => new();

internal IReadOnlyList<EvidenceLine> Lines => _lines;

internal EvidenceBlock AddLine(string label, string value)
{
_lines.Add(new EvidenceLine(label, value));
return this;
}

/// <summary>
/// Formats the evidence block as aligned label: value lines.
/// Labels are right-padded so all values start at the same column.
/// </summary>
internal string Format()
{
if (_lines.Count == 0)
{
return string.Empty;
}

int maxLabelLength = 0;
foreach (EvidenceLine line in _lines)
{
if (line.Label.Length > maxLabelLength)
{
maxLabelLength = line.Label.Length;
}
}

StringBuilder sb = new();
for (int i = 0; i < _lines.Count; i++)
{
if (i > 0)
{
sb.Append(Environment.NewLine);
}

EvidenceLine line = _lines[i];

// Pad label (which includes trailing colon) to align values, then append a space and value
sb.Append(line.Label.PadRight(maxLabelLength));
sb.Append(' ');
sb.Append(line.Value);
}

return sb.ToString();
}
}
9 changes: 9 additions & 0 deletions src/TestFramework/TestFramework/Assertions/EvidenceLine.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.VisualStudio.TestTools.UnitTesting;

/// <summary>
/// Represents a single labeled line in the evidence block of a structured assertion message.
/// </summary>
internal readonly record struct EvidenceLine(string Label, string Value);
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.VisualStudio.TestTools.UnitTesting;

/// <summary>
/// Builds a structured assertion failure message following the format:
/// <code>
/// Assertion failed. &lt;summary&gt;
/// &lt;user message&gt;
///
/// &lt;evidence block&gt;
///
/// &lt;call-site expression&gt;
/// </code>
/// </summary>
internal sealed class StructuredAssertionMessage
{
private const string AssertionPrefix = "Assertion failed.";

private readonly string _summary;
private readonly List<string> _additionalSummaryLines = [];
private readonly List<EvidenceBlock> _evidenceBlocks = [];
private string? _userMessage;
private string? _callSiteExpression;

internal StructuredAssertionMessage(string summary)
{
_summary = summary;
}

internal string? ExpectedText { get; private set; }

internal string? ActualText { get; private set; }

internal StructuredAssertionMessage WithAdditionalSummaryLine(string line)
{
_additionalSummaryLines.Add(line);
return this;
}

internal StructuredAssertionMessage WithUserMessage(string? userMessage)
{
if (!string.IsNullOrWhiteSpace(userMessage))
{
_userMessage = userMessage;
}

return this;
}

internal StructuredAssertionMessage WithEvidence(EvidenceBlock evidenceBlock)
{
_evidenceBlocks.Add(evidenceBlock);
return this;
}
Comment thread
Evangelink marked this conversation as resolved.

internal StructuredAssertionMessage WithExpectedAndActual(string? expectedText, string? actualText)
{
ExpectedText = expectedText;
ActualText = actualText;
return this;
}

internal StructuredAssertionMessage WithCallSiteExpression(string? callSiteExpression)
{
if (!string.IsNullOrWhiteSpace(callSiteExpression))
{
_callSiteExpression = callSiteExpression;
}

return this;
}

/// <summary>
/// Formats the structured message as a multi-line string following the RFC 012 layout.
/// </summary>
internal string Format()
{
StringBuilder sb = new();

// Line 1: Assertion prefix + summary
sb.Append(AssertionPrefix);
if (!string.IsNullOrEmpty(_summary))
{
sb.Append(' ');
sb.Append(_summary);
}

// Additional summary lines
foreach (string additionalLine in _additionalSummaryLines)
{
sb.Append(Environment.NewLine);
sb.Append(additionalLine);
}

// User message (on its own line, no label)
if (_userMessage is not null)
{
sb.Append(Environment.NewLine);
sb.Append(_userMessage);
}

// Evidence blocks (each separated by blank line)
foreach (EvidenceBlock evidence in _evidenceBlocks)
{
string formattedEvidence = evidence.Format();
if (!string.IsNullOrEmpty(formattedEvidence))
{
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(formattedEvidence);
}
}

// Call-site expression (separated by blank line)
if (_callSiteExpression is not null)
{
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Append(_callSiteExpression);
}

return sb.ToString();
}

/// <inheritdoc/>
public override string ToString() => Format();
}
Loading