Skip to content
Open
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
1 change: 1 addition & 0 deletions MSTest.slnf
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"src\\Analyzers\\MSTest.Analyzers.CodeFixes\\MSTest.Analyzers.CodeFixes.csproj",
"src\\Analyzers\\MSTest.Analyzers.Package\\MSTest.Analyzers.Package.csproj",
"src\\Analyzers\\MSTest.Analyzers\\MSTest.Analyzers.csproj",
"src\\Analyzers\\MSTest.AotReflection.SourceGeneration\\MSTest.AotReflection.SourceGeneration.csproj",
"src\\Analyzers\\MSTest.GlobalConfigsGenerator\\MSTest.GlobalConfigsGenerator.csproj",
"src\\Analyzers\\MSTest.SourceGeneration\\MSTest.SourceGeneration.csproj",
"src\\Package\\MSTest.Sdk\\MSTest.Sdk.csproj",
Expand Down
2 changes: 2 additions & 0 deletions TestFx.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
<BuildDependency Project="src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj" />
</Project>
<Project Path="src/Analyzers/MSTest.Analyzers/MSTest.Analyzers.csproj" />
<Project Path="src/Analyzers/MSTest.AotReflection.SourceGeneration/MSTest.AotReflection.SourceGeneration.csproj" />
<Project Path="src/Analyzers/MSTest.GlobalConfigsGenerator/MSTest.GlobalConfigsGenerator.csproj" />
<Project Path="src/Analyzers/MSTest.SourceGeneration/MSTest.SourceGeneration.csproj" />
</Folder>
Expand Down Expand Up @@ -133,6 +134,7 @@
<Project Path="test/UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests/Microsoft.Testing.Platform.MSBuild.UnitTests.csproj" />
<Project Path="test/UnitTests/Microsoft.Testing.Platform.UnitTests/Microsoft.Testing.Platform.UnitTests.csproj" />
<Project Path="test/UnitTests/MSTest.Analyzers.UnitTests/MSTest.Analyzers.UnitTests.csproj" />
<Project Path="test/UnitTests/MSTest.AotReflection.SourceGeneration.UnitTests/MSTest.AotReflection.SourceGeneration.UnitTests.csproj" />
<Project Path="test/UnitTests/MSTest.SelfRealExamples.UnitTests/MSTest.SelfRealExamples.UnitTests.csproj" />
<Project Path="test/UnitTests/MSTest.SourceGeneration.UnitTests/MSTest.SourceGeneration.UnitTests.csproj" />
<Project Path="test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/MSTestAdapter.PlatformServices.UnitTests.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;

using Microsoft.CodeAnalysis;

