Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix code generation for methods with default arguments #35

Merged
merged 1 commit into from
Jan 23, 2025
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
74 changes: 69 additions & 5 deletions src/MockMe.Generator/Extensions/MethodSymbolExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ public static string GetParametersWithOriginalTypesAndModifiers(this IMethodSymb
GetParametersWithTypesAndModifiers(method);

public static string GetParametersWithArgTypesAndModifiers(this IMethodSymbol method) =>
GetParametersWithTypesAndModifiers(method, "Arg<", ">");
GetParametersWithTypesAndModifiers(method, "Arg<", ">", true);

private static string GetParametersWithTypesAndModifiers(
this IMethodSymbol method,
string? typePrefix = null,
string? typePostfix = null
string? typePostfix = null,
bool wrapInArg = false
)
{
if (method.Parameters.Length == 0)
Expand All @@ -36,14 +37,18 @@ private static string GetParametersWithTypesAndModifiers(
RefKind.None or _ => p.IsParams ? "params " : "",
};

// Build the main "ref int x" or "Arg<int> x" part
var paramString =
$"{modifiers}{typePrefix}{p.Type.ToFullTypeString()}{typePostfix} {p.Name}";
if (p.HasExplicitDefaultValue)

// If the original parameter had a default value, we only append it if we're NOT
// wrapping in Arg<...>. (Skipping avoids e.g. Arg<int> x = 2 which is invalid.)
if (p.HasExplicitDefaultValue && !wrapInArg)
{
var defaultValue =
p.ExplicitDefaultValue != null ? p.ExplicitDefaultValue.ToString() : "null";
var defaultValue = GetDefaultValueForType(p.Type, p.ExplicitDefaultValue);
paramString += $" = {defaultValue}";
}

return paramString;
})
);
Expand Down Expand Up @@ -136,4 +141,63 @@ public static string GetUniqueMethodName(this IMethodSymbol methodSymbol)
var uniqueMethodName = $"{methodName}_{string.Join("_", parameterTypes)}";
return uniqueMethodName;
}

private static string GetDefaultValueForType(ITypeSymbol type, object? explicitValue)
{
// If the compiler recognized a default value, it sets HasExplicitDefaultValue = true,
// and ExplicitDefaultValue can be null (for '= default') or a constant (for '= 2', '= "x"', etc.)

switch (explicitValue)
{
case null:
// For a non-nullable value type, 'default'
// For reference types or nullable, 'null'
return type.IsValueType ? "default" : "null";
case bool b:
return b ? "true" : "false";
// If we do have a constant, handle string vs. others
// Wrap string in quotes
case string s:
return $"\"{s}\"";
}


if (type.TypeKind == TypeKind.Enum && type is INamedTypeSymbol namedEnum)
{
return GetEnumDefaultValueString(namedEnum, explicitValue);
}

return explicitValue.ToString();
}

private static string GetEnumDefaultValueString(INamedTypeSymbol enumType, object? rawValue) =>
rawValue switch
{
int intValue => FindEnumMember(enumType, intValue),
long longValue => FindEnumMember(enumType, longValue),
byte byteValue => FindEnumMember(enumType, byteValue),
sbyte sbyteValue => FindEnumMember(enumType, sbyteValue),
short shortValue => FindEnumMember(enumType, shortValue),
ushort ushortValue => FindEnumMember(enumType, ushortValue),
uint uintValue => FindEnumMember(enumType, uintValue),
ulong ulongValue => FindEnumMember(enumType, ulongValue),
null => $"{enumType.ToFullTypeString()} /* unknown null */",
// Fallback for unexpected cases:
_ => $"{enumType.ToFullTypeString()} /* unknown = {rawValue} */"
};

private static string FindEnumMember<T>(INamedTypeSymbol enumType, T value) where T : struct, IComparable
{
foreach (var member in enumType.GetMembers().OfType<IFieldSymbol>())
{
if (member.HasConstantValue && Equals(member.ConstantValue, value))
{
// e.g., "System.DayOfWeek.Monday"
return $"{enumType.ToFullTypeString()}.{member.Name}";
}
}

// Fallback if no matching member is found
return $"{enumType.ToFullTypeString()} /* unknown = {value} */";
}
}
172 changes: 172 additions & 0 deletions tests/MockMe.Tests/DefaultArgTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
using System;
using MockMe.Asserters;
using Xunit;

