Skip to content

Commit bf4d129

Browse files
committed
add support for generating expected value from field, method or property
1 parent a9fe4ad commit bf4d129

File tree

1 file changed

+25
-2
lines changed
  • tests/Smdn.Reflection.ReverseGenerating/Smdn.Reflection.ReverseGenerating

1 file changed

+25
-2
lines changed

tests/Smdn.Reflection.ReverseGenerating/Smdn.Reflection.ReverseGenerating/Generator.cs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@
1010
namespace Smdn.Reflection.ReverseGenerating;
1111

1212
public abstract class GeneratorTestCaseAttribute : Attribute {
13-
public string Expected { get; private set; }
13+
private readonly string expectedValue;
14+
public Type ExpectedValueGeneratorType { get; set; } = null;
15+
public string ExpectedValueGeneratorMemberName { get; set; } = null;
1416
public bool TranslateLanguagePrimitiveTypeDeclaration { get; set; } = true;
1517
public bool MemberWithNamespace { get; set; } = true;
1618
public bool MemberWithDeclaringTypeName { get; set; } = false;
@@ -29,13 +31,34 @@ public abstract class GeneratorTestCaseAttribute : Attribute {
2931
public MethodBodyOption MethodBody { get; set; } = MethodBodyOption.EmptyImplementation;
3032
public string SourceLocation { get; }
3133

34+
public string Expected {
35+
get {
36+
if (ExpectedValueGeneratorType is null && ExpectedValueGeneratorMemberName is null)
37+
return expectedValue;
38+
39+
var expectedValueGeneratorMember = ExpectedValueGeneratorType.GetMember(
40+
ExpectedValueGeneratorMemberName,
41+
MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
42+
BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic
43+
).FirstOrDefault();
44+
45+
return expectedValueGeneratorMember switch {
46+
FieldInfo f => (string)f.GetValue(obj: null),
47+
MethodInfo m => (string)m.Invoke(obj: null, parameters: null),
48+
PropertyInfo p => (string)p.GetGetMethod(nonPublic: true)?.Invoke(obj: null, parameters: null),
49+
null => throw new InvalidOperationException($"member not found: {ExpectedValueGeneratorType.FullName}.{ExpectedValueGeneratorMemberName}"),
50+
_ => throw new InvalidOperationException($"invalid member type: {ExpectedValueGeneratorType.FullName}.{ExpectedValueGeneratorMemberName}"),
51+
};
52+
}
53+
}
54+
3255
public GeneratorTestCaseAttribute(
3356
string expected,
3457
string sourceFilePath,
3558
int lineNumber
3659
)
3760
{
38-
this.Expected = expected;
61+
this.expectedValue = expected;
3962
this.SourceLocation = $"{Path.GetFileName(sourceFilePath)}:{lineNumber}";
4063
}
4164
}

0 commit comments

Comments
 (0)