Expand All @@ -19,31 +21,61 @@ internal static class TestClassModelBuilder
{
private static readonly SymbolDisplayFormat FullyQualifiedFormat =
SymbolDisplayFormat.FullyQualifiedFormat.WithMiscellaneousOptions(
SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier
| SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);

public static TestClassModel Build(INamedTypeSymbol typeSymbol)
{
// Methods / properties are walked across the full inheritance chain (excluding
// System.Object) so that MSTest members declared on a base class —
// [ClassInitialize], [ClassCleanup], [TestInitialize], [TestCleanup],
// [TestMethod], the [TestContext] setter, … — are visible to the consumer
// without runtime reflection.
//
// Iteration order is derived-first so that an override or `new`-shadowed member
// on the derived type wins over the base declaration with the same signature.
// Constructors are NEVER inherited and are taken only from the leaf type.
var methodsByKey = new Dictionary<string, TestMethodModel>(StringComparer.Ordinal);
var propertiesByName = new Dictionary<string, TestPropertyModel>(StringComparer.Ordinal);
ImmutableArray<TestMethodModel>.Builder methods = ImmutableArray.CreateBuilder<TestMethodModel>();
ImmutableArray<TestPropertyModel>.Builder properties = ImmutableArray.CreateBuilder<TestPropertyModel>();
ImmutableArray<TestConstructorModel>.Builder ctors = ImmutableArray.CreateBuilder<TestConstructorModel>();

foreach (ISymbol member in typeSymbol.GetMembers())
for (INamedTypeSymbol? current = typeSymbol;
current is not null && current.SpecialType != SpecialType.System_Object;
current = current.BaseType)
{
switch (member)
bool isLeaf = SymbolEqualityComparer.Default.Equals(current, typeSymbol);

foreach (ISymbol member in current.GetMembers())
{
case IMethodSymbol { MethodKind: MethodKind.Ordinary } method
when method.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal:
methods.Add(BuildMethod(method));
break;
case IPropertySymbol property
when property.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal:
properties.Add(BuildProperty(property));
break;
case IMethodSymbol { MethodKind: MethodKind.Constructor, IsStatic: false } ctor
when ctor.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal:
ctors.Add(new TestConstructorModel(BuildParameters(ctor)));
break;
switch (member)
{
case IMethodSymbol { MethodKind: MethodKind.Ordinary } method
when IsAccessibleFromConsumer(method):
string key = BuildMethodSignatureKey(method);
if (!methodsByKey.ContainsKey(key))
{
TestMethodModel model = BuildMethod(method);
methodsByKey[key] = model;
methods.Add(model);
}

break;
case IPropertySymbol property
when IsAccessibleFromConsumer(property):
if (!propertiesByName.ContainsKey(property.Name))
{
TestPropertyModel model = BuildProperty(property);
propertiesByName[property.Name] = model;
properties.Add(model);
}

break;
case IMethodSymbol { MethodKind: MethodKind.Constructor, IsStatic: false } ctor
when isLeaf && ctor.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal:
ctors.Add(new TestConstructorModel(BuildParameters(ctor)));
break;
}
}
}

Expand All @@ -61,6 +93,52 @@ public static TestClassModel Build(INamedTypeSymbol typeSymbol)
Attributes: BuildAttributes(typeSymbol.GetAttributes()));
}

// Restricted to accessibilities the emitted helper class (a separate static type
// declared in MSTest.SourceGenerated, not a derived type) can legally call.
// 'protected' and 'private protected' members require the caller to be a derived
// type, so they are excluded; 'protected internal' is included because the internal
// half is satisfied (the generated helper lives in the same assembly).
private static bool IsAccessibleFromConsumer(ISymbol symbol)
=> symbol.DeclaredAccessibility is
Accessibility.Public
or Accessibility.Internal
or Accessibility.ProtectedOrInternal;

private static string BuildMethodSignatureKey(IMethodSymbol method)
{
var sb = new StringBuilder();
sb.Append(method.IsStatic ? "S:" : "I:");
sb.Append(method.Name);
sb.Append('(');
bool first = true;
foreach (IParameterSymbol p in method.Parameters)
{
if (!first)
{
sb.Append(',');
}

first = false;
switch (p.RefKind)
{
case RefKind.Ref:
sb.Append("ref ");
break;
case RefKind.Out:
sb.Append("out ");
break;
case RefKind.In:
sb.Append("in ");
break;
}

sb.Append(p.Type.ToDisplayString(FullyQualifiedFormat));
}

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

private static TestMethodModel BuildMethod(IMethodSymbol method)
{
ITypeSymbol returnType = method.ReturnType;
Expand All @@ -82,15 +160,113 @@ private static TestMethodModel BuildMethod(IMethodSymbol method)
ReturnsValueTask: returnsValueTask,
ReturnsVoid: returnsVoid,
Parameters: BuildParameters(method),
Attributes: BuildAttributes(method.GetAttributes()));
Attributes: BuildAttributes(CollectInheritedAttributes(method)));
}

private static TestPropertyModel BuildProperty(IPropertySymbol property)
=> new(
Name: property.Name,
FullyQualifiedType: property.Type.ToDisplayString(FullyQualifiedFormat),
HasPublicSetter: property.SetMethod is { DeclaredAccessibility: Accessibility.Public },
Attributes: BuildAttributes(property.GetAttributes()));
Attributes: BuildAttributes(CollectInheritedAttributes(property)));

