// // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // namespace ImageSharp.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; /// /// Triggers passing instances which read an image for each file being enumerated by the (static) test class field/property defined by enumeratorMemberName /// instances will be passed for each the pixel format defined by the pixelTypes parameter /// public class WithFileCollectionAttribute : ImageDataAttributeBase { private readonly string enumeratorMemberName; /// /// Triggers passing instances which read an image for each file being enumerated by the (static) test class field/property defined by enumeratorMemberName /// instances will be passed for each the pixel format defined by the pixelTypes parameter /// /// The name of the static test class field/property enumerating the files /// The requested pixel types /// Additional theory parameter values public WithFileCollectionAttribute( string enumeratorMemberName, PixelTypes pixelTypes, params object[] additionalParameters) : base(pixelTypes, additionalParameters) { this.enumeratorMemberName = enumeratorMemberName; } protected override IEnumerable GetAllFactoryMethodArgs(MethodInfo testMethod, Type factoryType) { Func accessor = this.GetPropertyAccessor(testMethod.DeclaringType); accessor = accessor ?? this.GetFieldAccessor(testMethod.DeclaringType); IEnumerable files = (IEnumerable)accessor(); return files.Select(f => new object[] { f }); } protected override string GetFactoryMethodName(MethodInfo testMethod) => "File"; /// /// Based on MemberData implementation /// private Func GetFieldAccessor(Type type) { FieldInfo fieldInfo = null; for (Type reflectionType = type; reflectionType != null; reflectionType = reflectionType.GetTypeInfo().BaseType) { fieldInfo = reflectionType.GetRuntimeField(this.enumeratorMemberName); if (fieldInfo != null) break; } if (fieldInfo == null || !fieldInfo.IsStatic) return null; return () => fieldInfo.GetValue(null); } /// /// Based on MemberData implementation /// private Func GetPropertyAccessor(Type type) { PropertyInfo propInfo = null; for (Type reflectionType = type; reflectionType != null; reflectionType = reflectionType.GetTypeInfo().BaseType) { propInfo = reflectionType.GetRuntimeProperty(this.enumeratorMemberName); if (propInfo != null) break; } if (propInfo == null || propInfo.GetMethod == null || !propInfo.GetMethod.IsStatic) return null; return () => propInfo.GetValue(null, null); } } }