GFramework/GFramework.SourceGenerators.Tests/rule/ContextAwareGeneratorTests.cs
GeWuYou 40a9b523f5 feat(rule): 添加上下文感知诊断规则
- 新增 GF_Rule_001 诊断规则,要求类必须实现 IContextAware 接口
- 创建 ContextAwareDiagnostic 类定义诊断规则元数据
- 修改 ContextAwareGenerator 实现 IContextAware 接口检查
- 优化生成器代码结构,添加候选类查找和输出生成功能
- 更新 AnalyzerReleases.Unshipped.md 文档
- 调整测试代码以适配新的诊断规则
- 修复日志诊断规则的命名空间大小写错误
2025-12-27 13:04:01 +08:00

74 lines
2.9 KiB
C#

using GFramework.SourceGenerators.rule;
using GFramework.SourceGenerators.Tests.core;
using NUnit.Framework;
namespace GFramework.SourceGenerators.Tests.rule;
/// <summary>
/// 测试ContextAwareGenerator源代码生成器的功能
/// </summary>
[TestFixture]
public class ContextAwareGeneratorTests
{
/// <summary>
/// 测试ContextAware代码生成功能
/// 验证当使用[ContextAware]特性标记的类能够正确生成上下文感知的相关代码
/// </summary>
/// <returns>异步任务</returns>
[Test]
public async Task Generates_ContextAware_Code()
{
// 定义输入源代码,包含使用[ContextAware]特性的部分类
const string source = """
using System;
namespace GFramework.SourceGenerators.Attributes.rule
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class ContextAwareAttribute : Attribute
{
}
}
namespace TestApp
{
using GFramework.SourceGenerators.Attributes.rule;
[ContextAware]
public partial class MyRule
{
}
}
""";
const string frameworkStub = """
namespace GFramework.Core.architecture
{
public interface IArchitectureContext {}
}
""";
// 定义期望的生成结果代码
const string expected = """
// <auto-generated/>
#nullable enable
namespace TestApp;
partial class MyRule
{
protected GFramework.Core.architecture.IArchitectureContext Context { get; private set; } = null!;
void GFramework.Core.rule.IContextAware.SetContext(
GFramework.Core.architecture.IArchitectureContext context)
{
Context = context;
}
}
""";
// 执行源代码生成器测试
await GeneratorTest<ContextAwareGenerator>.RunAsync(
source + "\n" + frameworkStub,
("MyRule.ContextAware.g.cs", expected)
);
}
}