Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Aug 6, 2025

The TUnit0001 analyzer was incorrectly reporting type mismatch errors for custom data source generators that implement ITypedDataSourceAttribute<T> with wrapper types.

Problem

After upgrading from TUnit 0.25 to 0.52.25, users experienced false positive TUnit0001 warnings when using custom data source generators like:

public sealed class ApplicationFixtureGeneratorAttribute<T> : DataSourceGeneratorAttribute<ApplicationFixture<T>>
    where T : notnull
{ 
   protected override IEnumerable<Func<ApplicationFixture<T>>> GenerateDataSources(
            DataGeneratorMetadata dataGeneratorMetadata)
    {
        yield return () => new ApplicationFixture<T>();
    }
}

[ApplicationFixtureGenerator<IGantryMethods>]
public class MethodCallingTest(ApplicationFixture<IGantryMethods> appFixture)
{
    // TUnit0001 error was incorrectly reported here
}

Root Cause

The CheckDataGenerator method was using string-based detection of base class names to extract type arguments, which was fragile and didn't align with the interface-based approach used by the source generator.

Solution

Modified the analyzer to use the same approach as the source generator by looking for the ITypedDataSourceAttribute<T> interface to extract type arguments. This provides a more robust and consistent method that:

  1. Uses interface detection: Looks for ITypedDataSourceAttribute<T> interface implementations first
  2. Extracts correct types: Gets ApplicationFixture<IGantryMethods> from the interface instead of IGantryMethods from the attribute's type parameters
  3. Maintains consistency: Follows the exact same pattern as the source generator
  4. Preserves backward compatibility: Falls back to original base class detection when interface is not found

The fix correctly handles both single-type and tuple scenarios while maintaining full backward compatibility with existing code.

Fixes #2801.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

Copilot AI changed the title [WIP] TUnit0001 after updating from 0.25 to 0.52.25 Fix TUnit0001 false positive for custom DataSourceGeneratorAttribute implementations Aug 6, 2025
Copilot finished work on behalf of thomhurst August 6, 2025 20:53
Copilot AI requested a review from thomhurst August 6, 2025 20:53
@thomhurst
Copy link
Owner

@copilot Can you instead look for ITypedDataSourceAttribute<T>. All typed data generators should use this interface.

…DataSourceAttribute interface lookup

Co-authored-by: thomhurst <[email protected]>
Copy link
Contributor Author

Copilot AI commented Aug 6, 2025

@copilot Can you instead look for ITypedDataSourceAttribute<T>. All typed data generators should use this interface.

Changed the analyzer to look for ITypedDataSourceAttribute<T> interface instead of specific base class names. This follows the same pattern as the source generator and provides a cleaner, more reliable approach. The fix now correctly extracts ApplicationFixture<IGantryMethods> from the interface rather than IGantryMethods from the attribute's own type parameters, resolving the false positive TUnit0001 errors for custom data source generators. Commit: 42a9d47

Copilot AI changed the title Fix TUnit0001 false positive for custom DataSourceGeneratorAttribute implementations Fix TUnit0001 false positive for custom ITypedDataSourceAttribute implementations Aug 6, 2025
Copilot finished work on behalf of thomhurst August 6, 2025 21:27
@thomhurst thomhurst marked this pull request as ready for review August 6, 2025 21:28
@claude
Copy link
Contributor

claude bot commented Aug 6, 2025

Claude finished @Copilot's task —— View job


PR Review Complete

Todo List:

  • Read repository guidelines (CLAUDE.md)
  • Analyze changed files and implementation
  • Review code quality and best practices
  • Check for potential bugs or issues
  • Evaluate performance considerations
  • Assess security concerns
  • Review test coverage
  • Provide comprehensive feedback

Summary

This PR successfully fixes TUnit0001 false positive errors for custom data source generators by replacing fragile string-based base class detection with robust interface-based detection using ITypedDataSourceAttribute<T>.

Code Quality & Best Practices ✅

