soenneker / soenneker.utils.autobogus

The .NET Autogenerator
https://soenneker.com
MIT License
39 stars 4 forks source link

AutoFaker.Generate<T> on delegate-based types causes EngineExecutionException #380

Closed sergey-rybalkin closed 1 week ago

sergey-rybalkin commented 1 week ago

Actual Behavior

Calling AutoFaker.Generate<T> on types like Action<...> and Func<...> either directly or indirectly (e.g. target type has public property of type Action<int>) causes the whole program to crash with EngineExecutionException.

Sample code:

AutoFaker generator = new();
generator.Generate<Action>();

The problem seems to be that autobogus is calling private delegate constructor with randomly generated method pointer. However, setting public reflection flags doesn't seem to be a workaround as this constructor for some reason is reported as public by reflection API. So the following code also crashes:

AutoFaker generator = new()
{
    Config =
    {
        ReflectionCacheOptions = new ReflectionCacheOptions()
        {
            ConstructorFlags = BindingFlags.Public | BindingFlags.Instance,
            MethodFlags = BindingFlags.Public | BindingFlags.Instance,
        }
    }
};
generator.Generate<Action>();

Expected Behavior

Probably I'm missing some autofaker configuration settings, but it seems like the best way of doing this is to have some special handling for delegates by either ignoring them or assigning empty methods.

soenneker commented 1 week ago

@sergey-rybalkin should be fixed in 0ea1232380e803f9480800605edc21f18c14e5c6

We're now skipping any delegate creation of 'top level' types (i.e. .Generate<Action>()). 'Second level' types (i.e. Actions within classes) were already being skipped.