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 @@ -41,6 +41,7 @@ internal sealed partial class DotnetMuxerLocator
}

byte[] cpuInfoBytes = ReadFourBytes(headerReader);
// Stryker disable once all: Each byte order maps to paired Magic/Cigam CPU values for the same architecture.
uint cpuInfo = magic is MachOMagic32LittleEndian or MachOMagic64LittleEndian
? BinaryPrimitives.ReadUInt32LittleEndian(cpuInfoBytes)
: BinaryPrimitives.ReadUInt32BigEndian(cpuInfoBytes);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ internal sealed partial class DotnetMuxerLocator
uint peHeader = reader.ReadUInt32();

// Check if the offset is invalid
if (peHeader > fs.Length - 5)
if (peHeader > fs.Length - sizeof(uint))
{
resolutionLog("[GetMuxerArchitectureByPEHeaderOnWin]Invalid offset");
return ThrowInvalidImage();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ internal sealed partial class DotnetMuxerLocator

internal DotnetMuxerLocator(Action<string> resolutionLog)
{
// Stryker disable once Conditional: Forcing the branch that matches the current operating system is equivalent.
_muxerName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet";
using var currentProcess = Process.GetCurrentProcess();
_currentProcessFileName = currentProcess.MainModule!.FileName!;
Expand All @@ -40,6 +41,7 @@ private static PlatformArchitecture GetOSArchitecture()
_ => throw new NotSupportedException(),
};

// Stryker disable once Conditional: Forcing the branch that matches the current operating system is equivalent.
private static PlatformOperatingSystem GetOperatingSystem() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? PlatformOperatingSystem.Windows
: RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? PlatformOperatingSystem.OSX : PlatformOperatingSystem.Unix;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,8 @@ internal void AddAppHostDotnetRootEnvironmentVariable(
if (hasExplicitDotnetRoot || hasExplicitWindowsX86DotnetRoot)
{
EnvironmentVariables = hasExplicitDotnetRoot && isWindowsX86 && !hasExplicitWindowsX86DotnetRoot
? [$"{variableName}=", "DOTNET_ROOT(x86)=", .. EnvironmentVariables ?? []]
: [$"{variableName}=", .. EnvironmentVariables ?? []];
? [$"{variableName}=", "DOTNET_ROOT(x86)=", .. EnvironmentVariables!]
: [$"{variableName}=", .. EnvironmentVariables!];
return;
}

Expand All @@ -199,6 +199,7 @@ private bool ContainsEnvironmentVariable(string variableName, bool isWindows)
foreach (string environmentVariable in EnvironmentVariables)
{
int separatorIndex = environmentVariable.IndexOf('=');
// Stryker disable once Equality: At index zero the extracted name is empty and cannot equal the non-empty requested variable name.
if (separatorIndex > 0
&& string.Equals(environmentVariable.Substring(0, separatorIndex), variableName, comparison))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ namespace Microsoft.Testing.Platform.MSBuild;
public partial class InvokeTestingPlatformTask : Build.Utilities.ToolTask, IDisposable
{
private const string MonoRunnerName = "mono";
// Stryker disable once all: The inactive platform branch and its literal are unobservable on the current operating system.
private static readonly string DotnetRunnerName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet";

private readonly IFileSystem _fileSystem;
Expand Down Expand Up @@ -46,6 +47,7 @@ public partial class InvokeTestingPlatformTask : Build.Utilities.ToolTask, IDisp
public InvokeTestingPlatformTask()
: this(new FileSystem())
{
// Stryker disable once String: The opt-in debugger hook cannot be exercised safely by an automated unit test.
if (Environment.GetEnvironmentVariable("TESTINGPLATFORM_MSBUILD_LAUNCH_ATTACH_DEBUGGER") == "1")
{
Debugger.Launch();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ private static bool TryGetStackFrameLocation(string stackFrame, out int line, [N
if (hasLocation)
{
// get the exact info from stack frame.
Group code = match.Groups["code"];
Group codeWithoutLocation = match.Groups["code1"];
place = code.Success ? code.Value : codeWithoutLocation.Value;
place = match.Groups["code"].Value;

file = match.Groups["file"].Value;
_ = int.TryParse(match.Groups["line"].Value, out line);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public TestingPlatformSelfRegisteredExtensions()

internal TestingPlatformSelfRegisteredExtensions(IFileSystem fileSystem)
{
// Stryker disable once String: The opt-in debugger hook cannot be exercised safely by an automated unit test.
if (Environment.GetEnvironmentVariable("TESTINGPLATFORM_MSBUILD_LAUNCH_ATTACH_DEBUGGER") == "1")
{
Debugger.Launch();
Expand Down Expand Up @@ -148,6 +149,7 @@ private ITaskItem[] ValidateAndDeduplicateBuilderHooks()

foreach (IGrouping<string, ITaskItem> group in SelfRegisteredExtensionsBuilderHook.GroupBy(x => x.ItemSpec))
{
// Stryker disable once Linq: GroupBy never produces an empty grouping, so First and FirstOrDefault are equivalent here.
ITaskItem firstItem = group.First();
foreach (ITaskItem duplicateItem in group.Skip(1))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public TestingPlatformEntryPointTask()

internal TestingPlatformEntryPointTask(IFileSystem fileSystem)
{
// Stryker disable once String: The opt-in debugger hook cannot be exercised safely by an automated unit test.
if (Environment.GetEnvironmentVariable("TESTINGPLATFORM_MSBUILD_LAUNCH_ATTACH_DEBUGGER") == "1")
{
Debugger.Launch();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public static bool IsIdentifierStartCharacter(char ch)
return true;
}

// Stryker disable once Equality: U+007F is a control character and the Unicode-category path also rejects it.
if (ch <= '\u007F') // max ASCII
{
return false;
Expand Down Expand Up @@ -68,6 +69,7 @@ public static bool IsIdentifierPartCharacter(char ch)
return true;
}

// Stryker disable once Equality: U+007F is a control character and the Unicode-category path also rejects it.
if (ch <= '\u007F') // max ASCII
{
return false;
Expand Down
5 changes: 5 additions & 0 deletions src/Platform/SharedExtensionHelpers/StackTraceRegexHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ internal static string CreateFrameRegexPattern(bool matchFramesWithoutLocation)

private static (string AtString, string InPattern) GetLocalizedStackFrameRegexParts()
{
// Stryker disable once String: A failed resource lookup intentionally falls back to the same invariant text.
string atResourceName = "Word_At";
// Stryker disable once String: A failed resource lookup intentionally falls back to the same invariant pattern.
string inResourceName = "StackTrace_InFileLineNumber";

string? atString = null;
Expand All @@ -41,6 +43,7 @@ private static (string AtString, string InPattern) GetLocalizedStackFrameRegexPa
{
// Get these resources: https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/Resources/Strings.resx
#pragma warning disable RS0030 // Do not use banned APIs
// Stryker disable once all: If the private runtime API cannot be found, the fallback below produces the same pattern.
MethodInfo? getResourceStringMethod = typeof(Environment).GetMethod(
"GetResourceString",
BindingFlags.Static | BindingFlags.NonPublic, null, [typeof(string)], null);
Expand All @@ -64,7 +67,9 @@ or InvalidOperationException
// If reflection lookup/invocation fails, populate the defaults below.
}

// Stryker disable once Conditional: The current runtime returns the invariant fallback value for this private resource lookup.
atString = atString is null || atString == atResourceName ? "at" : atString;
// Stryker disable once Conditional: The current runtime returns the invariant fallback value for this private resource lookup.
inString = inString is null || inString == inResourceName ? "in {0}:line {1}" : inString;

string inPattern = string.Format(CultureInfo.InvariantCulture, inString, "(?<file>.+)", @"(?<line>\d+)");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,46 @@ public void GetMuxerArchitectureByPEHeaderOnWin_ThrowsForInvalidOffset()
Assert.Contains("[GetMuxerArchitectureByPEHeaderOnWin]Invalid offset", logs);
}

[TestMethod]
[DataRow(64, 61u)]
[DataRow(100, 97u)]
public void GetMuxerArchitectureByPEHeaderOnWin_RejectsOffsetJustPastLastReadableSignature(int fileLength, uint offset)
{
byte[] bytes = new byte[fileLength];
BitConverter.GetBytes(offset).CopyTo(bytes, 0x3C);
using TemporaryFile file = new(bytes);
List<string> logs = [];

Assert.ThrowsExactly<InvalidOperationException>(() => InvokePEHeaderParser(file.Path, logs.Add));
Assert.Contains("[GetMuxerArchitectureByPEHeaderOnWin]Invalid offset", logs);
}

[TestMethod]
public void GetMuxerArchitectureByPEHeaderOnWin_OffsetAtLastReadableSignature_IsNotClassifiedAsInvalidOffset()
{
byte[] bytes = new byte[100];
BitConverter.GetBytes(96u).CopyTo(bytes, 0x3C);
BitConverter.GetBytes(0x00004550u).CopyTo(bytes, 96);
using TemporaryFile file = new(bytes);
List<string> logs = [];

Assert.ThrowsExactly<EndOfStreamException>(() => InvokePEHeaderParser(file.Path, logs.Add));
Assert.DoesNotContain("[GetMuxerArchitectureByPEHeaderOnWin]Invalid offset", logs);
}

[TestMethod]
public void GetMuxerArchitectureByPEHeaderOnWin_OffsetAtLastReadableSignatureInMinimalHeader_IsNotClassifiedAsInvalidOffset()
{
byte[] bytes = new byte[64];
BitConverter.GetBytes(60u).CopyTo(bytes, 0x3C);
using TemporaryFile file = new(bytes);
List<string> logs = [];

Assert.ThrowsExactly<InvalidOperationException>(() => InvokePEHeaderParser(file.Path, logs.Add));
Assert.DoesNotContain("[GetMuxerArchitectureByPEHeaderOnWin]Invalid offset", logs);
Assert.Contains("[GetMuxerArchitectureByPEHeaderOnWin]Missing PE signature", logs);
}

[TestMethod]
public void GetMuxerArchitectureByPEHeaderOnWin_ThrowsForMissingPESignature()
{
Expand Down Expand Up @@ -161,6 +201,19 @@ public void GetOperatingSystem_MatchesRuntimeInformation()
Assert.AreEqual(expected, InvokeStaticMethod<object>("GetOperatingSystem").ToString());
}

[TestMethod]
public void Constructor_UsesPlatformSpecificMuxerName()
{
DotnetMuxerLocator locator = new(_ => { });
string muxerName = (string)typeof(DotnetMuxerLocator)
.GetField("_muxerName", BindingFlags.Instance | BindingFlags.NonPublic)!
.GetValue(locator)!;

Assert.AreEqual(
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet",
muxerName);
}

[TestMethod]
public void IsValidArchitectureMuxer_LogsCompatibleArchitecture()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ public void LogEventsFromTextOutput_AzureDevOpsCommands_AreWrittenToStdoutAtColu
// Regular output keeps flowing through the MSBuild logger and does not leak to stdout.
Assert.Contains("normal output line", loggedMessages);
Assert.DoesNotContain("normal output line", capturedStdout.ToString());
Assert.AreEqual(
"##[group]Tests: MyAssembly (net9.0)"
+ Environment.NewLine
+ "##[endgroup]"
+ Environment.NewLine
+ "normal output line"
+ Environment.NewLine,
task.GetCapturedOutput());
}

[TestMethod]
Expand All @@ -83,6 +91,57 @@ public void AddAppHostDotnetRootEnvironmentVariable_AddsArchitectureSpecificVari
Assert.AreEqual("CUSTOM_VARIABLE=value", task.EnvironmentVariables[1]);
}

[TestMethod]
public void AddAppHostDotnetRootEnvironmentVariable_WithNoUserVariables_AddsOnlyResolvedVariableAndLogsIt()
{
using AppHostTaskFixture fixture = new();
List<BuildMessageEventArgs> messages = [];
Mock<IBuildEngine> buildEngine = new();
buildEngine
.Setup(engine => engine.LogMessageEvent(It.IsAny<BuildMessageEventArgs>()))
.Callback<BuildMessageEventArgs>(messages.Add);
TestableInvokeTestingPlatformTask task = fixture.CreateTask();
task.BuildEngine = buildEngine.Object;

task.InvokeAddAppHostDotnetRootEnvironmentVariable();

Assert.IsNotNull(task.EnvironmentVariables);
Assert.AreSequenceEqual(
[$"{GetDotnetRootArchitectureVariableName()}={fixture.DotnetRoot}"],
task.EnvironmentVariables);
Assert.Contains(
message => message.Importance == MessageImportance.Low
&& message.Message == $"Setting '{GetDotnetRootArchitectureVariableName()}' to '{fixture.DotnetRoot}' for apphost runtime resolution.",
messages);
}

[TestMethod]
public void AddAppHostDotnetRootEnvironmentVariable_UsesRequestedEnvironmentVariableComparison()
{
using AppHostTaskFixture fixture = new();
string variableName = GetDotnetRootArchitectureVariableName();

TestableInvokeTestingPlatformTask windowsTask = fixture.CreateTask();
windowsTask.EnvironmentVariables = [$"{variableName.ToLowerInvariant()}=explicit"];
windowsTask.InvokeAddAppHostDotnetRootEnvironmentVariable(
RuntimeInformation.ProcessArchitecture,
isWindows: true,
Environment.Is64BitOperatingSystem);
Assert.AreSequenceEqual(
[$"{variableName.ToLowerInvariant()}=explicit"],
windowsTask.EnvironmentVariables!);

TestableInvokeTestingPlatformTask unixTask = fixture.CreateTask();
unixTask.EnvironmentVariables = [$"{variableName.ToLowerInvariant()}=explicit"];
unixTask.InvokeAddAppHostDotnetRootEnvironmentVariable(
RuntimeInformation.ProcessArchitecture,
isWindows: false,
Environment.Is64BitOperatingSystem);
Assert.AreSequenceEqual(
[$"{variableName}={fixture.DotnetRoot}", $"{variableName.ToLowerInvariant()}=explicit"],
unixTask.EnvironmentVariables!);
}

[TestMethod]
public void AddAppHostDotnetRootEnvironmentVariable_DoesNotOverrideExplicitDotnetRoot()
{
Expand Down Expand Up @@ -199,6 +258,26 @@ public void IsWindowsX86ProcessOn64BitOperatingSystem_ReturnsExpectedResult(
isWindows,
is64BitOperatingSystem));

[TestMethod]
public void Constructor_UsesPlatformSpecificPipeName()
{
TestableInvokeTestingPlatformTask task = new();
string pipeName = task.GetPipeName();
const string Prefix = "testingplatform.pipe.";

if (Path.DirectorySeparatorChar == '/')
{
Assert.IsTrue(Path.IsPathRooted(pipeName));
Assert.IsTrue(Guid.TryParseExact(Path.GetFileName(pipeName), "N", out _));
}
else
{
Assert.StartsWith(Prefix, pipeName);
Assert.DoesNotContain(Path.DirectorySeparatorChar.ToString(), pipeName);
Assert.IsTrue(Guid.TryParseExact(pipeName[Prefix.Length..], "N", out _));
}
}

private static string GetDotnetRootArchitectureVariableName()
=> $"DOTNET_ROOT_{RuntimeInformation.ProcessArchitecture.ToString().ToUpperInvariant()}";

Expand Down Expand Up @@ -231,6 +310,19 @@ public void InvokeAddAppHostDotnetRootEnvironmentVariable(
bool isWindows,
bool is64BitOperatingSystem)
=> AddAppHostDotnetRootEnvironmentVariable(currentProcessArchitecture, isWindows, is64BitOperatingSystem);

public string GetCapturedOutput()
=> ((StringBuilder)typeof(InvokeTestingPlatformTask)
.GetField("_output", BindingFlags.Instance | BindingFlags.NonPublic)!
.GetValue(this)!).ToString();

public string GetPipeName()
{
object description = typeof(InvokeTestingPlatformTask)
.GetField("_pipeNameDescription", BindingFlags.Instance | BindingFlags.NonPublic)!
.GetValue(this)!;
return (string)description.GetType().GetProperty("Name")!.GetValue(description)!;
}
}

private sealed class AppHostTaskFixture : IDisposable
Expand Down
Loading
Loading