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 @@ -48,12 +48,15 @@ private static bool HasDataSourceAttribute(IPropertySymbol property)
{
return property.GetAttributes().Any(attr =>
{
var attrName = attr.AttributeClass?.Name ?? "";
return attrName.EndsWith("DataSourceAttribute") ||
attrName == "ClassDataSource" ||
attrName == "MethodDataSource" ||
attrName == "ArgumentsAttribute" ||
attrName == "DataSourceForAttribute";
var attrClass = attr.AttributeClass;

if (attrClass == null)
{
return false;
}

// Check if the attribute implements IDataSourceAttribute
return attrClass.AllInterfaces.Any(i => i.GloballyQualified() == WellKnownFullyQualifiedClassNames.IDataSourceAttribute.WithGlobalPrefix);
});
}

Expand Down Expand Up @@ -85,4 +88,4 @@ public static string GetDefaultValueForType(ITypeSymbol type)
_ => $"default({type.GloballyQualified()})"
};
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
Expand All @@ -27,23 +25,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)

private static bool IsClassWithDataSourceProperties(SyntaxNode node)
{
if (node is not TypeDeclarationSyntax typeDecl)
{
return false;
}

// Include classes with properties that have attributes
var hasAttributedProperties = typeDecl.Members
.OfType<PropertyDeclarationSyntax>()
.Any(prop => prop.AttributeLists.Count > 0);

// Also include classes that inherit from data source attributes
var inheritsFromDataSource = typeDecl.BaseList?.Types.Any(t =>
t.ToString().Contains("DataSourceGeneratorAttribute") ||
t.ToString().Contains("AsyncDataSourceGeneratorAttribute") ||
t.ToString().Contains("DataSourceAttribute")) == true;

return hasAttributedProperties || inheritsFromDataSource;
return node is TypeDeclarationSyntax;
}

private static ClassWithDataSourceProperties? GetClassWithDataSourceProperties(GeneratorSyntaxContext context)
Expand All @@ -56,6 +38,19 @@ private static bool IsClassWithDataSourceProperties(SyntaxNode node)
return null;
}

// Skip types that are not publicly accessible to avoid accessibility issues
// Also check if the type is nested and ensure the containing types are also public
if (!IsPubliclyAccessible(typeSymbol))
{
return null;
}

// Skip open generic types (unbound type parameters) as they cannot be instantiated
if (typeSymbol.IsUnboundGenericType || typeSymbol.TypeParameters.Length > 0)
{
return null;
}

var propertiesWithDataSources = new List<PropertyWithDataSourceAttribute>();
var dataSourceInterface = semanticModel.Compilation.GetTypeByMetadataName("TUnit.Core.IDataSourceAttribute");

Expand All @@ -67,51 +62,34 @@ private static bool IsClassWithDataSourceProperties(SyntaxNode node)
// Check if this type itself implements IDataSourceAttribute (for custom data source classes)
var implementsDataSource = typeSymbol.AllInterfaces.Contains(dataSourceInterface, SymbolEqualityComparer.Default);

var currentType = typeSymbol;
var processedProperties = new HashSet<string>();

while (currentType != null)
var properties = typeSymbol.GetMembersIncludingBase()
.OfType<IPropertySymbol>()
.Where(CanSetProperty);

foreach (var property in properties)
{
foreach (var member in currentType.GetMembers())
if (!processedProperties.Add(property.Name))
{
if (member is IPropertySymbol property && CanSetProperty(property))
{
if (!processedProperties.Add(property.Name))
{
continue;
}

foreach (var attr in property.GetAttributes())
{
if (attr.AttributeClass != null &&
(attr.AttributeClass.IsOrInherits(dataSourceInterface) ||
attr.AttributeClass.AllInterfaces.Contains(dataSourceInterface, SymbolEqualityComparer.Default)))
{
propertiesWithDataSources.Add(new PropertyWithDataSourceAttribute
{
Property = property,
DataSourceAttribute = attr
});
break; // Only one data source per property
}
}
}
continue;
}

currentType = currentType.BaseType;

if (currentType?.SpecialType == SpecialType.System_Object)
foreach (var attr in property.GetAttributes())
{
break;
if (attr.AttributeClass != null &&
attr.AttributeClass.AllInterfaces.Contains(dataSourceInterface, SymbolEqualityComparer.Default))
{
propertiesWithDataSources.Add(new PropertyWithDataSourceAttribute
{
Property = property,
DataSourceAttribute = attr
});
break; // Only one data source per property
}
}
}

// Include the class if it has properties with data sources OR if it implements IDataSourceAttribute
if (propertiesWithDataSources.Count == 0 && !implementsDataSource)
{
return null;
}

return new ClassWithDataSourceProperties
{
ClassSymbol = typeSymbol,
Expand All @@ -124,6 +102,36 @@ private static bool CanSetProperty(IPropertySymbol property)
return property.SetMethod != null || property.SetMethod?.IsInitOnly == true;
}

private static bool IsPubliclyAccessible(INamedTypeSymbol typeSymbol)
{
// Check if the type itself is public
if (typeSymbol.DeclaredAccessibility != Accessibility.Public)
{
return false;
}

// If it's a nested type, ensure all containing types are also public
// and don't have unbound type parameters
var containingType = typeSymbol.ContainingType;
while (containingType != null)
{
if (containingType.DeclaredAccessibility != Accessibility.Public)
{
return false;
}

// Check if the containing type has unbound type parameters
if (containingType.IsUnboundGenericType || containingType.TypeParameters.Length > 0)
{
return false;
}

containingType = containingType.ContainingType;
}

return true;
}

