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
17 changes: 17 additions & 0 deletions docs/affected-test-selection.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,23 @@ builds that contain only the no-handshake fix.
`DOTNET_CLI_TEST_AFFECTED_TESTS_MODE` is an SDK-to-extension authorization marker. Repository scripts and pipeline
definitions must not set it.

## Headless collection compatibility

Collection launches discovery and execution batches in fresh, headless processes. On Windows, a headless process
can inherit a legacy console encoding rather than UTF-8. JSON discovery therefore escapes non-ASCII characters,
including surrogate pairs, so test UIDs and metadata remain lossless after decoding. Escaping only JSON control
characters is insufficient: a legacy encoding's best-fit fallback can convert Unicode into a raw control character
after serialization. The schema and decoded values are unchanged, and malformed discovery still fails collection.
Runner startup diagnostics and process statistics use stderr so they do not surround the JSON document on stdout.

Tests must also work independently of prior test execution and the launch directory. Desktop XML data-source tests
resolve their copied fixture from the application base directory. The AppContainer pipe test loads the framework
access-control and Windows-principal assemblies before impersonation, retaining the real restricted-token connection
and denial checks.

Regression coverage includes `Serialize_NonAsciiCharacters_ProducesLosslessAsciiJson` and the packed, headless
consumer test `ListTestsJson_HeadlessProcess_PreservesUnicode`.

## Storage design

The map uses the extension's Azure DevOps artifact provider:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,6 @@ private void WriteEscapedString(string? value)
case '\t':
_builder.Append("\\t");
break;
case '\u2028':
case '\u2029':
// Valid JSON but invalid in JavaScript string literals (legacy eval() concern);
// System.Text.Json escapes these by default so we mirror that.
AppendUnicodeEscape(c);
break;
default:
if (c < 0x20)
{
Expand All @@ -151,18 +145,24 @@ private void WriteEscapedString(string? value)
{
if (i + 1 < value.Length && char.IsLowSurrogate(value[i + 1]))
{
_builder.Append(c);
_builder.Append(value[++i]);
AppendUnicodeEscape(c);
AppendUnicodeEscape(value[++i]);
}
else
{
_builder.Append('\uFFFD');
AppendUnicodeEscape('\uFFFD');
}
}
else if (char.IsLowSurrogate(c))
{
// Unpaired low surrogate.
_builder.Append('\uFFFD');
AppendUnicodeEscape('\uFFFD');
}
else if (c >= 0x7F)
{
// Headless Windows processes can use a legacy console encoding whose best-fit
// fallback corrupts Unicode or even turns it into unescaped JSON control characters.
AppendUnicodeEscape(c);
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,5 @@ CompositeExtensionFactory<SlowestTestsConsumer> slowestTestCompositeServiceFacto
builder.TestHost.AddTestSessionLifetimeHandler(slowestTestCompositeServiceFactory);
using ITestApplication app = await builder.BuildAsync();
int returnValue = await app.RunAsync();
Console.WriteLine($"Process started: {CommandLine.TotalProcessesAttempt}");
Console.Error.WriteLine($"Process started: {CommandLine.TotalProcessesAttempt}");
return returnValue;
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,28 @@ public class DotnetTestPipeListTestsJsonTests : AcceptanceTestBase<DotnetTestPip

public TestContext TestContext { get; set; } = null!;

[TestMethod]
public async Task ListTestsJson_HeadlessProcess_PreservesUnicode()
{
var testHost = TestInfrastructure.TestHost.LocateFrom(
AssetFixture.TargetAssetPath, AssetName, TargetFrameworks.NetCurrent);

TestHostResult result = await testHost.ExecuteAsync(
"--list-tests json",
cancellationToken: TestContext.CancellationToken);

result.AssertExitCodeIs(ExitCode.Success);
Assert.AreEqual(string.Empty, result.StandardError);

using var document = System.Text.Json.JsonDocument.Parse(result.StandardOutput);
Assert.AreEqual(1, document.RootElement.GetProperty("schemaVersion").GetInt32());
System.Text.Json.JsonElement tests = document.RootElement.GetProperty("tests");
Assert.AreEqual(3, tests.GetArrayLength());
System.Text.Json.JsonElement unicodeTest = tests.EnumerateArray()
.Single(test => test.GetProperty("uid").GetString() == "unicode-\u20DD");
Assert.AreEqual("Unicode \u00C5 \u20DD \uD83D\uDE00", unicodeTest.GetProperty("displayName").GetString());
}

[TestMethod]
public async Task DotnetTestPipe_ListTestsJson_StreamsDiscoveredTestsOverPipeAndKeepsStdoutClean()
{
Expand Down Expand Up @@ -164,6 +186,13 @@ public async Task ExecuteRequestAsync(ExecuteRequestContext context)
new TestMethodIdentifierProperty("MyTestAssembly", "MyNamespace", "MyTestClass", "Test2", 0, [], "System.Void"),
new TestMetadataProperty("Category", "Integration")),
}));
await context.MessageBus.PublishAsync(this, new TestNodeUpdateMessage(context.Request.Session.SessionUid,
new TestNode()
{
Uid = "unicode-\u20DD",
DisplayName = "Unicode \u00C5 \u20DD \uD83D\uDE00",
Properties = new(DiscoveredTestNodeStateProperty.CachedInstance),
}));