Excellent improvements:

  • Interface-based detection: The move from string-based base class name matching to ITypedDataSourceAttribute<T> interface lookup is much more robust and aligns with the source generator's approach
  • Consistent logic: The analyzer now uses the exact same type extraction logic as the source generator, ensuring consistency
  • Backward compatibility: Proper fallback to attribute's own type arguments maintains compatibility with existing code

Code structure:

  • Clean separation of concerns in CheckDataGenerator method at TestDataAnalyzer.cs:811-825
  • Well-organized helper constants in WellKnown.cs:38

Potential Bugs/Issues ✅

No bugs identified. The implementation correctly:

  • Uses AllInterfaces.FirstOrDefault() with proper type checking
  • Handles the fallback case appropriately
  • Maintains existing error reporting logic
  • Preserves all original validation behavior

Edge cases handled:

  • Empty type arguments scenarios
  • Missing interface implementations
  • Backward compatibility with non-interface implementations

Performance Considerations ✅

Performance is maintained or improved:

  • Interface lookup via AllInterfaces.FirstOrDefault() is more efficient than iterating through base type hierarchies
  • Reduced string operations compared to the old metadataName?.Contains() approach
  • Single interface lookup replaces multiple base type iterations

No performance regressions introduced.

Security Concerns ✅

No security issues identified.

  • No exposure of sensitive data
  • No unsafe operations
  • Proper type safety maintained through interface contracts

Test Coverage ✅

Comprehensive test coverage added:

  1. Happy path test (Custom_DataSourceGenerator_With_Wrapper_Type_No_Error, lines 34-79):

  2. Error case test (Custom_DataSourceGenerator_With_Type_Mismatch_Shows_Error, lines 81-116):

    • Ensures legitimate type mismatches still produce TUnit0001 errors
    • Tests analyzer still catches real problems
    • Validates error reporting accuracy

Test quality:

  • Clear documentation explaining expected behavior
  • Real-world scenario reproduction
  • Both positive and negative test cases
  • Proper diagnostic expectation syntax ({|TUnit0001:value|})

Specific Technical Review

Key change in TestDataAnalyzer.cs:815-820:

if (attribute.AttributeClass?.AllInterfaces.FirstOrDefault(x => x.IsGenericType && 
        x.ConstructedFrom.GloballyQualified() == WellKnown.AttributeFullyQualifiedClasses.ITypedDataSourceAttribute.WithGlobalPrefix + "`1") 
    is { } typedDataSourceInterface)
{
    typeArguments = typedDataSourceInterface.TypeArguments;
}

This correctly:

  • Searches all interfaces of the attribute class
  • Matches against the generic ITypedDataSourceAttribute<T> interface
  • Extracts type arguments from the interface (not the attribute's own parameters)
  • Uses proper null-conditional operators and pattern matching

Overall Assessment

This is an excellent fix that:

  1. ✅ Solves the reported false positive issue
  2. ✅ Maintains backward compatibility
  3. ✅ Improves robustness and consistency
  4. ✅ Includes comprehensive tests
  5. ✅ Follows good software engineering practices

Recommendation: Approve and merge. The implementation is solid, well-tested, and addresses the root cause effectively.


@thomhurst
Copy link
Owner

@copilot The analyzer tests need fixing

…roach and update test expectations

Co-authored-by: thomhurst <[email protected]>
Copy link
Contributor Author

Copilot AI commented Aug 6, 2025

@copilot The analyzer tests need fixing

Fixed! The analyzer tests were failing due to missing using System; statements and incorrect test expectations. The analyzer now correctly uses the ITypedDataSourceAttribute<T> interface approach with proper fallback logic, and all 279 tests are passing. Commit: a9b4d7f

Copilot AI changed the title Fix TUnit0001 false positive for custom ITypedDataSourceAttribute implementations Fix TUnit0001 analyzer to use ITypedDataSourceAttribute interface detection Aug 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TUnit0001 after updating from 0.25 to 0.52.25

2 participants