private static void GeneratePropertyInjectionSources(SourceProductionContext context, ImmutableArray<ClassWithDataSourceProperties> classes)
{
if (classes.IsEmpty)
Expand All @@ -135,17 +143,23 @@ private static void GeneratePropertyInjectionSources(SourceProductionContext con

WriteFileHeader(sourceBuilder);

// Deduplicate classes by symbol to prevent duplicate source generation
var uniqueClasses = classes
.GroupBy(c => c.ClassSymbol, SymbolEqualityComparer.Default)
.Select(g => g.First())
.ToImmutableArray();

// Generate all property sources first with stable names
var classNameMapping = new Dictionary<INamedTypeSymbol, string>(SymbolEqualityComparer.Default);
foreach (var classInfo in classes)
foreach (var classInfo in uniqueClasses)
{
var sourceClassName = GetPropertySourceClassName(classInfo.ClassSymbol);
classNameMapping[classInfo.ClassSymbol] = sourceClassName;
}

GenerateModuleInitializer(sourceBuilder, classes, classNameMapping);
GenerateModuleInitializer(sourceBuilder, uniqueClasses, classNameMapping);

foreach (var classInfo in classes)
foreach (var classInfo in uniqueClasses)
{
GeneratePropertySource(sourceBuilder, classInfo, classNameMapping[classInfo.ClassSymbol]);
}
Expand Down Expand Up @@ -218,7 +232,7 @@ private static void GenerateUnsafeAccessorMethods(StringBuilder sb, ClassWithDat

// Use the property's containing type for the UnsafeAccessor, not the derived class
var containingType = propInfo.Property.ContainingType.ToDisplayString();

sb.AppendLine("#if NET8_0_OR_GREATER");
sb.AppendLine($" [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.Field, Name = \"{backingFieldName}\")]");
sb.AppendLine($" private static extern ref {propertyType} Get{propInfo.Property.Name}BackingField({containingType} instance);");
Expand Down Expand Up @@ -344,9 +358,10 @@ private static string GetPropertyCastExpression(IPropertySymbol property, string

private static string GetPropertySourceClassName(INamedTypeSymbol classSymbol)
{
// Use a random GUID for uniqueness
var guid = Guid.NewGuid();
return $"PropertyInjectionSource_{guid:N}";
// Use a deterministic hash based on the fully qualified type name for uniqueness
var fullTypeName = classSymbol.ToDisplayString();
var hash = fullTypeName.GetHashCode();
return $"PropertyInjectionSource_{Math.Abs(hash):x}";
}

private static string FormatTypedConstant(TypedConstant constant)
Expand Down
39 changes: 39 additions & 0 deletions TUnit.TestProject/Bugs/3072/Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using TUnit.Core.Interfaces;
using TUnit.TestProject.Attributes;

namespace TUnit.TestProject.Bugs._3072;

public record DataClass
{
public string TestProperty { get; init; } = "TestValue";
}

public abstract class BaseClass
{
[ClassDataSource<DataClass>(Shared = SharedType.PerTestSession)]
public required DataClass TestData { get; init; }
}

public class TestFactory : BaseClass, IAsyncInitializer
{
public Task InitializeAsync()
{
var test = TestData.TestProperty; // TestData is null here in 0.57.24
return Task.CompletedTask;
}
}

[EngineTest(ExpectedResult.Pass)]
public class Tests : IAsyncInitializer
{
[ClassDataSource<TestFactory>(Shared = SharedType.PerTestSession)]
public required TestFactory TestDataFactory { get; init; }

public Task InitializeAsync() => Task.CompletedTask;

[Test]
public async Task Test()
{
await Assert.That(TestDataFactory?.TestData?.TestProperty).IsEqualTo("TestValue");
}
}
20 changes: 20 additions & 0 deletions TUnit.TestProject/Bugs/SourceLocationRepro.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
namespace TUnit.TestProject.Bugs;

public abstract class BaseTestForSourceLocationCheck
{
[Test]
public async Task BaseTestMethod()
{
await Assert.That(Environment.ProcessorCount).IsGreaterThan(0);
}
}

[InheritsTests]
public sealed class DerivedTestForSourceLocationCheck : BaseTestForSourceLocationCheck
{
[Test]
public async Task DerivedTestMethod()
{
await Assert.That(Environment.ProcessorCount).IsGreaterThan(0);
}
}
1 change: 0 additions & 1 deletion TestProject.targets
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
<ItemGroup>
<ProjectReference Include="$(MSBuildThisFileDirectory)TUnit.Engine\TUnit.Engine.csproj" />
<ProjectReference Include="$(MSBuildThisFileDirectory)TUnit.Assertions\TUnit.Assertions.csproj" />
<PackageReference Include="Microsoft.Testing.Platform.MSBuild" />

<ProjectReference
Include="$(MSBuildThisFileDirectory)TUnit.Assertions.Analyzers\TUnit.Assertions.Analyzers.csproj"
Expand Down
Loading