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
@@ -1,6 +1,5 @@
using System;
using System.IO;
using System.Linq;
using GFramework.Game.Abstractions.Config;
using GFramework.Game.Config;
using GFramework.Game.Config.Generated;

Expand Down Expand Up @@ -88,7 +87,8 @@ public async Task LoadAsync_Should_Support_Generated_Bindings_In_Consumer_Projec
Assert.That(monsterTable.Get(1).Name, Is.EqualTo("Slime"));
Assert.That(monsterTable.Get(2).Hp, Is.EqualTo(30));
Assert.That(monsterTable.FindByName("Slime").Select(static config => config.Id), Is.EqualTo(new[] { 1 }));
Assert.That(dungeonMonsters.Select(static config => config.Name), Is.EquivalentTo(new[] { "Slime", "Goblin" }));
Assert.That(dungeonMonsters.Select(static config => config.Name),
Is.EquivalentTo(new[] { "Slime", "Goblin" }));
Assert.That(monsterTable.TryFindFirstByName("Goblin", out var goblin), Is.True);
Assert.That(goblin, Is.Not.Null);
Assert.That(goblin!.Id, Is.EqualTo(2));
Expand Down Expand Up @@ -154,10 +154,13 @@ public void GeneratedConfigCatalog_Should_Expose_Domain_And_Registration_Diagnos
Is.EqualTo(new[] { MonsterConfigBindings.TableName }));
Assert.That(GeneratedConfigCatalog.GetTablesForRegistration().Select(static metadata => metadata.TableName),
Is.SupersetOf(new[] { ItemConfigBindings.TableName, MonsterConfigBindings.TableName }));
Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, monsterOnlyOptions), Is.True);
Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, monsterOnlyOptions),
Is.True);
Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(itemMetadata, monsterOnlyOptions), Is.False);
Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, predicateOnlyOptions), Is.True);
Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(itemMetadata, predicateOnlyOptions), Is.False);
Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, predicateOnlyOptions),
Is.True);
Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(itemMetadata, predicateOnlyOptions),
Is.False);
Assert.That(GeneratedConfigCatalog.MatchesRegistrationOptions(monsterMetadata, options: null), Is.True);
});
}
Expand Down Expand Up @@ -232,6 +235,66 @@ public async Task RegisterAllGeneratedConfigTables_Should_Support_Filtering_By_D
});
}

