Skip to content
Closed
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 @@ -81,7 +81,7 @@ public async Task CSharp_NetCore_SingleTestProject()

var report = await strykerRunOutput.DeserializeJsonReportAsync();

CheckReportMutants(report, total: 656, ignored: 271, survived: 4, killed: 9, timeout: 2, nocoverage: 340);
CheckReportMutants(report, total: 656, ignored: 271, survived: 4, killed: 9, timeout: 2, nocoverage: 342);
CheckReportTestCounts(report, total: 11);
}

Expand All @@ -101,7 +101,7 @@ public async Task CSharp_NetCore_WithTwoTestProjects()

var report = await strykerRunOutput.DeserializeJsonReportAsync();

CheckReportMutants(report, total: 656, ignored: 117, survived: 5, killed: 11, timeout: 2, nocoverage: 491);
CheckReportMutants(report, total: 656, ignored: 117, survived: 5, killed: 11, timeout: 2, nocoverage: 493);
CheckReportTestCounts(report, total: 21);
}

Expand All @@ -121,7 +121,7 @@ public async Task CSharp_NetCore_MSTestMTP()

var report = await strykerRunOutput.DeserializeJsonReportAsync();

CheckReportMutants(report, total: 663, ignored: 272, survived: 1, killed: 1, timeout: 0, nocoverage: 359);
CheckReportMutants(report, total: 663, ignored: 272, survived: 1, killed: 1, timeout: 0, nocoverage: 361);
CheckReportTestCounts(report, total: 2);
}

Expand All @@ -143,7 +143,7 @@ public async Task CSharp_NetCore_XUnitMTP()

// Only the project under test is mutated here, so this run holds a single mutated assembly. The
// extra test covers ExtraProject, which the solution run mutates as well; see MTPSolution.
CheckReportMutants(report, total: 656, ignored: 271, survived: 1, killed: 1, timeout: 0, nocoverage: 353);
CheckReportMutants(report, total: 656, ignored: 271, survived: 1, killed: 1, timeout: 0, nocoverage: 355);
CheckReportTestCounts(report, total: 3);
}

Expand All @@ -163,7 +163,7 @@ public async Task CSharp_NetCore_NUnitMTP()

var report = await strykerRunOutput.DeserializeJsonReportAsync();

CheckReportMutants(report, total: 656, ignored: 271, survived: 1, killed: 1, timeout: 0, nocoverage: 353);
CheckReportMutants(report, total: 656, ignored: 271, survived: 1, killed: 1, timeout: 0, nocoverage: 355);
CheckReportTestCounts(report, total: 2);
}

Expand All @@ -183,7 +183,7 @@ public async Task CSharp_NetCore_TUnit()

var report = await strykerRunOutput.DeserializeJsonReportAsync();

CheckReportMutants(report, total: 656, ignored: 271, survived: 1, killed: 1, timeout: 0, nocoverage: 353);
CheckReportMutants(report, total: 656, ignored: 271, survived: 1, killed: 1, timeout: 0, nocoverage: 355);
CheckReportTestCounts(report, total: 2);
}

Expand All @@ -210,7 +210,7 @@ public async Task CSharp_NetCore_MTPSolution()
// Teacher.cs and Lesson.cs are reached from one test that spans both of their assemblies, so
// losing either one's coverage names the assembly at fault instead of moving a global count by one.
CheckEveryMutatedProjectIsCovered(report, "KilledMutants.cs", "Teacher.cs", "Lesson.cs");
CheckReportMutants(report, total:669, ignored: 275, survived: 2, killed: 3, timeout: 2, nocoverage: 357);
CheckReportMutants(report, total:669, ignored: 275, survived: 2, killed: 3, timeout: 2, nocoverage: 359);
CheckReportTestCounts(report, total: 11);
}

Expand Down Expand Up @@ -250,7 +250,7 @@ public async Task CSharp_NetCore_SolutionRun()

var report = await strykerRunOutput.DeserializeJsonReportAsync();

CheckReportMutants(report, total: 656, ignored: 271, survived: 4, killed: 9, timeout: 2, nocoverage: 340);
CheckReportMutants(report, total: 656, ignored: 271, survived: 4, killed: 9, timeout: 2, nocoverage: 342);
CheckReportTestCounts(report, total: 23);
}

Expand Down
74 changes: 73 additions & 1 deletion src/Stryker.Core/Stryker.Core.UnitTest/MutantAndCompileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
namespace Stryker.Core.UnitTest;

[TestClass]
public class MutantAndCompileTests
public class MutantAndCompileTests : TestBase
{
private readonly CodeInjection _injector = new();

Expand Down Expand Up @@ -84,4 +84,76 @@ public static int Get(string key)

rollbackedResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty();
}

