diff --git a/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs b/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs index 226672aa717a0..16f8c060186e3 100644 --- a/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs +++ b/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs @@ -2,21 +2,35 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections; using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; using Xunit; namespace System.Reflection.Tests { public class RuntimeReflectionExtensionsTests { + [Fact] + public void GetRuntimeEvents() + { + AssertExtensions.Throws("type", () => default(Type).GetRuntimeEvents()); + + List events = typeof(TestType).GetRuntimeEvents().ToList(); + Assert.Equal(1, events.Count); + Assert.Equal("StuffHappened", events[0].Name); + } + [Fact] public void GetRuntimeMethods() { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeMethods(null); + RuntimeReflectionExtensions.GetRuntimeMethods(default(Type)); }); @@ -52,9 +66,9 @@ public void GetRuntimeFields() { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeFields(null); + RuntimeReflectionExtensions.GetRuntimeFields(default(Type)); }); List fields = new List(); @@ -75,23 +89,37 @@ public void GetRuntimeFields() } } + [Fact] + public void GetRuntimeProperties() + { + AssertExtensions.Throws("type", () => default(Type).GetRuntimeProperties()); + + List properties = typeof(TestType).GetRuntimeProperties().ToList(); + List propertyNames = properties.Select(p => p.Name).Distinct().ToList(); + Assert.Equal(5, properties.Count); + Assert.Contains("Length", propertyNames); + Assert.Contains("Position", propertyNames); + Assert.Contains("CanRead", propertyNames); + Assert.Contains("CanWrite", propertyNames); + Assert.Contains("CanSeek", propertyNames); + } + [Fact] public void GetRuntimeProperty() { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeProperty(null, "foo"); + RuntimeReflectionExtensions.GetRuntimeProperty(default(Type), "foo"); }); - - - Assert.Throws(() => + AssertExtensions.Throws("name", () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeProperty(null); }); + Assert.Null(typeof(TestType).GetRuntimeProperty("")); List properties = new List(); @@ -122,6 +150,8 @@ public void GetRuntimeProperty() } } } + + Assert.Equal(typeof(TestType).GetProperty("Length"), typeof(TestType).GetRuntimeProperty("Length")); } [Fact] @@ -129,17 +159,19 @@ public void GetRuntimeEvent() { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeEvent(null, "foo"); + RuntimeReflectionExtensions.GetRuntimeEvent(default(Type), "foo"); }); - Assert.Throws(() => + Assert.Throws(null, () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeEvent(null); }); + Assert.Null(typeof(TestType).GetRuntimeEvent("")); + List events = new List(); foreach (TypeInfo type in types) @@ -158,6 +190,8 @@ public void GetRuntimeEvent() Assert.NotNull(type.AsType().GetRuntimeEvent(eventName)); } } + + Assert.Equal(typeof(TestType).GetEvent("StuffHappened"), typeof(TestType).GetRuntimeEvent("StuffHappened")); } [Fact] @@ -165,23 +199,25 @@ public void GetRuntimeMethod() { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeMethod(null, "foo", new Type[0]); + RuntimeReflectionExtensions.GetRuntimeMethod(default(Type), "foo", Type.EmptyTypes); }); - Assert.Throws(() => + AssertExtensions.Throws("name", () => { - typeof(RuntimeReflectionExtensionsTests).GetRuntimeMethod(null, new Type[0]); + typeof(RuntimeReflectionExtensionsTests).GetRuntimeMethod(null, Type.EmptyTypes); }); - Assert.Throws(() => + AssertExtensions.Throws("types", () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeMethod("RunTest_GetRuntimeMethod", null); }); + Assert.Null(typeof(TestType).GetRuntimeMethod("", Type.EmptyTypes)); + List methods = new List(); foreach (TypeInfo type in types) @@ -199,6 +235,8 @@ public void GetRuntimeMethod() Assert.NotNull(type.AsType().GetRuntimeMethod(methodName, parameters)); } } + + Assert.Equal(typeof(TestType).GetMethod("Flush"), typeof(TestType).GetRuntimeMethod("Flush", Array.Empty())); } [Fact] @@ -206,17 +244,19 @@ public void GetRuntimeField() { var types = GetTypes(); - Assert.Throws(() => + AssertExtensions.Throws("type", () => { - RuntimeReflectionExtensions.GetRuntimeField(null, "foo"); + RuntimeReflectionExtensions.GetRuntimeField(default(Type), "foo"); }); - Assert.Throws(() => + Assert.Throws(null, () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeField(null); }); + Assert.Null(typeof(TestType).GetRuntimeField("")); + List fields = new List(); foreach (TypeInfo type in types) @@ -232,6 +272,49 @@ public void GetRuntimeField() Assert.NotNull(type.AsType().GetRuntimeField(fieldName)); } } + + Assert.Equal(typeof(TestType).GetField("_pizzaSize"), typeof(TestType).GetRuntimeField("_pizzaSize")); + } + + [Fact] + public void GetMethodInfo() + { + AssertExtensions.Throws("del", () => default(Action).GetMethodInfo()); + Assert.Equal(typeof(RuntimeReflectionExtensionsTests).GetMethod("GetMethodInfo"), ((Action)GetMethodInfo).GetMethodInfo()); + } + + [Fact] + public void GetRuntimeBaseDefinition() + { + Assert.Throws(() => default(MethodInfo).GetRuntimeBaseDefinition()); + + MethodInfo derivedFoo = typeof(TestDerived).GetMethod(nameof(TestDerived.Foo)); + MethodInfo baseFoo = typeof(TestBase).GetMethod(nameof(TestBase.Foo)); + MethodInfo actual = derivedFoo.GetRuntimeBaseDefinition(); + Assert.Equal(baseFoo, actual); + } + + [Fact] + public void GetRuntimeInterfaceMap() + { + AssertExtensions.Throws("typeInfo", () => default(TypeInfo).GetRuntimeInterfaceMap(typeof(ICloneable))); + AssertExtensions.Throws("ifaceType", () => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(null)); + Assert.Throws(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(ICloneable))); + Assert.Throws(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(string))); + + InterfaceMapping map = typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(IDisposable)); + Assert.Same(typeof(TestType), map.TargetType); + Assert.Same(typeof(IDisposable), map.InterfaceType); + Assert.Equal(1, map.InterfaceMethods.Length); + Assert.Equal(1, map.TargetMethods.Length); + MethodInfo ifaceDispose = map.InterfaceMethods[0]; + MethodInfo targetDispose = map.TargetMethods[0]; + Assert.Equal(ifaceDispose.CallingConvention, targetDispose.CallingConvention); + Assert.Equal(ifaceDispose.Name, targetDispose.Name); + Assert.Same(ifaceDispose.ReturnType, targetDispose.ReturnType); + Assert.Equal(ifaceDispose.GetParameters().Length, targetDispose.GetParameters().Length); + Assert.Same(typeof(TestTypeBase), targetDispose.DeclaringType); + Assert.Same(typeof(IDisposable), ifaceDispose.DeclaringType); } private static string GetMethodName(string methodName) @@ -255,7 +338,6 @@ private static Type[] GetMethodParameters(string methodName) return parameterList.ToArray(); } - private static TypeInfo[] GetTypes() { Assembly asm = typeof(PropertyTestBaseClass).GetTypeInfo().Assembly; @@ -267,5 +349,125 @@ private static TypeInfo[] GetTypes() } return list.ToArray(); } + + private abstract class TestBase + { + public abstract void Foo(); + } + + private class TestDerived : TestBase + { + public override void Foo() { throw null; } + } + + abstract class TestTypeBase : IDisposable + { + public abstract bool CanRead { get; } + public abstract bool CanWrite { get; } + public abstract bool CanSeek { get; } + public abstract long Length { get; } + public abstract long Position { get; set; } + + public virtual Task FlushAsync() + { + throw null; + } + + public abstract void Flush(); + + public virtual Task ReadAsync(byte[] buffer, int offset, int count) + { + throw null; + } + + public abstract int Read(byte[] buffer, int offset, int count); + + public abstract long Seek(long offset, SeekOrigin origin); + + public abstract void SetLength(long value); + + public abstract void Write(byte[] buffer, int offset, int count); + public virtual Task WriteAsync(byte[] buffer, int offset, int count) + { + throw null; + } + + public void Dispose() + { + throw null; + } + } + + class TestType : TestTypeBase + { + public TestType() + { + } + + public class Nested + { + + } + + #pragma warning disable 0067 // event never used + public event Action StuffHappened; + #pragma warning restore 0067 + + #pragma warning disable 0169 // field never used + private int _pizzaSize; + #pragma warning restore 0169 + + public override bool CanRead => false; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length + { + get + { + throw new NotImplementedException(); + } + } + + public override long Position + { + get + { + throw new NotImplementedException(); + } + + set + { + throw new NotImplementedException(); + } + } + + public override void Flush() + { + throw new NotImplementedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotImplementedException(); + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotImplementedException(); + } + + public override void SetLength(long value) + { + throw new NotImplementedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotImplementedException(); + } + } } } diff --git a/src/libraries/System.Reflection/tests/Configurations.props b/src/libraries/System.Reflection/tests/Configurations.props index c398e42e89942..8b803e0772f2c 100644 --- a/src/libraries/System.Reflection/tests/Configurations.props +++ b/src/libraries/System.Reflection/tests/Configurations.props @@ -2,6 +2,7 @@ + netcoreapp; netstandard; diff --git a/src/libraries/System.Reflection/tests/ConstructorInfoTests.cs b/src/libraries/System.Reflection/tests/ConstructorInfoTests.cs index 5bc838ff53e57..0078386655351 100644 --- a/src/libraries/System.Reflection/tests/ConstructorInfoTests.cs +++ b/src/libraries/System.Reflection/tests/ConstructorInfoTests.cs @@ -38,6 +38,7 @@ public static IEnumerable Equals_TestData() public void Equals(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected) { Assert.Equal(expected, constructorInfo1.Equals(constructorInfo2)); + Assert.NotEqual(expected, constructorInfo1 != constructorInfo2); } [Fact] @@ -146,7 +147,7 @@ public void Invoke_ParameterWrongType_ThrowsArgumentException() [Fact] public void Invoke_ExistingInstance() { - // Should not prouce a second object. + // Should not produce a second object. ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj1 = new ClassWith3Constructors(100, "hello"); ClassWith3Constructors obj2 = (ClassWith3Constructors)constructors[2].Invoke(obj1, new object[] { 999, "initialized" }); diff --git a/src/libraries/System.Reflection/tests/FieldInfoTests.cs b/src/libraries/System.Reflection/tests/FieldInfoTests.cs index 2611c6362e59b..4644f366c21aa 100644 --- a/src/libraries/System.Reflection/tests/FieldInfoTests.cs +++ b/src/libraries/System.Reflection/tests/FieldInfoTests.cs @@ -423,6 +423,16 @@ public static void SetValue_Generic(Type openType, Type gaType, string fieldName Assert.Equal(initialValue, fi.GetValue(obj)); } + [Fact] + public void SecurityAttributes() + { + FieldInfo info = GetField(typeof(FieldInfoTests), nameof(FieldInfoTests.s_intField)); + + Assert.True(info.IsSecurityCritical); + Assert.False(info.IsSecuritySafeCritical); + Assert.False(info.IsSecurityTransparent); + } + private static FieldInfo GetField(Type type, string name) { return type.GetTypeInfo().DeclaredFields.FirstOrDefault(fieldInfo => fieldInfo.Name.Equals(name)); diff --git a/src/libraries/System.Reflection/tests/MemberInfoTests.cs b/src/libraries/System.Reflection/tests/MemberInfoTests.cs index d90d138bbea69..baa72312bb149 100644 --- a/src/libraries/System.Reflection/tests/MemberInfoTests.cs +++ b/src/libraries/System.Reflection/tests/MemberInfoTests.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Runtime.InteropServices; using Xunit; #pragma warning disable 0414 @@ -16,25 +17,246 @@ public class MemberInfoTests [Fact] public void MetadataToken() { - Assert.Equal(GetMembers(typeof(SampleClass)), GetMembers(typeof(SampleClass))); - Assert.Equal(GetMembers(new MemberInfoTests().GetType()), GetMembers(new MemberInfoTests().GetType())); - Assert.Equal(GetMembers(new Dictionary().GetType()), GetMembers(new Dictionary().GetType())); - Assert.Equal(GetMembers(typeof(int)), GetMembers(typeof(int))); - Assert.Equal(GetMembers(typeof(Dictionary<,>)), GetMembers(typeof(Dictionary<,>))); + Assert.Equal(GetMetadataTokens(typeof(SampleClass)), GetMetadataTokens(typeof(SampleClass))); + Assert.Equal(GetMetadataTokens(new MemberInfoTests().GetType()), GetMetadataTokens(new MemberInfoTests().GetType())); + Assert.Equal(GetMetadataTokens(new Dictionary().GetType()), GetMetadataTokens(new Dictionary().GetType())); + Assert.Equal(GetMetadataTokens(typeof(int)), GetMetadataTokens(typeof(int))); + Assert.Equal(GetMetadataTokens(typeof(Dictionary<,>)), GetMetadataTokens(typeof(Dictionary<,>))); } - private IEnumerable GetMembers(Type type) + [Fact] + public void ReflectedType() + { + Type t = typeof(Derived); + MemberInfo[] members = t.GetMembers(); + foreach (MemberInfo member in members) + { + Assert.Equal(t, member.ReflectedType); + } + } + + [Fact] + public void PropertyReflectedType() + { + Type t = typeof(Base); + PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1)); + Assert.Equal(t, p.ReflectedType); + Assert.NotNull(p.GetMethod); + Assert.NotNull(p.SetMethod); + } + + [Fact] + public void InheritedPropertiesHidePrivateAccessorMethods() + { + Type t = typeof(Derived); + PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1)); + Assert.Equal(t, p.ReflectedType); + Assert.NotNull(p.GetMethod); + Assert.Null(p.SetMethod); + } + + [Fact] + public void GenericMethodsInheritTheReflectedTypeOfTheirTemplate() + { + Type t = typeof(Derived); + MethodInfo moo = t.GetMethod("Moo"); + Assert.Equal(t, moo.ReflectedType); + MethodInfo mooInst = moo.MakeGenericMethod(typeof(int)); + Assert.Equal(t, mooInst.ReflectedType); + } + + [Fact] + public void DeclaringMethodOfTypeParametersOfInheritedMethods() + { + Type t = typeof(Derived); + MethodInfo moo = t.GetMethod("Moo"); + Assert.Equal(t, moo.ReflectedType); + Type theM = moo.GetGenericArguments()[0]; + MethodBase moo1 = theM.DeclaringMethod; + Type reflectedTypeOfMoo1 = moo1.ReflectedType; + Assert.Equal(typeof(Base), reflectedTypeOfMoo1); + } + + [Fact] + public void DeclaringMethodOfTypeParametersOfInheritedMethods2() + { + Type t = typeof(GDerived); + MethodInfo moo = t.GetMethod("Moo"); + Assert.Equal(t, moo.ReflectedType); + Type theM = moo.GetGenericArguments()[0]; + MethodBase moo1 = theM.DeclaringMethod; + Type reflectedTypeOfMoo1 = moo1.ReflectedType; + Assert.Equal(typeof(GBase<>), reflectedTypeOfMoo1); + } + + [Fact] + public void InheritedPropertyAccessors() + { + Type t = typeof(Derived); + PropertyInfo p = t.GetProperty(nameof(Base.MyProperty)); + MethodInfo getter = p.GetMethod; + MethodInfo setter = p.SetMethod; + Assert.Equal(t, getter.ReflectedType); + Assert.Equal(t, setter.ReflectedType); + } + + [Fact] + public void InheritedEventAccessors() + { + Type t = typeof(Derived); + EventInfo e = t.GetEvent(nameof(Base.MyEvent)); + MethodInfo adder = e.AddMethod; + MethodInfo remover = e.RemoveMethod; + Assert.Equal(t, adder.ReflectedType); + Assert.Equal(t, remover.ReflectedType); + } + + [Fact] + public void ReflectedTypeIsPartOfIdentity() + { + Type b = typeof(Base); + Type d = typeof(Derived); + + { + EventInfo e = b.GetEvent(nameof(Base.MyEvent)); + EventInfo ei = d.GetEvent(nameof(Derived.MyEvent)); + Assert.False(e.Equals(ei)); + } + + { + FieldInfo f = b.GetField(nameof(Base.MyField)); + FieldInfo fi = d.GetField(nameof(Derived.MyField)); + Assert.False(f.Equals(fi)); + } + + { + MethodInfo m = b.GetMethod(nameof(Base.Moo)); + MethodInfo mi = d.GetMethod(nameof(Derived.Moo)); + Assert.False(m.Equals(mi)); + } + + { + PropertyInfo p = b.GetProperty(nameof(Base.MyProperty)); + PropertyInfo pi = d.GetProperty(nameof(Derived.MyProperty)); + Assert.False(p.Equals(pi)); + } + } + + [Fact] + public void FieldInfoReflectedTypeDoesNotSurviveRuntimeHandles() + { + Type t = typeof(Derived); + FieldInfo f = t.GetField(nameof(Base.MyField)); + Assert.Equal(typeof(Derived), f.ReflectedType); + RuntimeFieldHandle h = f.FieldHandle; + FieldInfo f2 = FieldInfo.GetFieldFromHandle(h); + Assert.Equal(typeof(Base), f2.ReflectedType); + } + + [Fact] + public void MethodInfoReflectedTypeDoesNotSurviveRuntimeHandles() + { + Type t = typeof(Derived); + MethodInfo m = t.GetMethod(nameof(Base.Moo)); + Assert.Equal(typeof(Derived), m.ReflectedType); + RuntimeMethodHandle h = m.MethodHandle; + MethodBase m2 = MethodBase.GetMethodFromHandle(h); + Assert.Equal(typeof(Base), m2.ReflectedType); + } + + [Fact] + public void GetCustomAttributesData() + { + MemberInfo[] m = typeof(MemberInfoTests).GetMember("SampleClass"); + Assert.Equal(1, m.Count()); + foreach(CustomAttributeData cad in m[0].GetCustomAttributesData()) + { + if (cad.AttributeType == typeof(ComVisibleAttribute)) + { + ConstructorInfo c = cad.Constructor; + Assert.False(c.IsStatic); + Assert.Equal(typeof(ComVisibleAttribute), c.DeclaringType); + ParameterInfo[] p = c.GetParameters(); + Assert.Equal(1, p.Length); + Assert.Equal(typeof(bool), p[0].ParameterType); + return; + } + } + + Assert.True(false, "Expected to find ComVisibleAttribute"); + } + + public static IEnumerable EqualityOperator_TestData() + { + yield return new object[] { typeof(SampleClass) }; + yield return new object[] { new MemberInfoTests().GetType() }; + yield return new object[] { typeof(int) }; + yield return new object[] { typeof(Dictionary<,>) }; + } + + [Theory] + [MemberData(nameof(EqualityOperator_TestData))] + public void EqualityOperator_Equal_ReturnsTrue(Type type) + { + MemberInfo[] members1 = GetOrderedMembers(type); + MemberInfo[] members2 = GetOrderedMembers(type); + + Assert.Equal(members1.Length, members2.Length); + for (int i = 0; i < members1.Length; i++) + { + Assert.True(members1[i] == members2[i]); + Assert.False(members1[i] != members2[i]); + } + } + + private MemberInfo[] GetMembers(Type type) + { + return type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + } + + private IEnumerable GetMetadataTokens(Type type) { return type.GetTypeInfo().GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Select(m => m.HasMetadataToken() ? m.MetadataToken : 0); } + private MemberInfo[] GetOrderedMembers(Type type) => GetMembers(type).OrderBy(member => member.Name).ToArray(); + + private class Base + { + public event Action MyEvent { add { } remove { } } +#pragma warning disable 0649 + public int MyField; +#pragma warning restore 0649 + public int MyProperty { get; set; } + + public int MyProperty1 { get; private set; } + public int MyProperty2 { private get; set; } + + public void Moo() { } + } + + private class Derived : Base + { + } + + private class GBase + { + public void Moo() { } + } + + private class GDerived : GBase + { + } + +#pragma warning disable 0067, 0169 #pragma warning disable 0067, 0169 + [ComVisible(false)] public class SampleClass { public int PublicField; private int PrivateField; - public SampleClass() { } + public SampleClass(bool y) { } private SampleClass(int x) { } public void PublicMethod() { } diff --git a/src/libraries/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs b/src/libraries/System.Reflection/tests/MemberInfoTests.netcoreapp.cs similarity index 100% rename from src/libraries/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs rename to src/libraries/System.Reflection/tests/MemberInfoTests.netcoreapp.cs diff --git a/src/libraries/System.Reflection/tests/ParameterInfoTests.cs b/src/libraries/System.Reflection/tests/ParameterInfoTests.cs index e9df054b4217f..6eb731574d4b9 100644 --- a/src/libraries/System.Reflection/tests/ParameterInfoTests.cs +++ b/src/libraries/System.Reflection/tests/ParameterInfoTests.cs @@ -5,6 +5,8 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; using Xunit; namespace System.Reflection.Tests @@ -98,6 +100,33 @@ public void RawDefaultValue(Type type, string name, int index) Assert.NotNull(parameterInfo.RawDefaultValue); } + [Fact] + public void RawDefaultValue_Enum() + { + ParameterInfo p = GetParameterInfo(typeof(ParameterInfoMetadata), "Foo1", 0); + object raw = p.RawDefaultValue; + Assert.Equal(typeof(int), raw.GetType()); + Assert.Equal((int)raw, (int)BindingFlags.DeclaredOnly); + } + + [Fact] + public void RawDefaultValueFromAttribute() + { + ParameterInfo p = GetParameterInfo(typeof(ParameterInfoMetadata), "Foo2", 0); + object raw = p.RawDefaultValue; + Assert.Equal(typeof(int), raw.GetType()); + Assert.Equal((int)raw, (int)BindingFlags.IgnoreCase); + } + + [Fact] + public void RawDefaultValue_MetadataTrumpsAttribute() + { + ParameterInfo p = GetParameterInfo(typeof(ParameterInfoMetadata), "Foo3", 0); + object raw = p.RawDefaultValue; + Assert.Equal(typeof(int), raw.GetType()); + Assert.Equal((int)raw, (int)BindingFlags.FlattenHierarchy); + } + [Theory] [InlineData(typeof(ParameterInfoMetadata), "MethodWithRefParameter", 0, false)] [InlineData(typeof(ParameterInfoMetadata), "MethodWithOutParameter", 1, true)] @@ -193,6 +222,27 @@ public void CustomAttributesTest(Type attrType) Assert.True(prov.IsDefined(attrType, true)); } + [Fact] + public void VerifyGetCustomAttributesData() + { + ParameterInfo p = GetParameterInfo(typeof(ParameterInfoMetadata), "MethodWithCustomAttribute", 0); + foreach (CustomAttributeData cad in p.GetCustomAttributesData()) + { + if(cad.AttributeType == typeof(MyAttribute)) + { + ConstructorInfo c = cad.Constructor; + Assert.False(c.IsStatic); + Assert.False(c.IsPublic); + ParameterInfo[] paramInfo = c.GetParameters(); + Assert.Equal(1, paramInfo.Length); + Assert.Equal(typeof(int), paramInfo[0].ParameterType); + return; + } + } + + Assert.True(false, "Expected to find MyAttribute"); + } + public static IEnumerable s_CustomAttributesTestData { get @@ -231,6 +281,47 @@ public void GetRequiredCustomModifiers(Type type, string name, int index, Type[] Assert.Equal(expected, parameterInfo.GetRequiredCustomModifiers()); } + [Theory] + [MemberData(nameof(VerifyParameterInfoGetRealObjectWorks_TestData))] + public void VerifyParameterInfoGetRealObjectWorks(MemberInfo pretendMember, int pretendPosition, string expectedParameterName) + { + // Regression test for https://github.com/dotnet/corefx/issues/20574 + // + // It's easy to forget that ParameterInfo's and runtime-implemented ParameterInfo's are different objects and just because the + // latter doesn't support serialization doesn't mean other providers won't either. + // + // For historical reasons, ParameterInfo contains some serialization support that subtypes can optionally hang off. This + // test ensures that support doesn't get vaporized. + + // Just pretend that we're BinaryFormatter and are deserializing a Parameter... + IObjectReference podParameter = new PodPersonParameterInfo(pretendMember, pretendPosition); + StreamingContext sc = new StreamingContext(StreamingContextStates.Clone); + ParameterInfo result = (ParameterInfo)(podParameter.GetRealObject(sc)); + + Assert.Equal(pretendPosition, result.Position); + Assert.Equal(expectedParameterName, result.Name); + Assert.Equal(pretendMember.Name, result.Member.Name); + } + + public static IEnumerable VerifyParameterInfoGetRealObjectWorks_TestData + { + get + { + Type t = typeof(PretendParent); + ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(int), typeof(int) }); + MethodInfo method = t.GetMethod(nameof(PretendParent.PretendMethod)); + PropertyInfo property = t.GetProperty("Item"); + + yield return new object[] { ctor, 0, "a" }; + yield return new object[] { ctor, 1, "b" }; + yield return new object[] { method, -1, null }; + yield return new object[] { method, 0, "x" }; + yield return new object[] { method, 1, "y" }; + yield return new object[] { property, 0, "index1" }; + yield return new object[] { property, 1, "index2" }; + } + } + private static ParameterInfo GetParameterInfo(Type type, string name, int index) { ParameterInfo[] parameters = GetMethod(type, name).GetParameters(); @@ -245,6 +336,12 @@ private static MethodInfo GetMethod(Type type, string name) // Metadata for reflection public class ParameterInfoMetadata { + public void Foo1(BindingFlags bf = BindingFlags.DeclaredOnly) { } + public void Foo2([CustomBindingFlags(Value = BindingFlags.IgnoreCase)] BindingFlags bf) { } + public void Foo3([CustomBindingFlags(Value = BindingFlags.DeclaredOnly)] BindingFlags bf = BindingFlags.FlattenHierarchy ) { } + + public void MethodWithCustomAttribute([My(2)]string str, int iValue, long lValue) { } + public void Method1(string str, int iValue, long lValue) { } public void Method2() { } public void MethodWithArray(string[] strArray) { } @@ -274,5 +371,39 @@ public class GenericClass public void GenericMethod(T t) { } public string GenericMethodWithDefault(int i, T t = default(T)) { return "somestring"; } } + + private class MyAttribute : Attribute + { + internal MyAttribute(int i) { } + } + + internal sealed class CustomBindingFlagsAttribute : UsableCustomConstantAttribute + { + public new object Value { get { return RealValue; } set { RealValue = value; } } + } + + internal abstract class UsableCustomConstantAttribute : CustomConstantAttribute + { + public sealed override object Value => RealValue; + protected object RealValue { get; set; } + } + + private sealed class PretendParent + { + public PretendParent(int a, int b) { } + public void PretendMethod(int x, int y) { } + public int this[int index1, int index2] { get { throw null; } } + } + + private sealed class PodPersonParameterInfo : MockParameterInfo + { + public PodPersonParameterInfo(MemberInfo pretendMember, int pretendPosition) + { + // Serialization can recreate a ParameterInfo from just these two pieces of data. Of course, this is just a test and no one + // ever told this Member that it was adopting a counterfeit Parameter, but this is just a test... + MemberImpl = pretendMember; + PositionImpl = pretendPosition; + } + } } } diff --git a/src/libraries/System.Reflection/tests/PropertyInfoTests.cs b/src/libraries/System.Reflection/tests/PropertyInfoTests.cs index a24b1abaaa40e..4f4594ab5121d 100644 --- a/src/libraries/System.Reflection/tests/PropertyInfoTests.cs +++ b/src/libraries/System.Reflection/tests/PropertyInfoTests.cs @@ -249,6 +249,8 @@ public void Equals(Type type1, string name1, Type type2, string name2, bool expe PropertyInfo propertyInfo1 = GetProperty(type1, name1); PropertyInfo propertyInfo2 = GetProperty(type2, name2); Assert.Equal(expected, propertyInfo1.Equals(propertyInfo2)); + Assert.Equal(expected, propertyInfo1 == propertyInfo2); + Assert.Equal(!expected, propertyInfo1 != propertyInfo2); } [Fact] diff --git a/src/libraries/System.Reflection/tests/System.Reflection.Tests.csproj b/src/libraries/System.Reflection/tests/System.Reflection.Tests.csproj index 876c6861cfc11..ad1c0e21aa960 100644 --- a/src/libraries/System.Reflection/tests/System.Reflection.Tests.csproj +++ b/src/libraries/System.Reflection/tests/System.Reflection.Tests.csproj @@ -1,10 +1,13 @@ {B027C72E-F04E-42E0-A7F7-993AEF8400D2} - netstandard-Debug;netstandard-Release + netcoreapp-Debug;netcoreapp-Release;netstandard-Debug;netstandard-Release true + + Common\System\Reflection\MockParameterInfo.cs + @@ -32,6 +35,10 @@ ResourceTextFile.txt + + + + diff --git a/src/libraries/System.Reflection/tests/TypeInfoTests.cs b/src/libraries/System.Reflection/tests/TypeInfoTests.cs index 5962bcf0703b9..71f317a5361bc 100644 --- a/src/libraries/System.Reflection/tests/TypeInfoTests.cs +++ b/src/libraries/System.Reflection/tests/TypeInfoTests.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System.Collections; using System.Collections.Generic; using System.Linq; +using System.IO; using System.Runtime.InteropServices; using Xunit; @@ -17,25 +19,27 @@ public class TypeInfoTests [InlineData(typeof(TI_SubClass), 2)] [InlineData(typeof(ClassWithStaticConstructor), 0)] [InlineData(typeof(ClassWithMultipleConstructors), 4)] - public void DeclaredEvents(Type type, int expectedCount) + public void DeclaredConstructors(Type type, int expectedCount) { ConstructorInfo[] constructors = type.GetTypeInfo().DeclaredConstructors.Where(ctorInfo => !ctorInfo.IsStatic).ToArray(); Assert.Equal(expectedCount, constructors.Length); foreach (ConstructorInfo constructorInfo in constructors) { Assert.NotNull(constructorInfo); + Assert.True(constructorInfo.IsSpecialName); } } [Theory] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.EventPublic), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.EventPublicStatic), true)] - [InlineData(typeof(TI_BaseClass), "NoSuchEvent", false)] - [InlineData(typeof(TI_BaseClass), "", false)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublicNew), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublic), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublicStatic), false)] - public void DeclaredEvents(Type type, string name, bool exists) + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.EventPublic), true, "EventHandler")] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.EventPublicStatic), true, "EventHandler")] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.StuffHappened), true, "Action`1")] + [InlineData(typeof(TI_BaseClass), "NoSuchEvent", false, "EventHandler")] + [InlineData(typeof(TI_BaseClass), "", false, "EventHandler")] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublicNew), true, "EventHandler")] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublic), true, "EventHandler")] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.EventPublicStatic), false, "EventHandler")] + public void DeclaredEvents(Type type, string name, bool exists, string eventHandlerTypeName) { IEnumerable events = type.GetTypeInfo().DeclaredEvents; Assert.Equal(exists, events.Any(eventInfo => eventInfo.Name.Equals(name))); @@ -44,6 +48,7 @@ public void DeclaredEvents(Type type, string name, bool exists) if (exists) { Assert.Equal(name, declaredEventInfo.Name); + Assert.Equal(eventHandlerTypeName, declaredEventInfo.EventHandlerType.Name); } else { @@ -52,24 +57,26 @@ public void DeclaredEvents(Type type, string name, bool exists) } [Theory] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._field1), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._field2), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._readonlyField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._volatileField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_field), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_readonlyField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_volatileField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_arrayField), true)] - [InlineData(typeof(TI_BaseClass), "NoSuchField", false)] - [InlineData(typeof(TI_BaseClass), "", false)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._field2), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._readonlyField), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._volatileField), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_field), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_readonlyField), true)] - [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_volatileField), true)] - [InlineData(typeof(TI_BaseClass), nameof(TI_SubClass.s_arrayField), true)] - public void DeclaredFields(Type type, string name, bool exists) + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._field1), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._field2), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._readonlyField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass._volatileField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_field), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_readonlyField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_volatileField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.s_arrayField), true, typeof(string[]), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.StuffHappened), true, typeof(Action), true)] + [InlineData(typeof(TI_BaseClass), "_privateField", true, typeof(int), true)] + [InlineData(typeof(TI_BaseClass), "NoSuchField", false, default(Type), default(Boolean))] + [InlineData(typeof(TI_BaseClass), "", false, default(Type), default(Boolean))] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._field2), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._readonlyField), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass._volatileField), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_field), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_readonlyField), true, typeof(string), false)] + [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.s_volatileField), true, typeof(string), false)] + [InlineData(typeof(TI_BaseClass), nameof(TI_SubClass.s_arrayField), true, typeof(string[]), false)] + public void DeclaredFields(Type type, string name, bool exists, Type fieldType, bool isPrivate) { IEnumerable fields = type.GetTypeInfo().DeclaredFields.Select(fieldInfo => fieldInfo.Name); FieldInfo declaredFieldInfo = type.GetTypeInfo().GetDeclaredField(name); @@ -77,6 +84,8 @@ public void DeclaredFields(Type type, string name, bool exists) { Assert.Equal(name, declaredFieldInfo.Name); Assert.Contains(name, fields); + Assert.Equal(fieldType, declaredFieldInfo.FieldType); + Assert.Equal(isPrivate, declaredFieldInfo.IsPrivate); } else { @@ -101,6 +110,10 @@ public void DeclaredMembers(Type type, string[] expected) [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.VirtualVoidMethodReturningVoid1), true)] [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.VirtualVoidMethodReturningVoid2), true)] [InlineData(typeof(TI_BaseClass), nameof(TI_BaseClass.StaticVoidMethodReturningVoid), true)] + [InlineData(typeof(TI_BaseClass), "add_StuffHappened", true)] + [InlineData(typeof(TI_BaseClass), "remove_StuffHappened", true)] + [InlineData(typeof(TI_BaseClass), "set_StringProperty1", true)] + [InlineData(typeof(TI_BaseClass), "get_StringProperty1", true)] [InlineData(typeof(TI_BaseClass), "NoSuchMethod", false)] [InlineData(typeof(TI_BaseClass), "", false)] [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.VoidMethodReturningVoid2), true)] @@ -165,8 +178,10 @@ private void DeclaredNestedTypes(Type type, string name, bool exists) [InlineData(typeof(TI_SubClass), nameof(TI_SubClass.StaticStringProperty))] public void DeclaredProperties(Type type, string name) { - IEnumerable properties = type.GetTypeInfo().DeclaredProperties.Select(property => property.Name); + TypeInfo typeInfo = type.GetTypeInfo(); + IEnumerable properties = typeInfo.DeclaredProperties.Select(property => property.Name); Assert.Contains(name, properties); + Assert.Equal(name, typeInfo.GetDeclaredProperty(name).Name); } [Fact] @@ -511,6 +526,10 @@ public void IsInstanceOfType(Type type, object o, bool expected) [InlineData(typeof(object), typeof(TI_ClassWithInterface1), true)] [InlineData(typeof(int?), typeof(int), true)] [InlineData(typeof(List), typeof(List<>), false)] + [InlineData(typeof(IDisposable), typeof(Stream), true)] + [InlineData(typeof(IList), typeof(ArrayList), true)] + [InlineData(typeof(object), typeof(int), true)] + [InlineData(typeof(object), typeof(string), true)] // Null [InlineData(typeof(BaseClassWithInterface1Interface2), null, false)] // Lists and arrays @@ -1567,6 +1586,7 @@ public TI_BaseClass(short i) { } public event EventHandler EventPublic; // Inherited public static event EventHandler EventPublicStatic; + public event Action StuffHappened; public static string[] s_arrayField = new string[5]; public string _field1 = ""; @@ -1577,6 +1597,8 @@ public TI_BaseClass(short i) { } public static readonly string s_readonlyField = ""; public static volatile string s_volatileField = ""; + private int _privateField; + public void VoidMethodReturningVoid1() { } public void StringMethodReturningVoid(string str) { } public void VoidMethodReturningVoid2() { } diff --git a/src/libraries/System.Runtime/tests/System/Reflection/TypeInfoTests.netcoreapp.cs b/src/libraries/System.Reflection/tests/TypeInfoTests.netcoreapp.cs similarity index 100% rename from src/libraries/System.Runtime/tests/System/Reflection/TypeInfoTests.netcoreapp.cs rename to src/libraries/System.Reflection/tests/TypeInfoTests.netcoreapp.cs diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj b/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj index fc58e977fe6db..f8bc27a6271dd 100644 --- a/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj +++ b/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj @@ -34,9 +34,6 @@ Common\System\IO\TempFile.cs - - Common\System\Reflection\MockParameterInfo.cs - System\StringTests.cs @@ -169,25 +166,17 @@ - - - - - - - - @@ -249,10 +238,8 @@ - - diff --git a/src/libraries/System.Runtime/tests/System/Reflection/ConstructorInfoTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/ConstructorInfoTests.cs deleted file mode 100644 index a0e366e40ec52..0000000000000 --- a/src/libraries/System.Runtime/tests/System/Reflection/ConstructorInfoTests.cs +++ /dev/null @@ -1,249 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Xunit; - -namespace System.Reflection.Tests -{ - public static class ConstructorInfoTests - { - public static IEnumerable Equality_TestData() - { - ConstructorInfo[] methodSampleConstructors1 = GetConstructors(typeof(ConstructorInfoInvokeSample)); - ConstructorInfo[] methodSampleConstructors2 = GetConstructors(typeof(ConstructorInfoInvokeSample)); - yield return new object[] { methodSampleConstructors1[0], methodSampleConstructors2[0], true }; - yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[1], true }; - yield return new object[] { methodSampleConstructors1[2], methodSampleConstructors2[2], true }; - yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[2], false }; - } - - [Theory] - [MemberData(nameof(Equality_TestData))] - public static void Test_Equality(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected) - { - Assert.Equal(expected, constructorInfo1 == constructorInfo2); - Assert.NotEqual(expected, constructorInfo1 != constructorInfo2); - } - - [Fact] - public static void Verify_Invoke_ReturnsNewObject() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - Assert.Equal(cis.Length, 3); - ConstructorInfoInvokeSample obj = (ConstructorInfoInvokeSample)cis[0].Invoke(null); - Assert.NotNull(obj); - } - - [Fact] - [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Invoking static constructors not supported on UapAot")] - public static void TestInvoke_Nullery() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoClassA)); - object obj = cis[0].Invoke(null, new object[] { }); - Assert.Null(obj); - } - - [Fact] - public static void TestInvokeNeg() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoClassA)); - object obj = null; - Assert.Throws(() => { obj = cis[0].Invoke(new object[] { }); }); - Assert.Null(obj); - } - - [Fact] - public static void TestInvoke_1DArray() - { - ConstructorInfo[] cis = GetConstructors(typeof(object[])); - object[] arr = null; - //Test data for array length - int[] arraylength = { 1, 2, 99, 65535 }; - - //try to invoke Array ctors with different lengths - foreach (int length in arraylength) - { - //create big Array with elements - arr = (object[])cis[0].Invoke(new object[] { length }); - Assert.NotNull(arr); - Assert.Equal(arr.Length, length); - } - } - - [Fact] - public static void TestInvoke_1DArrayWithNegativeLength() - { - ConstructorInfo[] cis = GetConstructors(typeof(object[])); - object[] arr = null; - //Test data for array length - int[] arraylength = { -1, -2, -99 }; - //try to invoke Array ctors with different lengths - foreach (int length in arraylength) - { - //create big Array with elements - Assert.Throws(() => { arr = (object[])cis[0].Invoke(new object[] { length }); }); - } - } - - [Fact] - public static void TestInvokeWithOneParam() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - obj = (ConstructorInfoInvokeSample)cis[1].Invoke(new object[] { 100 }); - - Assert.NotNull(obj); - Assert.Equal(obj.intValue, 100); - } - - [Fact] - public static void TestInvokeWithTwoParams() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { 101, "hello" }); - - Assert.NotNull(obj); - Assert.Equal(obj.intValue, 101); - Assert.Equal(obj.strValue, "hello"); - } - - [Fact] - public static void TestInvoke_NoParamsProvided() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - Assert.Throws(() => { obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { }); }); - } - - [Fact] - public static void TestInvoke_ParamMismatch() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - Assert.Throws(() => { obj = (ConstructorInfoInvokeSample)cis[2].Invoke(new object[] { 121 }); }); - } - - [Fact] - public static void TestInvoke_WrongParamType() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj = null; - AssertExtensions.Throws(null, () => { obj = (ConstructorInfoInvokeSample)cis[1].Invoke(new object[] { "hello" }); }); - } - - [Fact] - public static void TestInvoke_ConstructorOnExistingInstance() - { - ConstructorInfo[] cis = GetConstructors(typeof(ConstructorInfoInvokeSample)); - //try to invoke Array ctors with one param - ConstructorInfoInvokeSample obj1 = new ConstructorInfoInvokeSample(100, "hello"); - ConstructorInfoInvokeSample obj2 = null; - obj2 = (ConstructorInfoInvokeSample)cis[2].Invoke(obj1, new object[] { 999, "initialized" }); - Assert.Null(obj2); - Assert.Equal(obj1.intValue, 999); - Assert.Equal(obj1.strValue, "initialized"); - } - - [Fact] - public static void TestInvoke_AbstractConstructor() - { - ConstructorInfo[] cis = GetConstructors(typeof(Base)); - object obj = null; - Assert.Throws(() => { obj = (Base)cis[0].Invoke(new object[] { }); }); - } - - [Fact] - public static void TestInvoke_DerivedConstructor() - { - ConstructorInfo[] cis = GetConstructors(typeof(Derived)); - Derived obj = null; - obj = (Derived)cis[0].Invoke(new object[] { }); - Assert.NotNull(obj); - } - - [Fact] - public static void TestInvoke_Struct() - { - ConstructorInfo[] cis = GetConstructors(typeof(MyStruct)); - MyStruct obj; - obj = (MyStruct)cis[0].Invoke(new object[] { 1, 2 }); - Assert.NotNull(obj); - Assert.Equal(obj.x, 1); - Assert.Equal(obj.y, 2); - } - - public static ConstructorInfo[] GetConstructors(Type type) - { - return type.GetTypeInfo().DeclaredConstructors.ToArray(); - } - } - - //Metadata for Reflection - public class ConstructorInfoInvokeSample - { - public int intValue = 0; - public string strValue = ""; - - public ConstructorInfoInvokeSample() { } - - public ConstructorInfoInvokeSample(int i) - { - this.intValue = i; - } - - public ConstructorInfoInvokeSample(int i, string s) - { - this.intValue = i; - this.strValue = s; - } - - public string Method1(DateTime t) - { - return ""; - } - } - - public static class ConstructorInfoClassA - { - static ConstructorInfoClassA() - { - } - } - - public abstract class Base - { - public Base() - { - } - } - - public class Derived : Base - { - public Derived() - { - } - } - - public struct MyStruct - { - public int x; - public int y; - - public MyStruct(int p1, int p2) - { - x = p1; - y = p2; - } - }; -} diff --git a/src/libraries/System.Runtime/tests/System/Reflection/EventInfoTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/EventInfoTests.cs deleted file mode 100644 index f43d9fcdff29b..0000000000000 --- a/src/libraries/System.Runtime/tests/System/Reflection/EventInfoTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using Xunit; - -namespace System.Reflection.Tests -{ - public static class EventInfoTests - { - public static IEnumerable Equality_TestData() - { - yield return new object[] { GetEventInfo(typeof(BaseClass), "EventPublic"), GetEventInfo(typeof(BaseClass), "EventPublic"), true }; - yield return new object[] { GetEventInfo(typeof(BaseClass), "EventPublic"), GetEventInfo(typeof(SubClass), "EventPublic"), false }; - yield return new object[] { GetEventInfo(typeof(BaseClass), "EventPublic"), GetEventInfo(typeof(BaseClass), "EventPublicStatic"), false }; - } - - [Theory] - [MemberData(nameof(Equality_TestData))] - public static void Test_Equality(EventInfo constructorInfo1, EventInfo constructorInfo2, bool expected) - { - Assert.Equal(expected, constructorInfo1 == constructorInfo2); - Assert.NotEqual(expected, constructorInfo1 != constructorInfo2); - } - - //private helper methods - private static EventInfo GetEventInfo(Type t, string eventName) - { - TypeInfo ti = t.GetTypeInfo(); - IEnumerator allevents = ti.DeclaredEvents.GetEnumerator(); - EventInfo eventFound = null; - while (allevents.MoveNext()) - { - if (eventName.Equals(allevents.Current.Name)) - { - eventFound = allevents.Current; - break; - } - } - return eventFound; - } - } - -#pragma warning disable 0067 // the event was declared but never used - // Metadata for Reflection - public class BaseClass - { - public event EventHandler EventPublic; // inherited - public static event EventHandler EventPublicStatic; - } - - public class SubClass : BaseClass - { - public new event EventHandler EventPublic; //overrides event - } -#pragma warning restore 0067 -} \ No newline at end of file diff --git a/src/libraries/System.Runtime/tests/System/Reflection/FieldInfoTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/FieldInfoTests.cs deleted file mode 100644 index f18d429516a16..0000000000000 --- a/src/libraries/System.Runtime/tests/System/Reflection/FieldInfoTests.cs +++ /dev/null @@ -1,65 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using Xunit; - -namespace System.Reflection.Tests -{ - public class FieldInfoTests - { - [Theory] - [InlineData("nonstatic_strField", "nonstatic_strField", true)] - [InlineData("nonstatic_strField", "intFieldStatic", false)] - public static void TestEquality_EqualAndNotEqualFields(string fieldName1, string fieldName2, bool expected) - { - FieldInfo info1 = GetField(fieldName1); - FieldInfo info2 = GetField(fieldName2); - - Assert.NotNull(info1); - Assert.NotNull(info2); - Assert.Equal(expected, info1 == info2); - Assert.NotEqual(expected, info1 != info2); - } - - [Fact] - public static void Test_SecurityAttributes() - { - FieldInfo info = GetField("intFieldStatic"); - - Assert.True(info.IsSecurityCritical); - Assert.False(info.IsSecuritySafeCritical); - Assert.False(info.IsSecurityTransparent); - } - - // Helper method to get field from Type type - private static FieldInfo GetField(string fieldName) - { - Type t = typeof(FieldInfoTests); - TypeInfo ti = t.GetTypeInfo(); - IEnumerator alldefinedFields = ti.DeclaredFields.GetEnumerator(); - FieldInfo fi = null, found = null; - - while (alldefinedFields.MoveNext()) - { - fi = alldefinedFields.Current; - if (fi.Name.Equals(fieldName)) - { - //found type - found = fi; - break; - } - } - return found; - } - - // Fields for Reflection - public static int intFieldStatic = 100; - public int intFieldNonStatic = 101; - public static string static_strField = "Static string field"; - public string nonstatic_strField = "NonStatic string field"; - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime/tests/System/Reflection/MemberInfoTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/MemberInfoTests.cs deleted file mode 100644 index 78a7deb8d3308..0000000000000 --- a/src/libraries/System.Runtime/tests/System/Reflection/MemberInfoTests.cs +++ /dev/null @@ -1,256 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using Xunit; - -namespace System.Reflection.Tests -{ - public class MemberInfoTests - { - [Fact] - public static void TestReflectedType() - { - Type t = typeof(Derived); - MemberInfo[] members = t.GetMembers(); - foreach (MemberInfo member in members) - { - Assert.Equal(t, member.ReflectedType); - } - } - - [Fact] - public static void TestPropertyReflectedType() - { - Type t = typeof(Base); - PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1)); - Assert.Equal(t, p.ReflectedType); - Assert.NotNull(p.GetMethod); - Assert.NotNull(p.SetMethod); - } - - [Fact] - public static void TestInheritedPropertiesHidePrivateAccessorMethods() - { - Type t = typeof(Derived); - PropertyInfo p = t.GetProperty(nameof(Base.MyProperty1)); - Assert.Equal(t, p.ReflectedType); - Assert.NotNull(p.GetMethod); - Assert.Null(p.SetMethod); - } - - [Fact] - public static void TestGenericMethodsInheritTheReflectedTypeOfTheirTemplate() - { - Type t = typeof(Derived); - MethodInfo moo = t.GetMethod("Moo"); - Assert.Equal(t, moo.ReflectedType); - MethodInfo mooInst = moo.MakeGenericMethod(typeof(int)); - Assert.Equal(t, mooInst.ReflectedType); - } - - [Fact] - public static void TestDeclaringMethodOfTypeParametersOfInheritedMethods() - { - Type t = typeof(Derived); - MethodInfo moo = t.GetMethod("Moo"); - Assert.Equal(t, moo.ReflectedType); - Type theM = moo.GetGenericArguments()[0]; - MethodBase moo1 = theM.DeclaringMethod; - Type reflectedTypeOfMoo1 = moo1.ReflectedType; - Assert.Equal(typeof(Base), reflectedTypeOfMoo1); - } - - [Fact] - public static void TestDeclaringMethodOfTypeParametersOfInheritedMethods2() - { - Type t = typeof(GDerived); - MethodInfo moo = t.GetMethod("Moo"); - Assert.Equal(t, moo.ReflectedType); - Type theM = moo.GetGenericArguments()[0]; - MethodBase moo1 = theM.DeclaringMethod; - Type reflectedTypeOfMoo1 = moo1.ReflectedType; - Assert.Equal(typeof(GBase<>), reflectedTypeOfMoo1); - } - - [Fact] - public static void TestInheritedPropertyAccessors() - { - Type t = typeof(Derived); - PropertyInfo p = t.GetProperty(nameof(Base.MyProperty)); - MethodInfo getter = p.GetMethod; - MethodInfo setter = p.SetMethod; - Assert.Equal(t, getter.ReflectedType); - Assert.Equal(t, setter.ReflectedType); - } - - [Fact] - public static void TestInheritedEventAccessors() - { - Type t = typeof(Derived); - EventInfo e = t.GetEvent(nameof(Base.MyEvent)); - MethodInfo adder = e.AddMethod; - MethodInfo remover = e.RemoveMethod; - Assert.Equal(t, adder.ReflectedType); - Assert.Equal(t, remover.ReflectedType); - } - - [Fact] - public static void TestReflectedTypeIsPartOfIdentity() - { - Type b = typeof(Base); - Type d = typeof(Derived); - - { - EventInfo e = b.GetEvent(nameof(Base.MyEvent)); - EventInfo ei = d.GetEvent(nameof(Derived.MyEvent)); - Assert.False(e.Equals(ei)); - } - - { - FieldInfo f = b.GetField(nameof(Base.MyField)); - FieldInfo fi = d.GetField(nameof(Derived.MyField)); - Assert.False(f.Equals(fi)); - } - - { - MethodInfo m = b.GetMethod(nameof(Base.Moo)); - MethodInfo mi = d.GetMethod(nameof(Derived.Moo)); - Assert.False(m.Equals(mi)); - } - - { - PropertyInfo p = b.GetProperty(nameof(Base.MyProperty)); - PropertyInfo pi = d.GetProperty(nameof(Derived.MyProperty)); - Assert.False(p.Equals(pi)); - } - } - - [Fact] - public static void TestFieldInfoReflectedTypeDoesNotSurviveRuntimeHandles() - { - Type t = typeof(Derived); - FieldInfo f = t.GetField(nameof(Base.MyField)); - Assert.Equal(typeof(Derived), f.ReflectedType); - RuntimeFieldHandle h = f.FieldHandle; - FieldInfo f2 = FieldInfo.GetFieldFromHandle(h); - Assert.Equal(typeof(Base), f2.ReflectedType); - } - - [Fact] - public static void TestMethodInfoReflectedTypeDoesNotSurviveRuntimeHandles() - { - Type t = typeof(Derived); - MethodInfo m = t.GetMethod(nameof(Base.Moo)); - Assert.Equal(typeof(Derived), m.ReflectedType); - RuntimeMethodHandle h = m.MethodHandle; - MethodBase m2 = MethodBase.GetMethodFromHandle(h); - Assert.Equal(typeof(Base), m2.ReflectedType); - } - - [Fact] - public void TestGetCustomAttributesData() - { - MemberInfo[] m = typeof(MemberInfoTests).GetMember("SampleClass"); - Assert.Equal(1, m.Count()); - foreach(CustomAttributeData cad in m[0].GetCustomAttributesData()) - { - if (cad.AttributeType == typeof(ComVisibleAttribute)) - { - ConstructorInfo c = cad.Constructor; - Assert.False(c.IsStatic); - Assert.Equal(typeof(ComVisibleAttribute), c.DeclaringType); - ParameterInfo[] p = c.GetParameters(); - Assert.Equal(1, p.Length); - Assert.Equal(typeof(bool), p[0].ParameterType); - return; - } - } - - Assert.True(false, "Expected to find ComVisibleAttribute"); - } - - public static IEnumerable EqualityOperator_TestData() - { - yield return new object[] { typeof(SampleClass) }; - yield return new object[] { new MemberInfoTests().GetType() }; - yield return new object[] { typeof(int) }; - yield return new object[] { typeof(Dictionary<,>) }; - } - - [Theory] - [MemberData(nameof(EqualityOperator_TestData))] - public void EqualityOperator_Equal_ReturnsTrue(Type type) - { - MemberInfo[] members1 = GetOrderedMembers(type); - MemberInfo[] members2 = GetOrderedMembers(type); - - Assert.Equal(members1.Length, members2.Length); - for (int i = 0; i < members1.Length; i++) - { - Assert.True(members1[i] == members2[i]); - Assert.False(members1[i] != members2[i]); - } - } - - private MemberInfo[] GetOrderedMembers(Type type) => GetMembers(type).OrderBy(member => member.Name).ToArray(); - - private MemberInfo[] GetMembers(Type type) - { - return type.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - } - - private class Base - { - public event Action MyEvent { add { } remove { } } -#pragma warning disable 0649 - public int MyField; -#pragma warning restore 0649 - public int MyProperty { get; set; } - - public int MyProperty1 { get; private set; } - public int MyProperty2 { private get; set; } - - public void Moo() { } - } - - private class Derived : Base - { - } - - private class GBase - { - public void Moo() { } - } - - private class GDerived : GBase - { - } - -#pragma warning disable 0067, 0169 - [ComVisible(false)] - public class SampleClass - { - public int PublicField; - private int PrivateField; - - public SampleClass(bool y) { } - private SampleClass(int x) { } - - public void PublicMethod() { } - private void PrivateMethod() { } - - public int PublicProp { get; set; } - private int PrivateProp { get; set; } - - public event EventHandler PublicEvent; - private event EventHandler PrivateEvent; - } -#pragma warning restore 0067, 0169 - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime/tests/System/Reflection/ModuleTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/ModuleTests.cs index 71de569377ee0..1f850d0c51179 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/ModuleTests.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/ModuleTests.cs @@ -110,7 +110,6 @@ public void TestGetHashCode() [Theory] [InlineData(typeof(ModuleTests))] [InlineData(typeof(PointerTests))] - [InlineData(typeof(EventInfoTests))] public void TestGetType(Type type) { Assert.Equal(type, Module.GetType(type.FullName, true, true)); diff --git a/src/libraries/System.Runtime/tests/System/Reflection/ParameterInfoTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/ParameterInfoTests.cs deleted file mode 100644 index 88a8cc13c3dbe..0000000000000 --- a/src/libraries/System.Runtime/tests/System/Reflection/ParameterInfoTests.cs +++ /dev/null @@ -1,181 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.Serialization; -using Xunit; - -namespace System.Reflection.Tests -{ - public static class ParameterInfoTests - { - [Fact] - public static void RawDefaultValue() - { - MethodInfo m = GetMethod(typeof(ParameterInfoTests), "Foo1"); - ParameterInfo p = m.GetParameters()[0]; - object raw = p.RawDefaultValue; - Assert.Equal(typeof(int), raw.GetType()); - Assert.Equal((int)raw, (int)BindingFlags.DeclaredOnly); - } - - [Fact] - public static void RawDefaultValueFromAttribute() - { - MethodInfo m = GetMethod(typeof(ParameterInfoTests), "Foo2"); - ParameterInfo p = m.GetParameters()[0]; - object cooked = p.DefaultValue; - object raw = p.RawDefaultValue; - - Assert.Equal(typeof(int), raw.GetType()); - Assert.Equal((int)raw, (int)BindingFlags.IgnoreCase); - } - - [Fact] - public static void RawDefaultValue_MetadataTrumpsAttribute() - { - MethodInfo m = GetMethod(typeof(ParameterInfoTests), "Foo3"); - ParameterInfo p = m.GetParameters()[0]; - object cooked = p.DefaultValue; - object raw = p.RawDefaultValue; - - Assert.Equal(typeof(int), raw.GetType()); - Assert.Equal((int)raw, (int)BindingFlags.FlattenHierarchy); - } - - [Fact] - public static void VerifyGetCustomAttributesData() - { - MethodInfo m = GetMethod(typeof(MyClass), "Method1"); - ParameterInfo p = m.GetParameters()[0]; - - foreach (CustomAttributeData cad in p.GetCustomAttributesData()) - { - if(cad.AttributeType == typeof(MyAttribute)) - { - ConstructorInfo c = cad.Constructor; - Assert.False(c.IsStatic); - Assert.False(c.IsPublic); - ParameterInfo[] paramInfo = c.GetParameters(); - Assert.Equal(1, paramInfo.Length); - Assert.Equal(typeof(int), paramInfo[0].ParameterType); - return; - } - } - - Assert.True(false, "Expected to find MyAttribute"); - } - - [Theory] - [MemberData(nameof(VerifyParameterInfoGetRealObjectWorks_TestData))] - public static void VerifyParameterInfoGetRealObjectWorks(MemberInfo pretendMember, int pretendPosition, string expectedParameterName) - { - // Regression test for https://github.com/dotnet/corefx/issues/20574 - // - // It's easy to forget that ParameterInfo's and runtime-implemented ParameterInfo's are different objects and just because the - // latter doesn't support serialization doesn't mean other providers won't either. - // - // For historical reasons, ParameterInfo contains some serialization support that subtypes can optionally hang off. This - // test ensures that support doesn't get vaporized. - - // Just pretend that we're BinaryFormatter and are deserializing a Parameter... - IObjectReference podParameter = new PodPersonParameterInfo(pretendMember, pretendPosition); - StreamingContext sc = new StreamingContext(StreamingContextStates.Clone); - ParameterInfo result = (ParameterInfo)(podParameter.GetRealObject(sc)); - - Assert.Equal(pretendPosition, result.Position); - Assert.Equal(expectedParameterName, result.Name); - Assert.Equal(pretendMember.Name, result.Member.Name); - } - - public static IEnumerable VerifyParameterInfoGetRealObjectWorks_TestData - { - get - { - Type t = typeof(PretendParent); - ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(int), typeof(int) }); - MethodInfo method = t.GetMethod(nameof(PretendParent.PretendMethod)); - PropertyInfo property = t.GetProperty("Item"); - - yield return new object[] { ctor, 0, "a" }; - yield return new object[] { ctor, 1, "b" }; - yield return new object[] { method, -1, null }; - yield return new object[] { method, 0, "x" }; - yield return new object[] { method, 1, "y" }; - yield return new object[] { property, 0, "index1" }; - yield return new object[] { property, 1, "index2" }; - } - } - - private sealed class PretendParent - { - public PretendParent(int a, int b) { } - public void PretendMethod(int x, int y) { } - public int this[int index1, int index2] { get { throw null; } } - } - - private sealed class PodPersonParameterInfo : MockParameterInfo - { - public PodPersonParameterInfo(MemberInfo pretendMember, int pretendPosition) - { - // Serialization can recreate a ParameterInfo from just these two pieces of data. Of course, this is just a test and no one - // ever told this Member that it was adopting a counterfeit Parameter, but this is just a test... - MemberImpl = pretendMember; - PositionImpl = pretendPosition; - } - } - - private static void Foo1(BindingFlags bf = BindingFlags.DeclaredOnly) { } - - private static void Foo2([CustomBindingFlags(Value = BindingFlags.IgnoreCase)] BindingFlags bf) { } - - private static void Foo3([CustomBindingFlags(Value = BindingFlags.DeclaredOnly)] BindingFlags bf = BindingFlags.FlattenHierarchy ) { } - - //Gets MethodInfo object from a Type - public static MethodInfo GetMethod(Type t, string method) - { - TypeInfo ti = t.GetTypeInfo(); - IEnumerator alldefinedMethods = ti.DeclaredMethods.GetEnumerator(); - MethodInfo mi = null; - - while (alldefinedMethods.MoveNext()) - { - if (alldefinedMethods.Current.Name.Equals(method)) - { - //found method - mi = alldefinedMethods.Current; - break; - } - } - return mi; - } - - // Class For Reflection Metadata - public class MyClass - { - public void Method1([My(2)]string str, int iValue, long lValue) - { - } - } - - private class MyAttribute : Attribute - { - internal MyAttribute(int i) { } - } - } - - internal sealed class CustomBindingFlagsAttribute : UsableCustomConstantAttribute - { - public new object Value { get { return RealValue; } set { RealValue = value; } } - } - - internal abstract class UsableCustomConstantAttribute : CustomConstantAttribute - { - public sealed override object Value => RealValue; - protected object RealValue { get; set; } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime/tests/System/Reflection/PropertyInfoTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/PropertyInfoTests.cs deleted file mode 100644 index 031f82d378c06..0000000000000 --- a/src/libraries/System.Runtime/tests/System/Reflection/PropertyInfoTests.cs +++ /dev/null @@ -1,85 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Reflection; -using Xunit; - -namespace System.Reflection.Tests -{ - public static class PropertyInfoTests - { - [Fact] - public static void GetRawConstantValueOnProperty() - { - // - // Why does PropertyInfo expose a GetRawConstantValue property? - // - // - ECMA metadata has the ability to specify a "default value" for a property but C# has no way to generate it. - // - The CustomConstantAttribute class is not marked as usable on a property. - // - PropertyInfo f = typeof(TestClass).GetTypeInfo().GetDeclaredProperty(nameof(TestClass.MyProp)); - Assert.Throws(() => f.GetRawConstantValue()); - } - - [Fact] - public static void TestEquality_False() - { - PropertyInfo pi1 = typeof(SampleMethod).GetTypeInfo().GetProperty("MyPropAA"); - PropertyInfo pi2 = typeof(SampleMethod).GetTypeInfo().GetProperty("MyPropBB"); - - Assert.False(pi1 == pi2); - Assert.True(pi1 != pi2); - } - - [Fact] - public static void TestEquality_True() - { - PropertyInfo pi1 = typeof(SampleMethod).GetTypeInfo().GetProperty("MyPropAA"); - PropertyInfo pi2 = typeof(SampleMethod).GetTypeInfo().GetProperty("MyPropAA"); - - Assert.True(pi1 == pi2); - Assert.False(pi1 != pi2); - } - - private class TestClass - { - public static BindingFlags MyProp { get; } - } - - //Reflection Metadata - public class SampleMethod - { - public double m_PropBB = 1; - public short m_PropAA = 2; - //indexer Property - public string[] mystrings = { "abc", "def", "ghi", "jkl" }; - - public string this[int Index] - { - get - { - return mystrings[Index]; - } - set - { - mystrings[Index] = value; - } - } - - // MyPropAA - ReadWrite property - public string MyPropAA - { - get { return m_PropAA.ToString(); } - set { m_PropAA = short.Parse(value); } - } - - public double MyPropBB - { - get { return m_PropBB; } - set { m_PropBB = value; } - } - } - } -} \ No newline at end of file diff --git a/src/libraries/System.Runtime/tests/System/Reflection/RuntimeReflectionExtensionsTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/RuntimeReflectionExtensionsTests.cs deleted file mode 100644 index c5330bd033e22..0000000000000 --- a/src/libraries/System.Runtime/tests/System/Reflection/RuntimeReflectionExtensionsTests.cs +++ /dev/null @@ -1,206 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Xunit; - -namespace System.Reflection.Tests -{ - public class RuntimeReflectionExtensionsTests - { - [Fact] - public void GetMethodInfo() - { - Assert.Equal(typeof(RuntimeReflectionExtensionsTests).GetMethod("GetMethodInfo"), ((Action)GetMethodInfo).GetMethodInfo()); - } - - [Fact] - public void GetMethodInfoOnNull() => AssertExtensions.Throws("del", () => default(Action).GetMethodInfo()); - - [Fact] - public void GetRuntimeBaseDefinition() - { - MethodInfo derivedFoo = typeof(TestDerived).GetMethod(nameof(TestDerived.Foo)); - MethodInfo baseFoo = typeof(TestBase).GetMethod(nameof(TestBase.Foo)); - MethodInfo actual = derivedFoo.GetRuntimeBaseDefinition(); - Assert.Equal(baseFoo, actual); - } - - [Fact] - public void GetRuntimeBaseDefinitionOnNull() => - Assert.Throws(() => default(MethodInfo).GetRuntimeBaseDefinition()); - - private abstract class TestBase - { - public abstract void Foo(); - } - - private class TestDerived : TestBase - { - public override void Foo() { throw null; } - } - - [Fact] - public void GetRuntimeEvent() - { - Assert.Equal(typeof(TestType).GetEvent("StuffHappened"), typeof(TestType).GetRuntimeEvent("StuffHappened")); - } - - [Fact] - public void GetRuntimeEventOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeEvent("")); - - [Fact] - public void GetRuntimeEventWithNull() => - Assert.Throws(null, () => typeof(TestType).GetRuntimeEvent(null)); - - [Fact] - public void GetRuntimeEventEmptyName() => Assert.Null(typeof(TestType).GetRuntimeEvent("")); - - [Fact] - public void GetRuntimeField() - { - Assert.Equal(typeof(TestType).GetField("_pizzaSize"), typeof(TestType).GetRuntimeField("_pizzaSize")); - } - - [Fact] - public void GetRuntimeFieldOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeField("")); - - [Fact] - public void GetRuntimeFieldWithNull() => - Assert.Throws(null, () => typeof(TestType).GetRuntimeField(null)); - - [Fact] - public void GetRuntimeFieldEmptyName() => Assert.Null(typeof(TestType).GetRuntimeField("")); - - [Fact] - public void GetRuntimeMethod() - { - Assert.Equal(typeof(TestType).GetMethod("Flush"), typeof(TestType).GetRuntimeMethod("Flush", Array.Empty())); - } - - [Fact] - public void GetRuntimeMethodOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeMethod("", Type.EmptyTypes)); - - [Fact] - public void GetRuntimeMethodWithNullName() => AssertExtensions.Throws("name", () => typeof(TestType).GetRuntimeMethod(null, Type.EmptyTypes)); - - [Fact] - public void GetRuntimeMethodWithNullTypes() => AssertExtensions.Throws("types", () => typeof(TestType).GetRuntimeMethod("", null)); - - [Fact] - public void GetRuntimeMethodEmptyName() => Assert.Null(typeof(TestType).GetRuntimeMethod("", Type.EmptyTypes)); - - [Fact] - public void GetRuntimeProperty() - { - Assert.Equal(typeof(TestType).GetProperty("Length"), typeof(TestType).GetRuntimeProperty("Length")); - } - - [Fact] - public void GetRuntimePropertyOnNull() => - AssertExtensions.Throws("type", () => default(Type).GetRuntimeProperty("")); - - [Fact] - public void GetRuntimePropertyWithNull() => - AssertExtensions.Throws("name", () => typeof(TestType).GetRuntimeProperty(null)); - - [Fact] - public void GetRuntimePropertyEmptyName() => Assert.Null(typeof(TestType).GetRuntimeProperty("")); - - [Fact] - public void GetRuntimeEvents() - { - List events = typeof(TestType).GetRuntimeEvents().ToList(); - Assert.Equal(1, events.Count); - Assert.Equal("StuffHappened", events[0].Name); - } - - [Fact] - public void GetRuntimeEventsOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeEvents()); - - - [Fact] - public void GetRuntimeFields() - { - List fields = typeof(TestType).GetRuntimeFields().ToList(); - Assert.Equal(2, fields.Count); - List fieldNames = fields.Select(f => f.Name).ToList(); - Assert.Contains("StuffHappened", fieldNames); - Assert.Contains("_pizzaSize", fieldNames); - } - - [Fact] - public void GetRuntimeFieldsOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeFields()); - - [Fact] - public void GetRuntimeMethods() - { - List methods = typeof(TestType).GetRuntimeMethods().ToList(); - List methodNames = methods.Select(m => m.Name).Distinct().ToList(); - Assert.Contains("remove_StuffHappened", methodNames); - Assert.Contains("add_StuffHappened", methodNames); - Assert.Contains("Equals", methodNames); - Assert.Contains("GetHashCode", methodNames); - Assert.Contains("ToString", methodNames); - Assert.Contains("get_CanRead", methodNames); - Assert.Contains("Read", methodNames); - } - - [Fact] - public void GetRuntimeMethodsOnNull() => AssertExtensions.Throws("type", () => default(Type).GetRuntimeMethods()); - - [Fact] - public void GetRuntimeProperties() - { - List properties = typeof(TestType).GetRuntimeProperties().ToList(); - List propertyNames = properties.Select(p => p.Name).Distinct().ToList(); - Assert.Equal(5, properties.Count); - Assert.Contains("Length", propertyNames); - Assert.Contains("Position", propertyNames); - Assert.Contains("CanRead", propertyNames); - Assert.Contains("CanWrite", propertyNames); - Assert.Contains("CanSeek", propertyNames); - } - - [Fact] - public void GetRuntimePropertiesOnNull() => - AssertExtensions.Throws("type", () => default(Type).GetRuntimeProperties()); - - [Fact] - public void GetRuntimeInterfaceMap() - { - InterfaceMapping map = typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(IDisposable)); - Assert.Same(typeof(TestType), map.TargetType); - Assert.Same(typeof(IDisposable), map.InterfaceType); - Assert.Equal(1, map.InterfaceMethods.Length); - Assert.Equal(1, map.TargetMethods.Length); - MethodInfo ifaceDispose = map.InterfaceMethods[0]; - MethodInfo targetDispose = map.TargetMethods[0]; - Assert.Equal(ifaceDispose.CallingConvention, targetDispose.CallingConvention); - Assert.Equal(ifaceDispose.Name, targetDispose.Name); - Assert.Same(ifaceDispose.ReturnType, targetDispose.ReturnType); - Assert.Equal(ifaceDispose.GetParameters().Length, targetDispose.GetParameters().Length); - Assert.Same(typeof(TestTypeBase), targetDispose.DeclaringType); - Assert.Same(typeof(IDisposable), ifaceDispose.DeclaringType); - } - - [Fact] - public void GetRuntimeInterfaceMapOnNull() => - AssertExtensions.Throws("typeInfo", () => default(TypeInfo).GetRuntimeInterfaceMap(typeof(ICloneable))); - - [Fact] - public void GetRuntimeInterfaceMapWithNull() => - AssertExtensions.Throws("ifaceType", () => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(null)); - - [Fact] - public void GetRuntimeInterfaceMapNotImplemented() => - Assert.Throws(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(ICloneable))); - - [Fact] - public void GetRuntimeInterfaceMapNotInterface() => - Assert.Throws(() => typeof(TestType).GetTypeInfo().GetRuntimeInterfaceMap(typeof(string))); - } -} diff --git a/src/libraries/System.Runtime/tests/System/Reflection/TypeDelegatorTests.netcoreapp.cs b/src/libraries/System.Runtime/tests/System/Reflection/TypeDelegatorTests.netcoreapp.cs index feafcd2154961..8b26171f85f77 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/TypeDelegatorTests.netcoreapp.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/TypeDelegatorTests.netcoreapp.cs @@ -17,7 +17,6 @@ private static IEnumerable SZArrayOrNotTypes() yield return new object[] { typeof(int), false }; yield return new object[] { typeof(int[]).MakeByRefType(), false }; yield return new object[] { typeof(int[,]), false }; - yield return new object[] { typeof(TypeInfoTests), false }; if (PlatformDetection.IsNonZeroLowerBoundArraySupported) { yield return new object[] { Array.CreateInstance(typeof(int), new[] { 2 }, new[] { -1 }).GetType(), false }; diff --git a/src/libraries/System.Runtime/tests/System/Reflection/TypeInfoTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/TypeInfoTests.cs deleted file mode 100644 index ed3c620f59605..0000000000000 --- a/src/libraries/System.Runtime/tests/System/Reflection/TypeInfoTests.cs +++ /dev/null @@ -1,263 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Xunit; - -namespace System.Reflection.Tests -{ - public abstract class TestTypeBase : IDisposable - { - public abstract bool CanRead { get; } - public abstract bool CanWrite { get; } - public abstract bool CanSeek { get; } - public abstract long Length { get; } - public abstract long Position { get; set; } - - public virtual Task FlushAsync() - { - throw null; - } - - public abstract void Flush(); - - public virtual Task ReadAsync(byte[] buffer, int offset, int count) - { - throw null; - } - - public abstract int Read(byte[] buffer, int offset, int count); - - public abstract long Seek(long offset, SeekOrigin origin); - - public abstract void SetLength(long value); - - public abstract void Write(byte[] buffer, int offset, int count); - public virtual Task WriteAsync(byte[] buffer, int offset, int count) - { - throw null; - } - - public void Dispose() - { - throw null; - } - } - - public class TestType : TestTypeBase - { - public TestType() - { - } - - public class Nested - { - - } - -#pragma warning disable 0067 // event never used - public event Action StuffHappened; -#pragma warning restore 0067 - -#pragma warning disable 0169 // field never used - private int _pizzaSize; -#pragma warning restore 0169 - - public override bool CanRead => false; - - public override bool CanSeek => false; - - public override bool CanWrite => false; - - public override long Length - { - get - { - throw new NotImplementedException(); - } - } - - public override long Position - { - get - { - throw new NotImplementedException(); - } - - set - { - throw new NotImplementedException(); - } - } - - public override void Flush() - { - throw new NotImplementedException(); - } - - public override int Read(byte[] buffer, int offset, int count) - { - throw new NotImplementedException(); - } - - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotImplementedException(); - } - - public override void SetLength(long value) - { - throw new NotImplementedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotImplementedException(); - } - } - - public class TypeInfoTests - { - public TypeInfo TestTypeInfo => typeof(TestType).GetTypeInfo(); - - [Fact] - public void DeclaredConstructors() - { - List ctors = TestTypeInfo.DeclaredConstructors.ToList(); - Assert.Equal(1, ctors.Count); - Assert.True(ctors[0].IsSpecialName); - Assert.Equal(0, ctors[0].GetParameters().Count()); - } - - [Fact] - public void DeclaredEvents() - { - List events = TestTypeInfo.DeclaredEvents.ToList(); - Assert.Equal(1, events.Count); - Assert.Equal("StuffHappened", events[0].Name); - Assert.Equal("Action`1", events[0].EventHandlerType.Name); - } - - [Fact] - public void GetDeclaredEvent() - { - Assert.Equal("StuffHappened", TestTypeInfo.GetDeclaredEvent("StuffHappened").Name); - } - - [Fact] - public void DeclaredFields() - { - List fields = TestTypeInfo.DeclaredFields.ToList(); - Assert.Equal(2, fields.Count); - FieldInfo stuffHappened = fields.Single(f => f.Name == "StuffHappened"); - Assert.Equal(typeof(Action), stuffHappened.FieldType); - Assert.True(stuffHappened.IsPrivate); - FieldInfo pizzaSize = fields.Single(f => f.Name == "_pizzaSize"); - Assert.Equal(typeof(int), pizzaSize.FieldType); - Assert.True(pizzaSize.IsPrivate); - } - - [Fact] - public void GetDeclaredField() - { - Assert.Equal("_pizzaSize", TestTypeInfo.GetDeclaredField("_pizzaSize").Name); - } - - [Fact] - public void DeclaredMethods() - { - List methods = TestTypeInfo.DeclaredMethods.OrderBy(m => m.Name).ToList(); - Assert.Equal(13, methods.Count); - List methodNames = methods.Select(m => m.Name).ToList(); - Assert.Contains("add_StuffHappened", methodNames); - Assert.Contains("Flush", methodNames); - Assert.Contains("get_CanRead", methodNames); - Assert.Contains("get_CanSeek", methodNames); - Assert.Contains("get_CanWrite", methodNames); - Assert.Contains("get_Length", methodNames); - Assert.Contains("get_Position", methodNames); - Assert.Contains("Read", methodNames); - Assert.Contains("remove_StuffHappened", methodNames); - Assert.Contains("Seek", methodNames); - Assert.Contains("set_Position", methodNames); - Assert.Contains("SetLength", methodNames); - Assert.Contains("Write", methodNames); - } - - [Fact] - public void GetDeclaredMethod() - { - Assert.Equal("Flush", TestTypeInfo.GetDeclaredMethod("Flush").Name); - } - - [Fact] - public void DeclaredNestedTypes() - { - List types = TestTypeInfo.DeclaredNestedTypes.ToList(); - Assert.Equal(1, types.Count); - Assert.Equal("Nested", types[0].Name); - Assert.True(types[0].IsNestedPublic); - } - - [Fact] - public void GetDeclaredNestedType() - { - Assert.Equal("Nested", TestTypeInfo.GetDeclaredNestedType("Nested").Name); - } - - [Fact] - public void DeclaredProperties() - { - List properties = TestTypeInfo.DeclaredProperties.OrderBy(p => p.Name).ToList(); - Assert.Equal(5, properties.Count); - Assert.Equal("CanRead", properties[0].Name); - Assert.Equal("CanSeek", properties[1].Name); - Assert.Equal("CanWrite", properties[2].Name); - Assert.Equal("Length", properties[3].Name); - Assert.Equal("Position", properties[4].Name); - } - - [Fact] - public void GetDeclaredProperty() - { - Assert.Equal("CanRead", TestTypeInfo.GetDeclaredProperty("CanRead").Name); - } - - [Fact] - public void GenericTypeParameters() - { - Type[] parameters = TestTypeInfo.GenericTypeParameters; - Assert.Equal(0, parameters.Length); - } - - [Fact] - public void ImplementedInterfaces() - { - List interfaces = TestTypeInfo.ImplementedInterfaces.OrderBy(t => t.Name).ToList(); - Assert.Equal(1, interfaces.Count); - Assert.Equal(typeof(IDisposable), interfaces[0]); - } - - [Fact] - public void AsType() - { - Type type = TestTypeInfo.AsType(); - Assert.Equal(typeof(TestType), type); - } - - [Theory] - [InlineData(typeof(IDisposable), typeof(Stream))] - [InlineData(typeof(IList), typeof(ArrayList))] - [InlineData(typeof(object), typeof(int))] - [InlineData(typeof(object), typeof(string))] - public void IsAssignableFrom(Type to, Type from) - { - Assert.True(to.GetTypeInfo().IsAssignableFrom(from)); - } - } -} \ No newline at end of file