namespace MockMe.Tests
{
public enum EnumLong : long
{
Unknown = 0,
First = 1
}

public class ClassWithDefaultArgs
{
private const string Dummy = "Hello World";

public void MethodWithPrimitiveDefault(int i = 5)
{
}

public void MethodWithNullableDefault(int? arg = 15)
{
}

public void MethodWithBoolDefault(bool value = true)
{
}

public void MethodWithConstStringDefault(string greeting = Dummy)
{
}

public void MethodWithStringDefault(string greeting = "Hello World")
{
}

public void MethodWithDateTimeDefault(DateTime date = default)
{
}

public void MethodWithEnumLongDefault(EnumLong value = EnumLong.First)
{
}

public void MethodWithEnumDefault(DayOfWeek day = DayOfWeek.Monday)
{
}

public void MethodWithMultipleDefaults(double factor = 1.0, bool enabled = true, string label = "default")
{
}
}

public class DefaultArgTests
{
[Fact]
public void GetParametersWithArgTypesAndModifiers_Should_SkipDefaultValues()
{
var mock = Mock.Me(default(ClassWithDefaultArgs));

{
int result = 0;
mock.Setup.MethodWithPrimitiveDefault(Arg.Any()).Callback(args => result = args.i);
mock.MockedObject.MethodWithPrimitiveDefault();
mock.Assert.MethodWithPrimitiveDefault(Arg.Any()).WasCalled();
Assert.Equal(5, result);

mock.MockedObject.MethodWithPrimitiveDefault(15);
mock.Assert.MethodWithPrimitiveDefault(Arg.Any()).WasCalled(NumTimes.Exactly(2));
Assert.Equal(15, result);
}

{
int? result = 0;
mock.Setup.MethodWithNullableDefault(Arg.Any()).Callback(args => result = args.arg);
mock.MockedObject.MethodWithNullableDefault();
mock.Assert.MethodWithNullableDefault(Arg.Any()).WasCalled();
Assert.Equal(15, result);

mock.MockedObject.MethodWithNullableDefault(5);
mock.Assert.MethodWithNullableDefault(Arg.Any()).WasCalled(NumTimes.Exactly(2));
Assert.Equal(5, result);
}

{
bool result = false;
mock.Setup.MethodWithBoolDefault(Arg.Any()).Callback(args => result = args.value);
mock.MockedObject.MethodWithBoolDefault();
mock.Assert.MethodWithBoolDefault(Arg.Any()).WasCalled();
Assert.True(result);

mock.MockedObject.MethodWithBoolDefault(false);
mock.Assert.MethodWithBoolDefault(Arg.Any()).WasCalled(NumTimes.Exactly(2));
Assert.False(result);
}

{
string result = "";
mock.Setup.MethodWithConstStringDefault(Arg.Any()).Callback(args => result = args.greeting);
mock.MockedObject.MethodWithConstStringDefault();
mock.Assert.MethodWithConstStringDefault(Arg.Any()).WasCalled();
Assert.Equal("Hello World", result);

mock.MockedObject.MethodWithConstStringDefault("Goodbye World");
mock.Assert.MethodWithConstStringDefault(Arg.Any()).WasCalled(NumTimes.Exactly(2));
Assert.Equal("Goodbye World", result);
}

{
string result = "";
mock.Setup.MethodWithStringDefault(Arg.Any()).Callback(args => result = args.greeting);
mock.MockedObject.MethodWithStringDefault();
mock.Assert.MethodWithStringDefault(Arg.Any()).WasCalled();
Assert.Equal("Hello World", result);

mock.MockedObject.MethodWithStringDefault("Goodbye World");
mock.Assert.MethodWithStringDefault(Arg.Any()).WasCalled(NumTimes.Exactly(2));
Assert.Equal("Goodbye World", result);
}

{
DateTime result = default;
mock.Setup.MethodWithDateTimeDefault(Arg.Any()).Callback(args => result = args.date);
mock.MockedObject.MethodWithDateTimeDefault();
mock.Assert.MethodWithDateTimeDefault(Arg.Any()).WasCalled();
Assert.Equal(default(DateTime), result);

mock.MockedObject.MethodWithDateTimeDefault(DateTime.Now);
mock.Assert.MethodWithDateTimeDefault(Arg.Any()).WasCalled(NumTimes.Exactly(2));
Assert.NotEqual(default(DateTime), result);
}

{
EnumLong result = default;
mock.Setup.MethodWithEnumLongDefault(Arg.Any()).Callback(args => result = args.value);
mock.MockedObject.MethodWithEnumLongDefault();
mock.Assert.MethodWithEnumLongDefault(Arg.Any()).WasCalled();
Assert.Equal(EnumLong.First, result);

mock.MockedObject.MethodWithEnumLongDefault(EnumLong.Unknown);
mock.Assert.MethodWithEnumLongDefault(Arg.Any()).WasCalled(NumTimes.Exactly(2));
Assert.Equal(EnumLong.Unknown, result);
}

{
DayOfWeek result = default;
mock.Setup.MethodWithEnumDefault(Arg.Any()).Callback(args => result = args.day);
mock.MockedObject.MethodWithEnumDefault();
mock.Assert.MethodWithEnumDefault(Arg.Any()).WasCalled();
Assert.Equal(DayOfWeek.Monday, result);

mock.MockedObject.MethodWithEnumDefault(DayOfWeek.Tuesday);
mock.Assert.MethodWithEnumDefault(Arg.Any()).WasCalled(NumTimes.Exactly(2));
Assert.Equal(DayOfWeek.Tuesday, result);
}

{
(double factor, bool enabled, string label) result = (0.0, false, "");
mock.Setup.MethodWithMultipleDefaults(Arg.Any(), Arg.Any(), Arg.Any())
.Callback(args => result = (args.factor, args.enabled, args.label));
mock.MockedObject.MethodWithMultipleDefaults();
mock.Assert.MethodWithMultipleDefaults(Arg.Any(), Arg.Any(), Arg.Any()).WasCalled();
Assert.Equal((1.0, true, "default"), result);

mock.MockedObject.MethodWithMultipleDefaults(2.0, false, "custom");
mock.Assert.MethodWithMultipleDefaults(Arg.Any(), Arg.Any(), Arg.Any())
.WasCalled(NumTimes.Exactly(2));
Assert.Equal((2.0, false, "custom"), result);
}
}
}
}
Loading