[TestMethod]
public void InterpolatedStringHandlerMutationsShouldCompileWithoutErrors()
{
const string source = """
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;

namespace Lib;

public static class HandlerExamples
{
public static string Describe(IReadOnlyList<int> items) =>
string.Create(CultureInfo.InvariantCulture, $"First is {items[0]}");

public static string DescribeSum(int a, int b) =>
string.Create(CultureInfo.InvariantCulture, $"Sum is {a + b}");

public static void AppendLine(StringBuilder sb, int x)
{
sb.AppendLine($"Value is {x}");
}

public static void Log(int x) => Write($"Value is {x}");

private static void Write(ref DefaultInterpolatedStringHandler handler) => _ = handler.ToStringAndClear();

public static string Invariant(int x) => FormattableString.Invariant($"Value is {x}");

public static string FormatLocal(int x)
{
FormattableString f = $"Value is {x}";
return FormattableString.Invariant(f);
}
}
""";

var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp14);
var syntaxTree = CSharpSyntaxTree.ParseText(source, parseOptions);
Type[] typeToLoad = [typeof(object), typeof(List<>), typeof(Enumerable), typeof(Nullable<>), typeof(MemoryMappedFile),
typeof(MemoryMappedViewAccessor)];
var syntaxTrees = new List<SyntaxTree> { syntaxTree };
syntaxTrees.AddRange(_injector.GetHelpersSyntaxTreesToInject(parseOptions));
var mutator = new CsharpMutantOrchestrator(new MutantPlacer(_injector), options: new StrykerOptions
{
MutationLevel = MutationLevel.Complete,
});

List<MetadataReference> metadataReferences = [.. typeToLoad.Select(t => t.Assembly.Location).Distinct().
Select(l => MetadataReference.CreateFromFile(l))];
Assembly.GetAssembly(typeof(MemoryMappedViewAccessor)).GetReferencedAssemblies().Select(Assembly.Load).Select(a => a.Location).
Distinct().Select(l => MetadataReference.CreateFromFile(l)).ToList().ForEach(metadataReferences.Add);
var compilation = CSharpCompilation.Create("TestCompilation",
syntaxTrees: syntaxTrees,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithNullableContextOptions(NullableContextOptions.Enable),
references: metadataReferences
);

var mutatedTree = mutator.Mutate(syntaxTree, compilation.GetSemanticModel(syntaxTree));
compilation = compilation.ReplaceSyntaxTree(syntaxTree, mutatedTree);

using var ms = new MemoryStream();
var compileResult = compilation.Emit(ms);

compileResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ShouldBeEmpty();
compileResult.Success.ShouldBeTrue();
mutator.Mutants.Where(m => m.Mutation.Type == Mutator.String).Count().ShouldBe(6);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2018,5 +2018,149 @@ public void ShouldProtectDirectives()
ShouldMutateSourceInClassToExpected(source, expected);
}

[TestMethod]
public void ShouldMutateInterpolatedStringHandlerInStringCreate()
{
var source = """
public static string Describe(IReadOnlyList<int> items) =>
string.Create(System.Globalization.CultureInfo.InvariantCulture, $"First is {items[0]}");
""";

var expected = """
public static string Describe(IReadOnlyList<int> items) =>
(StrykerNamespace.MutantControl.IsActive(0) ? string.Create(System.Globalization.CultureInfo.InvariantCulture, $"") : string.Create(System.Globalization.CultureInfo.InvariantCulture, $"First is {items[0]}"));
""";

ShouldMutateSourceInClassToExpected(source, expected);
}

[TestMethod]
public void ShouldMutateInterpolatedStringHandlerWithInnerMutation()
{
var source = """
public static string Describe(int a, int b) =>
string.Create(System.Globalization.CultureInfo.InvariantCulture, $"Sum is {a + b}");
""";

var expected = """
public static string Describe(int a, int b) =>
(StrykerNamespace.MutantControl.IsActive(0) ? string.Create(System.Globalization.CultureInfo.InvariantCulture, $"") : string.Create(System.Globalization.CultureInfo.InvariantCulture, $"Sum is {(StrykerNamespace.MutantControl.IsActive(1) ? a - b : a + b)}"));
""";

ShouldMutateSourceInClassToExpected(source, expected);
}

[TestMethod]
public void ShouldMutateInterpolatedStringHandlerInExpressionStatement()
{
var source = """
public void AppendValue(StringBuilder sb, int x)
{
sb.AppendLine($"Value is {x}");
}
""";

var expected = """
public void AppendValue(StringBuilder sb, int x)
{
if (StrykerNamespace.MutantControl.IsActive(0)) { } else
{
if (StrykerNamespace.MutantControl.IsActive(1))
{
;
}
else
{
if (StrykerNamespace.MutantControl.IsActive(2))
{
sb.AppendLine($"");
}
else
{
sb.AppendLine($"Value is {x}");
}
}
}
}
""";

ShouldMutateSourceInClassToExpected(source, expected);
}

