Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better implementation for helpers in async state machine #640

Merged
merged 1 commit into from
Aug 1, 2024
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
59 changes: 54 additions & 5 deletions src/Meziantou.Framework.InlineSnapshotTesting/CallerContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,17 @@ public static CallerContext Get(InlineSnapshotSettings settings, string? filePat
if (frame is null)
continue;

var methodInfo = frame.GetMethod();
if (methodInfo == null)
var method = frame.GetMethod();
if (method == null)
continue;

var attribute = methodInfo.GetCustomAttribute<InlineSnapshotAssertionAttribute>();
method = GetActualMethod(method);

var attribute = method.GetCustomAttribute<InlineSnapshotAssertionAttribute>();
if (attribute is null)
continue;

methodName = methodInfo.Name;
methodName = method.Name;
if (ParseLocalFunctionName(methodName, out var localFunctionName))
{
methodName = localFunctionName;
Expand All @@ -52,7 +54,7 @@ public static CallerContext Get(InlineSnapshotSettings settings, string? filePat
parameterName = attribute.ParameterName;
if (parameterName is not null)
{
var parameters = methodInfo.GetParameters();
var parameters = method.GetParameters();
for (var j = 0; j < parameterName.Length; j++)
{
if (parameters[j].Name == parameterName)
Expand Down Expand Up @@ -179,6 +181,53 @@ public readonly CSharpStringFormats FilterFormats(CSharpStringFormats formats)
return formats;
}

private static MethodBase GetActualMethod(MethodBase method)
{
if (method.DeclaringType.IsAssignableTo(typeof(IAsyncStateMachine)))
{
var parentType = method.DeclaringType.DeclaringType;
if (parentType is not null)
{
static MethodInfo[] GetDeclaredMethods(Type type) => type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
var methods = GetDeclaredMethods(parentType);
if (methods is not null)
{
foreach (var candidateMethod in methods)
{
var attributes = candidateMethod.GetCustomAttributes<StateMachineAttribute>(inherit: false);
// ReSharper disable once ConditionIsAlwaysTrueOrFalse - Taken from CoreFX
if (attributes is null)
{
continue;
}

bool foundAttribute = false, foundIteratorAttribute = false;
foreach (var asma in attributes)
{
if (asma.StateMachineType == method.DeclaringType)
{
foundAttribute = true;
foundIteratorAttribute |= asma is IteratorStateMachineAttribute
|| typeof(System.Runtime.CompilerServices.AsyncIteratorStateMachineAttribute) != null
&& typeof(System.Runtime.CompilerServices.AsyncIteratorStateMachineAttribute).IsInstanceOfType(asma);
}
}

if (foundAttribute)
{
// If this is an iterator (sync or async), mark the iterator as changed, so it gets the + annotation
// of the original method. Non-iterator async state machines resolve directly to their builder methods
// so aren't marked as changed.
return candidateMethod;
}
}
}
}
}

return method;
}

private static Version? GetCSharpLanguageVersionFromAssemblyLocation(string assemblyLocation)
{
try
Expand Down
32 changes: 13 additions & 19 deletions src/Meziantou.Framework.InlineSnapshotTesting/FileEditor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,29 +83,23 @@ public static void UpdateFile(CallerContext context, InlineSnapshotSettings sett
span = new TextSpan(span.Start + context.ColumnNumber, 1);
}

// It can be hard to find the method name from the call stack (compiler state machine from async/await, iterators, async iterators, etc.)
// If there is only one invocation, let's use it
var nodes = FindInvocations(root, span).ToArray();
if (nodes.Length > 1)
var nodes = FindInvocations(root, span).Where(invocation =>
{
nodes = FindInvocations(root, span).Where(invocation =>
{
// Dummy.MethodName()
if (invocation.Expression is MemberAccessExpressionSyntax { Name.Identifier.Text: string memberName } && memberName == context.MethodName)
return true;
// Dummy.MethodName()
if (invocation.Expression is MemberAccessExpressionSyntax { Name.Identifier.Text: string memberName } && memberName == context.MethodName)
return true;

// Dummy.MethodName<T>()
if (invocation.Expression is GenericNameSyntax { Identifier.Text: string memberName2 } && memberName2 == context.MethodName)
return true;
// Dummy.MethodName<T>()
if (invocation.Expression is GenericNameSyntax { Identifier.Text: string memberName2 } && memberName2 == context.MethodName)
return true;

// MethodName()
if (invocation.Expression is IdentifierNameSyntax { Identifier.Text: string identifierName } && identifierName == context.MethodName)
return true;
// MethodName()
if (invocation.Expression is IdentifierNameSyntax { Identifier.Text: string identifierName } && identifierName == context.MethodName)
return true;

return false;
})
.ToArray();
}
return false;
})
.ToArray();

if (nodes.Length == 0)
throw new InlineSnapshotException("Cannot find the SyntaxNode to update");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<Description>Enables verification of objects using inline snapshots</Description>
<DefineConstants Condition="'$(IsOfficialBuild)' != 'true'">$(DefineConstants);DEBUG_TaskDialogPrompt</DefineConstants>

<Version>3.0.6</Version>
<Version>3.0.7</Version>
<NoWarn>$(NoWarn);NU5100</NoWarn>

<!-- Buggy because of netstandard2.0 -->
Expand All @@ -27,7 +27,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="DiffEngine" Version="15.4.6" />
<PackageReference Include="DiffEngine" Version="15.5.0" />
<PackageReference Include="DiffPlex" Version="1.7.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.10.0" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,128 @@ static async System.Threading.Tasks.Task Helper(string expected, [CallerFilePath
"""");
}

[Fact]
public async Task SupportAsyncHelperMethods_WithAsyncCodeAndMultipleInvocation()
{
await AssertSnapshot(
$$""""
await Helper("", GetValue());

string GetValue() => "";

[InlineSnapshotAssertion(nameof(expected))]
static async System.Threading.Tasks.Task Helper(string expected, string dummy, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = -1)
{
await System.Threading.Tasks.Task.Yield();
var data = new
{
FirstName = "Gérald",
LastName = "Barré",
NickName = "meziantou",
};
{{nameof(InlineSnapshot)}}.{{nameof(InlineSnapshot.Validate)}}(data, expected, filePath, lineNumber);
}
"""",
$$""""
await Helper("""
FirstName: Gérald
LastName: Barré
NickName: meziantou
""", GetValue());

string GetValue() => "";

[InlineSnapshotAssertion(nameof(expected))]
static async System.Threading.Tasks.Task Helper(string expected, string dummy, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = -1)
{
await System.Threading.Tasks.Task.Yield();
var data = new
{
FirstName = "Gérald",
LastName = "Barré",
NickName = "meziantou",
};
{{nameof(InlineSnapshot)}}.{{nameof(InlineSnapshot.Validate)}}(data, expected, filePath, lineNumber);
}
"""");
}

[Fact]
public async Task SupportMultipleAsyncHelperMethods_WithAsyncCode()
{
await AssertSnapshot(
$$""""
await Helper1("");

await Helper2("");

[InlineSnapshotAssertion(nameof(expected))]
static async System.Threading.Tasks.Task Helper1(string expected, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = -1)
{
await System.Threading.Tasks.Task.Yield();
var data = new
{
FirstName = "Gérald",
LastName = "Barré",
NickName = "meziantou",
};
{{nameof(InlineSnapshot)}}.{{nameof(InlineSnapshot.Validate)}}(data, expected, filePath, lineNumber);
}

[InlineSnapshotAssertion(nameof(expected))]
static async System.Threading.Tasks.Task Helper2(string expected, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = -1)
{
await System.Threading.Tasks.Task.Yield();
var data = new
{
FirstName = "Gérald",
LastName = "Barré",
NickName = "meziantou",
};
{{nameof(InlineSnapshot)}}.{{nameof(InlineSnapshot.Validate)}}(data, expected, filePath, lineNumber);
}
"""",
$$""""
await Helper1("""
FirstName: Gérald
LastName: Barré
NickName: meziantou
""");

await Helper2("""
FirstName: Gérald
LastName: Barré
NickName: meziantou
""");

[InlineSnapshotAssertion(nameof(expected))]
static async System.Threading.Tasks.Task Helper1(string expected, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = -1)
{
await System.Threading.Tasks.Task.Yield();
var data = new
{
FirstName = "Gérald",
LastName = "Barré",
NickName = "meziantou",
};
{{nameof(InlineSnapshot)}}.{{nameof(InlineSnapshot.Validate)}}(data, expected, filePath, lineNumber);
}

[InlineSnapshotAssertion(nameof(expected))]
static async System.Threading.Tasks.Task Helper2(string expected, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = -1)
{
await System.Threading.Tasks.Task.Yield();
var data = new
{
FirstName = "Gérald",
LastName = "Barré",
NickName = "meziantou",
};
{{nameof(InlineSnapshot)}}.{{nameof(InlineSnapshot.Validate)}}(data, expected, filePath, lineNumber);
}
"""");
}

[Fact]
public async Task SupportAsyncGenericHelperMethods()
{
Expand Down