/// <summary>
/// 验证生成绑定会同时暴露 YAML 序列化、schema 路径解析与文本校验入口。
/// </summary>
[Test]
public async Task GeneratedBindings_Should_Expose_Serializer_And_Validator_Helpers()
{
CreateMonsterFiles();

var config = new MonsterConfig
{
Id = 3,
Name = "Bat",
Hp = 12,
Faction = "cave"
};

var yaml = MonsterConfigBindings.SerializeToYaml(config);
var schemaPath = MonsterConfigBindings.GetSchemaPath(_rootPath);
var configDirectoryPath = MonsterConfigBindings.GetConfigDirectoryPath(_rootPath);

Assert.Multiple(() =>
{
Assert.That(schemaPath, Is.EqualTo(Path.Combine(_rootPath, "schemas", "monster.schema.json")));
Assert.That(configDirectoryPath, Is.EqualTo(Path.Combine(_rootPath, "monster")));
Assert.That(yaml, Does.Contain("id: 3"));
Assert.That(yaml, Does.Contain("name: Bat"));
Assert.That(yaml, Does.Contain("hp: 12"));
Assert.That(yaml, Does.Contain("faction: cave"));
Assert.That(yaml.EndsWith("\n", StringComparison.Ordinal), Is.True);
});

Assert.DoesNotThrow(() =>
MonsterConfigBindings.ValidateYaml(_rootPath, "monster/generated.yaml", yaml));

Assert.DoesNotThrowAsync(async () =>
await MonsterConfigBindings.ValidateYamlAsync(_rootPath, "monster/generated.yaml", yaml));
Comment thread
GeWuYou marked this conversation as resolved.

var invalidYaml = """
id: 3
name: Bat
hp: 12
unknownField: true
""";

var exception = Assert.Throws<ConfigLoadException>(() =>
MonsterConfigBindings.ValidateYaml(_rootPath, "monster/generated.yaml", invalidYaml));
var asyncException = Assert.ThrowsAsync<ConfigLoadException>(async () =>
await MonsterConfigBindings.ValidateYamlAsync(_rootPath, "monster/generated.yaml", invalidYaml));

Assert.Multiple(() =>
{
Assert.That(exception, Is.Not.Null);
Assert.That(exception!.Diagnostic.SchemaPath, Is.EqualTo(schemaPath));
Assert.That(exception.Diagnostic.FailureKind, Is.EqualTo(ConfigLoadFailureKind.UnknownProperty));
Assert.That(asyncException, Is.Not.Null);
Assert.That(asyncException!.Diagnostic.SchemaPath, Is.EqualTo(schemaPath));
Assert.That(asyncException.Diagnostic.FailureKind, Is.EqualTo(ConfigLoadFailureKind.UnknownProperty));
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

/// <summary>
/// 在临时消费者根目录中创建测试文件。
/// </summary>
Expand Down
93 changes: 93 additions & 0 deletions GFramework.Game.Tests/Config/YamlConfigSchemaValidatorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using System.IO;
using GFramework.Game.Config;

namespace GFramework.Game.Tests.Config;

/// <summary>
/// 验证内部 schema 解析器会输出稳定且可预期的运行时依赖元数据。
/// </summary>
[TestFixture]
public sealed class YamlConfigSchemaValidatorTests
{
private string _rootPath = null!;

/// <summary>
/// 为每个测试准备独立临时目录。
/// </summary>
[SetUp]
public void SetUp()
{
_rootPath = Path.Combine(Path.GetTempPath(), "GFramework.SchemaValidatorTests", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_rootPath);
}

/// <summary>
/// 清理测试临时目录。
/// </summary>
[TearDown]
public void TearDown()
{
if (Directory.Exists(_rootPath))
{
Directory.Delete(_rootPath, true);
}
}

/// <summary>
/// 验证 schema 中声明的跨表引用名称会以序数排序形式输出,
/// 避免热重载依赖推导与测试快照受哈希集合枚举顺序影响。
/// </summary>
[Test]
public void Load_Should_Return_Referenced_Table_Names_In_Ordinal_Sorted_Order()
{
var schemaPath = CreateSchemaFile(
"schemas/monster.schema.json",
"""
{
"type": "object",
"properties": {
"weaponId": {
"type": "string",
"x-gframework-ref-table": "weapon"
},
"allies": {
"type": "array",
"items": {
"type": "integer",
"x-gframework-ref-table": "ally"
}
},
"itemId": {
"type": "string",
"x-gframework-ref-table": "item"
}
}
}
""");

var schema = YamlConfigSchemaValidator.Load("monster", schemaPath);

Assert.That(schema.ReferencedTableNames, Is.EqualTo(new[] { "ally", "item", "weapon" }));
}

/// <summary>
/// 在临时目录中创建 schema 文件。
/// </summary>
/// <param name="relativePath">相对根目录的路径。</param>
/// <param name="content">文件内容。</param>
/// <returns>写入后的绝对路径。</returns>
private string CreateSchemaFile(
string relativePath,
string content)
{
var fullPath = Path.Combine(_rootPath, relativePath.Replace('/', Path.DirectorySeparatorChar));
var directoryPath = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrWhiteSpace(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}

File.WriteAllText(fullPath, content.Replace("\n", Environment.NewLine, StringComparison.Ordinal));
return fullPath;
}
}
60 changes: 60 additions & 0 deletions GFramework.Game.Tests/Config/YamlConfigTextSerializerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using GFramework.Game.Config;

namespace GFramework.Game.Tests.Config;

/// <summary>
/// 验证公开 YAML 文本序列化入口的换行与参数契约。
/// </summary>
[TestFixture]
public sealed class YamlConfigTextSerializerTests
{
/// <summary>
/// 验证序列化结果会稳定地以 LF 作为尾随换行,
/// 避免不同宿主平台的行尾约定影响生成内容。
/// </summary>
[Test]
public void Serialize_Should_Use_Trailing_Lf_Newline()
{
var yaml = YamlConfigTextSerializer.Serialize(new MonsterYamlStub
{
Id = 1,
Name = "Slime"
});

Assert.Multiple(() =>
{
Assert.That(yaml, Does.Contain("id: 1"));
Assert.That(yaml, Does.Contain("name: Slime"));
Assert.That(yaml.EndsWith("\n", StringComparison.Ordinal), Is.True);
Assert.That(yaml.EndsWith("\r\n", StringComparison.Ordinal), Is.False);
});
}

/// <summary>
/// 验证空对象引用会继续通过参数异常暴露给调用方。
/// </summary>
[Test]
public void Serialize_Should_Throw_When_Value_Is_Null()
{
var exception = Assert.Throws<ArgumentNullException>(() =>
YamlConfigTextSerializer.Serialize<MonsterYamlStub>(null!));

Assert.That(exception!.ParamName, Is.EqualTo("value"));
}

/// <summary>
/// 用于 YAML 序列化测试的最小配置对象。
/// </summary>
private sealed class MonsterYamlStub
{
/// <summary>
/// 获取或设置配置标识。
/// </summary>
public int Id { get; init; }

/// <summary>
/// 获取或设置配置名称。
/// </summary>
public string Name { get; init; } = string.Empty;
}
}
Loading
Loading