[TestMethod]
public void ShouldMutateInterpolatedStringHandlerInVoidExpressionBodiedMethod()
{
var source = """
public void Log(int x) => Write($"Value is {x}");
private void Write(ref System.Runtime.CompilerServices.DefaultInterpolatedStringHandler handler) { }
""";

var expected = """
public void Log(int x)
{
if (StrykerNamespace.MutantControl.IsActive(0))
{
Write($"");
}
else
{
Write($"Value is {x}");
}
}
private void Write(ref System.Runtime.CompilerServices.DefaultInterpolatedStringHandler handler) { }
""";

ShouldMutateSourceInClassToExpected(source, expected);
}

[TestMethod]
public void ShouldMutateFormattableStringInterpolatedString()
{
var source = """
public static string Format(int x) => FormattableString.Invariant($"Value is {x}");
""";

var expected = """
public static string Format(int x) =>
(StrykerNamespace.MutantControl.IsActive(0) ? FormattableString.Invariant($"") : FormattableString.Invariant($"Value is {x}"));
""";

ShouldMutateSourceInClassToExpected(source, expected);
}

[TestMethod]
public void ShouldMutateFormattableStringLocalDeclaration()
{
var source = """
public static string Format(int x)
{
FormattableString f = $"Value is {x}";
return FormattableString.Invariant(f);
}
""";

var expected = """
public static string Format(int x)
{
if (StrykerNamespace.MutantControl.IsActive(0)) { } else
{
if (StrykerNamespace.MutantControl.IsActive(1))
{
FormattableString f = $"";
return FormattableString.Invariant(f);
}
else
{
FormattableString f = $"Value is {x}";
return FormattableString.Invariant(f);
}
}
return default(string);
}
""";

ShouldMutateSourceInClassToExpected(source, expected);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ private static List<INodeOrchestrator> BuildOrchestratorList() =>
// ensure declaration are mutated at the block level
new LocalDeclarationOrchestrator(),
new InvocationExpressionOrchestrator(),
new InterpolatedStringExpressionOrchestrator(),
new NodeSpecificOrchestrator<GlobalStatementSyntax, GlobalStatementSyntax>(),
new MemberDefinitionOrchestrator<MemberDeclarationSyntax>(),
new MutateAtStatementLevelOrchestrator<AssignmentExpressionSyntax>(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Stryker.Core.Helpers;

namespace Stryker.Core.Mutants.CsharpNodeOrchestrators;

internal class InterpolatedStringExpressionOrchestrator : ExpressionSpecificOrchestrator<InterpolatedStringExpressionSyntax>
{
public override SyntaxNode Mutate(SyntaxNode node, SemanticModel semanticModel, MutationContext context)
{
if (node is InterpolatedStringExpressionSyntax interpolatedString && RequiresHigherLevelControl(interpolatedString, semanticModel))
{
context = PrepareContext(interpolatedString, context);
var mutations = GenerateMutationForNode(interpolatedString, semanticModel, context);
var targetNode = OrchestrateChildrenMutation(interpolatedString, semanticModel, context);
context.AddMutations(mutations, interpolatedString.ContainsDeclarations() ? MutationControl.Block : MutationControl.Statement);
RestoreContext(context);
return targetNode;
}

return base.Mutate(node, semanticModel, context);
}

private static bool RequiresHigherLevelControl(InterpolatedStringExpressionSyntax node, SemanticModel semanticModel)
{
if (semanticModel is null)
{
return false;
}

var conversion = semanticModel.GetConversion(node);
return conversion.IsInterpolatedStringHandler || conversion.IsInterpolatedString;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ namespace Stryker.Core.Mutants.CsharpNodeOrchestrators;

internal class InvocationExpressionOrchestrator : MemberAccessExpressionOrchestrator<InvocationExpressionSyntax>
{
protected override ExpressionSyntax InjectMutations(InvocationExpressionSyntax sourceNode, ExpressionSyntax targetNode, SemanticModel semanticModel, MutationContext context) =>
sourceNode.Parent is ExpressionStatementSyntax || semanticModel?.GetTypeInfo(sourceNode).Type?.SpecialType == SpecialType.System_Void
? targetNode
: base.InjectMutations(sourceNode, targetNode, semanticModel, context);

protected override MutationContext StoreMutations(InvocationExpressionSyntax node,
IEnumerable<Mutant> mutations,
Expand Down
Loading