context.Complete();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,5 @@ CompositeExtensionFactory<SlowestTestsConsumer> slowestTestCompositeServiceFacto
builder.TestHost.AddTestSessionLifetimeHandler(slowestTestCompositeServiceFactory);
using ITestApplication app = await builder.BuildAsync();
int returnValue = await app.RunAsync();
Console.WriteLine($"Process started: {CommandLine.TotalProcessesAttempt}");
Console.Error.WriteLine($"Process started: {CommandLine.TotalProcessesAttempt}");
return returnValue;
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public void GetDataShouldReadDataFromGivenDataSource()
{
System.Reflection.MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PassingTest");
DataSourceAttribute dataSourceAttribute = new(
"Microsoft.VisualStudio.TestTools.DataSource.XML", "DataTestSourceFile.xml", "settings", DataAccessMethod.Sequential);
"Microsoft.VisualStudio.TestTools.DataSource.XML", Path.Combine(AppContext.BaseDirectory, "DataTestSourceFile.xml"), "settings", DataAccessMethod.Sequential);

_mockTestMethodInfo.Setup(ds => ds.GetAttributes<DataSourceAttribute>())
.Returns([dataSourceAttribute]);
Expand All @@ -41,6 +41,7 @@ public void GetDataShouldReadDataFromGivenDataSource()
TestDataSource testDataSource = new();
IEnumerable<object>? dataRows = testDataSource.GetData(_mockTestMethodInfo.Object, _mockTestContext.Object);

dataRows.Should().HaveCount(4);
foreach (DataRow dataRow in dataRows.Cast<DataRow>())
{
dataRow[3].Should().Be("v1");
Expand All @@ -51,7 +52,7 @@ public void GetDataShouldSetDataConnectionInTestContextObject()
{
System.Reflection.MethodInfo methodInfo = typeof(DummyTestClass).GetMethod("PassingTest");
DataSourceAttribute dataSourceAttribute = new(
"Microsoft.VisualStudio.TestTools.DataSource.XML", "DataTestSourceFile.xml", "settings", DataAccessMethod.Sequential);
"Microsoft.VisualStudio.TestTools.DataSource.XML", Path.Combine(AppContext.BaseDirectory, "DataTestSourceFile.xml"), "settings", DataAccessMethod.Sequential);

_mockTestMethodInfo.Setup(ds => ds.GetAttributes<DataSourceAttribute>())
.Returns([dataSourceAttribute]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
[assembly: Parallelize(Scope = ExecutionScope.MethodLevel, Workers = 0)]

#if NETCOREAPP
Console.WriteLine("Dynamic code supported: " + System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported);
Console.Error.WriteLine("Dynamic code supported: " + System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported);
#endif

ITestApplicationBuilder builder = await TestApplication.CreateBuilderAsync(args);
Expand All @@ -35,9 +35,9 @@
builder.AddOpenTelemetryProvider(
tracing => tracing.AddTestingPlatformInstrumentation(),
metrics => metrics.AddTestingPlatformInstrumentation());
Console.WriteLine("NATIVE_AOT disabled");
Console.Error.WriteLine("NATIVE_AOT disabled");
#else
Console.WriteLine("NATIVE_AOT enabled");
Console.Error.WriteLine("NATIVE_AOT enabled");
#endif

builder.AddCrashDumpProvider(ignoreIfNotSupported: true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -938,6 +938,12 @@ public static bool TryOpenPipeAs(SafeHandle impersonationToken, string pipeName,
[SupportedOSPlatform("windows")]
public static bool TryConnectManagedClientAs(SafeHandle impersonationToken, string pipeName)
{
#if NET
// CurrentUserOnly loads these assemblies lazily; the AppContainer token cannot read the
// desktop runtime installation when collection runs this test in a fresh process.
_ = typeof(System.Security.AccessControl.GenericSecurityDescriptor).Assembly;
_ = typeof(System.Security.Principal.WindowsIdentity).Assembly;
#endif
if (!ImpersonateLoggedOnUser(impersonationToken))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,38 @@ public void Serialize_DisplayNameWithSpecialCharacters_EscapesProperly()
document.RootElement.GetProperty("tests")[0].GetProperty("displayName").GetString());
}

[TestMethod]
public void Serialize_NonAsciiCharacters_ProducesLosslessAsciiJson()
{
var node = new TestNode
{
Uid = new TestNodeUid("uid-\u20DD"),
DisplayName = "Unicode \u00C5 \u20DD \uD83D\uDE00",
};

string json = DiscoveredTestsJsonSerializer.Serialize([node]);

Assert.AreEqual(
"""

{
"schemaVersion": 1,
"tests": [
{
"uid": "uid-\u20dd",
"displayName": "Unicode \u00c5 \u20dd \ud83d\ude00"
}
]
}
""".Replace("\r", string.Empty),
json.Replace("\r", string.Empty));

using var document = JsonDocument.Parse(json);
JsonElement test = document.RootElement.GetProperty("tests")[0];
Assert.AreEqual(node.Uid.Value, test.GetProperty("uid").GetString());
Assert.AreEqual(node.DisplayName, test.GetProperty("displayName").GetString());
}

[TestMethod]
public void Serialize_DisplayNameWithLoneSurrogate_ReplacesWithReplacementCharacter()
{
Expand Down
Loading