// Mirror the runtime behavior of MemberInfo.GetCustomAttributes(inherit: true): walk the
// overridden-method chain and union attributes, keeping the most-derived application when
// the same attribute type appears on multiple levels.
private static ImmutableArray<AttributeData> CollectInheritedAttributes(IMethodSymbol method)
{
ImmutableArray<AttributeData> own = method.GetAttributes();
if (method.OverriddenMethod is null)
{
return own;
}

var seen = new HashSet<string>(StringComparer.Ordinal);
ImmutableArray<AttributeData>.Builder builder = ImmutableArray.CreateBuilder<AttributeData>();
AppendUnique(builder, seen, own);
for (IMethodSymbol? baseMethod = method.OverriddenMethod; baseMethod is not null; baseMethod = baseMethod.OverriddenMethod)
{
AppendUnique(builder, seen, baseMethod.GetAttributes());
}

return builder.ToImmutable();
}

private static ImmutableArray<AttributeData> CollectInheritedAttributes(IPropertySymbol property)
{
ImmutableArray<AttributeData> own = property.GetAttributes();
if (property.OverriddenProperty is null)
{
return own;
}

var seen = new HashSet<string>(StringComparer.Ordinal);
ImmutableArray<AttributeData>.Builder builder = ImmutableArray.CreateBuilder<AttributeData>();
AppendUnique(builder, seen, own);
for (IPropertySymbol? baseProperty = property.OverriddenProperty; baseProperty is not null; baseProperty = baseProperty.OverriddenProperty)
{
AppendUnique(builder, seen, baseProperty.GetAttributes());
}

return builder.ToImmutable();
}

private static void AppendUnique(
ImmutableArray<AttributeData>.Builder builder,
HashSet<string> seen,
ImmutableArray<AttributeData> attributes)
{
foreach (AttributeData attribute in attributes)
{
if (attribute.AttributeClass is not { } attributeClass)
{
continue;
}

// Attributes declared with AttributeUsage(AllowMultiple = true) may legitimately
// appear several times across the override chain (e.g. [TestCategory]) — keep every
// instance instead of collapsing them to one.
if (AllowsMultiple(attributeClass))
{
builder.Add(attribute);
continue;
}

string key = attributeClass.ToDisplayString(FullyQualifiedFormat);
if (seen.Add(key))
{
builder.Add(attribute);
}
}
}

private static bool AllowsMultiple(INamedTypeSymbol attributeClass)
{
for (INamedTypeSymbol? current = attributeClass; current is not null; current = current.BaseType)
{
foreach (AttributeData attribute in current.GetAttributes())
{
if (attribute.AttributeClass?.ToDisplayString(FullyQualifiedFormat) != "global::System.AttributeUsageAttribute")
{
continue;
}

foreach (KeyValuePair<string, TypedConstant> named in attribute.NamedArguments)
{
if (named.Key == "AllowMultiple" && named.Value.Value is bool allowMultiple)
{
return allowMultiple;
}
}

// AttributeUsage was found on this level but did not set AllowMultiple — default is false
// and base-level [AttributeUsage] is shadowed by the derived application per CLI rules.
return false;
}
}

return false;
}

private static EquatableArray<TestParameterModel> BuildParameters(IMethodSymbol method)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,8 @@
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="MSTest.AotReflection.SourceGeneration.UnitTests" Key="$(VsPublicKey)" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net8.0</TargetFrameworks>
<RootNamespace>MSTest.AotReflection.SourceGeneration.UnitTests</RootNamespace>
<UseMSTestFromSource>true</UseMSTestFromSource>
<EnableMSTestRunner>true</EnableMSTestRunner>
<OutputType>Exe</OutputType>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" PrivateAssets="all" VersionOverride="$(MicrosoftCodeAnalysisVersionForSourceGen)" />
<PackageReference Include="AwesomeAssertions" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="$(RepoRoot)src\Adapter\MSTest.TestAdapter\MSTest.TestAdapter.csproj" />
<ProjectReference Include="$(RepoRoot)src\TestFramework\TestFramework.Extensions\TestFramework.Extensions.csproj" />
<!-- Reference the generator project as a regular library so that the (internal) generator class
can be instantiated in tests; access is granted via InternalsVisibleTo on the generator project. -->
<ProjectReference Include="$(RepoRoot)src\Analyzers\MSTest.AotReflection.SourceGeneration\MSTest.AotReflection.SourceGeneration.csproj" />
</ItemGroup>

</Project>
Loading
Loading