public void Initialization()
        {
            var declaringType = MutableTypeObjectMother.Create();
            var attributes    = (MethodAttributes)7 | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
            var parameters    = ParameterDeclarationObjectMother.CreateMultiple(2);
            var body          = ExpressionTreeObjectMother.GetSomeExpression(typeof(void));

            var ctor = new MutableConstructorInfo(declaringType, attributes, parameters.AsOneTime(), body);

            Assert.That(ctor.DeclaringType, Is.SameAs(declaringType));
            Assert.That(ctor.MutableDeclaringType, Is.SameAs(declaringType));
            Assert.That(ctor.Name, Is.EqualTo(".ctor"));

            var actualParameters = ctor.GetParameters();

            Assert.That(actualParameters, Has.Length.EqualTo(2));
            CustomParameterInfoTest.CheckParameter(actualParameters[0], ctor, 0, parameters[0].Name, parameters[0].Type, parameters[0].Attributes);
            CustomParameterInfoTest.CheckParameter(actualParameters[1], ctor, 1, parameters[1].Name, parameters[1].Type, parameters[1].Attributes);
            Assert.That(ctor.MutableParameters, Is.EqualTo(actualParameters));

            var paramExpressions = ctor.ParameterExpressions;

            Assert.That(paramExpressions, Has.Count.EqualTo(2));
            Assert.That(paramExpressions[0], Has.Property("Name").EqualTo(parameters[0].Name).And.Property("Type").SameAs(parameters[0].Type));
            Assert.That(paramExpressions[1], Has.Property("Name").EqualTo(parameters[1].Name).And.Property("Type").SameAs(parameters[1].Type));

            Assert.That(ctor.Body, Is.SameAs(body));
        }
Пример #2
0
        public void WireConstructorWithInitialization()
        {
            var counter    = MutableFieldInfoObjectMother.Create(_mutableType, type: typeof(int));
            var initMethod = MutableMethodInfoObjectMother.Create(
                _mutableType, parameters: new[] { ParameterDeclarationObjectMother.Create(typeof(InitializationSemantics)) });
            var initializationMembers = Tuple.Create <FieldInfo, MethodInfo> (counter, initMethod);
            var constructor           = MutableConstructorInfoObjectMother.Create(_mutableType);
            var oldBody = constructor.Body;

            _proxySerializationEnablerMock.Expect(mock => mock.IsDeserializationConstructor(constructor)).Return(false);

            _builder.WireConstructorWithInitialization(constructor, initializationMembers, _proxySerializationEnablerMock);

            _proxySerializationEnablerMock.VerifyAllExpectations();
            var expectedBody = Expression.Block(
                Expression.Assign(
                    Expression.Field(new ThisExpression(_mutableType), counter),
                    Expression.Add(Expression.Field(new ThisExpression(_mutableType), counter), Expression.Constant(1))),
                oldBody,
                Expression.Assign(
                    Expression.Field(new ThisExpression(_mutableType), counter),
                    Expression.Subtract(Expression.Field(new ThisExpression(_mutableType), counter), Expression.Constant(1))),
                Expression.IfThen(
                    Expression.Equal(Expression.Field(new ThisExpression(_mutableType), counter), Expression.Constant(0)),
                    Expression.Call(new ThisExpression(_mutableType), initMethod, Expression.Constant(InitializationSemantics.Construction))));

            ExpressionTreeComparer.CheckAreEqualTrees(expectedBody, constructor.Body);
        }
Пример #3
0
        public void CreateProperty_Providers_ThrowsIfAlreadyExists()
        {
            var factory = new PropertyFactory(new MethodFactory(new RelatedMethodFinder()));

            Func <MethodBodyCreationContext, Expression> setBodyProvider = ctx => Expression.Empty();
            var indexParameters = ParameterDeclarationObjectMother.CreateMultiple(2);
            var property        = _mutableType.AddProperty("Property", typeof(int), indexParameters, setBodyProvider: setBodyProvider);

            Assert.That(
                () => factory.CreateProperty(_mutableType, "OtherName", property.PropertyType, indexParameters, 0, null, setBodyProvider),
                Throws.Nothing);

            Assert.That(
                () => factory.CreateProperty(_mutableType, property.Name, typeof(string), indexParameters, 0, null, setBodyProvider),
                Throws.Nothing);

            Assert.That(
                () => factory.CreateProperty(
                    _mutableType, property.Name, property.PropertyType, ParameterDeclarationObjectMother.CreateMultiple(3), 0, null, setBodyProvider),
                Throws.Nothing);

            Assert.That(
                () => factory.CreateProperty(_mutableType, property.Name, property.PropertyType, indexParameters, 0, null, setBodyProvider),
                Throws.InvalidOperationException.With.Message.EqualTo("Property with equal name and signature already exists."));
        }
Пример #4
0
        public void AddProperty()
        {
            var name                = "Property";
            var attributes          = (PropertyAttributes)7;
            var returnType          = ReflectionObjectMother.GetSomeType();
            var parameters          = ParameterDeclarationObjectMother.CreateMultiple(2);
            var setMethodParameters = parameters.Concat(new[] { ParameterDeclarationObjectMother.Create(returnType) });
            var indexParameterTypes = parameters.Select(p => p.Type).ToArray();
            var getMethod           = MutableMethodInfoObjectMother.Create(returnType: returnType, parameters: parameters);
            var setMethod           = MutableMethodInfoObjectMother.Create(parameters: setMethodParameters);
            var property            = MutablePropertyInfoObjectMother.Create(name: name, attributes: attributes, getMethod: getMethod, setMethod: setMethod);

            var getMethodBuilder = MockRepository.GenerateStub <IMethodBuilder>();
            var setMethodBuilder = MockRepository.GenerateStub <IMethodBuilder>();

            _context.MethodBuilders.Add(getMethod, getMethodBuilder);
            _context.MethodBuilders.Add(setMethod, setMethodBuilder);

            var callingConventions  = CallingConventions.Standard | CallingConventions.HasThis;
            var propertyBuilderMock = MockRepository.GenerateStrictMock <IPropertyBuilder>();

            _typeBuilderMock
            .Expect(mock => mock.DefineProperty(name, attributes, callingConventions, returnType, indexParameterTypes))
            .Return(propertyBuilderMock);
            SetupDefineCustomAttribute(propertyBuilderMock, property);
            propertyBuilderMock.Expect(mock => mock.SetGetMethod(getMethodBuilder));
            propertyBuilderMock.Expect(mock => mock.SetSetMethod(setMethodBuilder));

            _emitter.AddProperty(_context, property);

            _typeBuilderMock.VerifyAllExpectations();
            propertyBuilderMock.VerifyAllExpectations();
        }
Пример #5
0
        public void AddEvent()
        {
            var name         = "Event";
            var attributes   = (EventAttributes)7;
            var handlerType  = typeof(Func <int, string>);
            var addMethod    = MutableMethodInfoObjectMother.Create(parameters: new[] { ParameterDeclarationObjectMother.Create(handlerType) });
            var removeMethod = MutableMethodInfoObjectMother.Create(parameters: new[] { ParameterDeclarationObjectMother.Create(handlerType) });
            var raiseMethod  = MutableMethodInfoObjectMother.Create(
                returnType: typeof(string), parameters: new[] { ParameterDeclarationObjectMother.Create(typeof(int)) });
            var event_ = MutableEventInfoObjectMother.Create(
                name: name, attributes: attributes, addMethod: addMethod, removeMethod: removeMethod, raiseMethod: raiseMethod);

            var addMethodBuilder    = MockRepository.GenerateStub <IMethodBuilder>();
            var removeMethodBuilder = MockRepository.GenerateStub <IMethodBuilder>();
            var raiseMethodBuilder  = MockRepository.GenerateStub <IMethodBuilder>();

            _context.MethodBuilders.Add(addMethod, addMethodBuilder);
            _context.MethodBuilders.Add(removeMethod, removeMethodBuilder);
            _context.MethodBuilders.Add(raiseMethod, raiseMethodBuilder);

            var eventBuilderMock = MockRepository.GenerateStrictMock <IEventBuilder>();

            _typeBuilderMock.Expect(mock => mock.DefineEvent(name, attributes, handlerType)).Return(eventBuilderMock);
            SetupDefineCustomAttribute(eventBuilderMock, event_);
            eventBuilderMock.Expect(mock => mock.SetAddOnMethod(addMethodBuilder));
            eventBuilderMock.Expect(mock => mock.SetRemoveOnMethod(removeMethodBuilder));
            eventBuilderMock.Expect(mock => mock.SetRaiseMethod(raiseMethodBuilder));

            _emitter.AddEvent(_context, event_);

            _typeBuilderMock.VerifyAllExpectations();
            eventBuilderMock.VerifyAllExpectations();
        }
Пример #6
0
        public void SetBody()
        {
            var declaringType     = MutableTypeObjectMother.Create();
            var attribtes         = MethodAttributes.Virtual; // Methods which have a base method must be virtual.
            var returnType        = typeof(object);
            var parameters        = ParameterDeclarationObjectMother.CreateMultiple(2);
            var baseMethod        = ReflectionObjectMother.GetSomeVirtualMethod(); // Base method must be virtual.
            var genericParameters = new[] { MutableGenericParameterObjectMother.Create() };
            var method            = MutableMethodInfoObjectMother.Create(
                declaringType, "Method", attribtes, returnType, parameters, baseMethod, genericParameters: genericParameters);

            var fakeBody = ExpressionTreeObjectMother.GetSomeExpression(typeof(int));
            Func <MethodBodyModificationContext, Expression> bodyProvider = ctx =>
            {
                Assert.That(ctx.DeclaringType, Is.SameAs(declaringType));
                Assert.That(ctx.IsStatic, Is.False);
                Assert.That(ctx.Parameters, Is.EqualTo(method.ParameterExpressions).And.Not.Empty);
                Assert.That(ctx.GenericParameters, Is.EqualTo(genericParameters));
                Assert.That(ctx.ReturnType, Is.SameAs(returnType));
                Assert.That(ctx.BaseMethod, Is.SameAs(baseMethod));
                Assert.That(ctx.PreviousBody, Is.SameAs(method.Body));

                return(fakeBody);
            };

            method.SetBody(bodyProvider);

            var expectedBody = Expression.Convert(fakeBody, returnType);

            ExpressionTreeComparer.CheckAreEqualTrees(expectedBody, method.Body);
        }
Пример #7
0
        public void SetUp()
        {
            _declaringType = CustomTypeObjectMother.Create();
            _attributes    = (MethodAttributes)7 | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
            _parameters    = ParameterDeclarationObjectMother.CreateMultiple(2);

            _constructor = new ConstructorOnCustomType(_declaringType, _attributes, _parameters);
        }
Пример #8
0
        public void CreateProperty_Accessors_ThrowsForDifferentIndexParameters()
        {
            var indexParameters          = new[] { ParameterDeclarationObjectMother.Create(typeof(int)) };
            var valueParameter           = ParameterDeclarationObjectMother.Create(typeof(string));
            var nonMatchingSetParameters = new[] { ParameterDeclarationObjectMother.Create(typeof(long)), valueParameter };
            var getMethod = MutableMethodInfoObjectMother.Create(declaringType: _mutableType, returnType: valueParameter.Type, parameters: indexParameters);
            var setMethod = MutableMethodInfoObjectMother.Create(declaringType: _mutableType, parameters: nonMatchingSetParameters);

            _factory.CreateProperty(_mutableType, "Property", 0, getMethod, setMethod);
        }
Пример #9
0
        public void SetUp()
        {
            _declaringType = CustomTypeObjectMother.Create();
            _name          = "Method";
            _attributes    = (MethodAttributes)7;
            _typeArguments = new[] { ReflectionObjectMother.GetSomeType() };
            _returnType    = ReflectionObjectMother.GetSomeType();
            _parameters    = ParameterDeclarationObjectMother.CreateMultiple(2);

            _method = new MethodOnCustomType(_declaringType, _name, _attributes, _typeArguments, _returnType, _parameters);
        }
        private MutableMethodInfo CreateFakeGenericMethod()
        {
            var genericParameter = MutableGenericParameterObjectMother.Create(position: 0);

            return(MutableMethodInfoObjectMother.Create(
                       _mutableType,
                       attributes: MethodAttributes.Virtual,
                       genericParameters: new[] { genericParameter },
                       returnType: genericParameter,
                       parameters: new[] { ParameterDeclarationObjectMother.Create(typeof(int)), ParameterDeclarationObjectMother.Create(genericParameter) }));
        }
Пример #11
0
        public void CreateProperty_Accessors_ThrowsForDifferentIndexParameters()
        {
            var indexParameters          = new[] { ParameterDeclarationObjectMother.Create(typeof(int)) };
            var valueParameter           = ParameterDeclarationObjectMother.Create(typeof(string));
            var nonMatchingSetParameters = new[] { ParameterDeclarationObjectMother.Create(typeof(long)), valueParameter };
            var getMethod = MutableMethodInfoObjectMother.Create(declaringType: _mutableType, returnType: valueParameter.Type, parameters: indexParameters);
            var setMethod = MutableMethodInfoObjectMother.Create(declaringType: _mutableType, parameters: nonMatchingSetParameters);

            Assert.That(
                () => _factory.CreateProperty(_mutableType, "Property", 0, getMethod, setMethod),
                Throws.ArgumentException
                .With.ArgumentExceptionMessageEqualTo("Get and set accessor methods must have a matching signature.", "setMethod"));
        }
Пример #12
0
        public void SetUp()
        {
            _declaringType   = MutableTypeObjectMother.Create();
            _name            = "Property";
            _attributes      = (PropertyAttributes)7;
            _type            = ReflectionObjectMother.GetSomeType();
            _indexParameters = ParameterDeclarationObjectMother.CreateMultiple(2);
            _getMethod       = MutableMethodInfoObjectMother.Create(returnType: _type, parameters: _indexParameters);
            _setMethod       =
                MutableMethodInfoObjectMother.Create(parameters: _indexParameters.Concat(new[] { ParameterDeclarationObjectMother.Create(_type) }));

            _property = new MutablePropertyInfo(_declaringType, _name, _attributes, _getMethod, _setMethod);
        }
Пример #13
0
        private void CopyMethodBodyAndCheckResult(BodyContextBase context, MethodAttributes methodAttributes)
        {
            var parameter        = ParameterDeclarationObjectMother.CreateMultiple(2);
            var constantBodyPart = ExpressionTreeObjectMother.GetSomeExpression(typeof(int));
            var body             = Expression.Block(parameter[0].Expression, parameter[1].Expression, constantBodyPart);
            var methodToCopy     = MutableMethodInfoObjectMother.Create(
                declaringType: _mutableType, attributes: methodAttributes, returnType: typeof(int), parameters: parameter, body: body);
            var arguments = parameter.Select(p => ExpressionTreeObjectMother.GetSomeExpression(p.Type)).ToArray();

            var result = context.CopyMethodBody(methodToCopy, arguments.AsOneTime());

            var expectedBody = Expression.Block(arguments[0], arguments[1], constantBodyPart);

            ExpressionTreeComparer.CheckAreEqualTrees(expectedBody, result);
        }
        public void CreateExplicitOverride()
        {
            var method = NormalizingMemberInfoFromExpressionUtility.GetMethod((A obj) => obj.OverrideHierarchy(7));
            Func <MethodBodyCreationContext, Expression> bodyProvider = ctx => null;

            var fakeResult = MutableMethodInfoObjectMother.Create(
                _mutableType,
                attributes: MethodAttributes.Virtual,
                parameters: new[] { ParameterDeclarationObjectMother.Create(typeof(int)) });

            _methodFactoryMock
            .Setup(
                mock =>
                mock.CreateMethod(
                    _mutableType,
                    "Remotion.TypePipe.UnitTests.MutableReflection.Implementation.MemberFactory.MethodOverrideFactoryTest.A.OverrideHierarchy",
                    MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.HideBySig,
                    It.Is <IEnumerable <GenericParameterDeclaration> > (param => param.SequenceEqual(GenericParameterDeclaration.None)),
                    It.IsAny <Func <GenericParameterContext, Type> >(),
                    It.IsAny <Func <GenericParameterContext, IEnumerable <ParameterDeclaration> > >(),
                    bodyProvider))
            .Returns(fakeResult)
            .Callback(
                (
                    MutableType declaringType,
                    string nameArgument,
                    MethodAttributes attributes,
                    IEnumerable <GenericParameterDeclaration> genericParameters,
                    Func <GenericParameterContext, Type> returnTypeProvider,
                    Func <GenericParameterContext, IEnumerable <ParameterDeclaration> > parameterProvider,
                    Func <MethodBodyCreationContext, Expression> bodyProviderArg) =>
            {
                var returnType = returnTypeProvider(_noGenericParameters);
                var parameters = parameterProvider(_noGenericParameters);

                Assert.That(returnType, Is.SameAs(typeof(void)));
                var parameter = parameters.Single();
                Assert.That(parameter.Name, Is.EqualTo("aaa"));
                Assert.That(parameter.Type, Is.SameAs(typeof(int)));
            })
            .Verifiable();

            var result = _factory.CreateExplicitOverride(_mutableType, method, bodyProvider);

            _methodFactoryMock.Verify();
            Assert.That(result, Is.SameAs(fakeResult));
            Assert.That(result.AddedExplicitBaseDefinitions, Is.EqualTo(new[] { method }));
        }
Пример #15
0
        public void CreateEvent_Accessors_ThrowsIfAlreadyExists()
        {
            var addRemoveMethod = MutableMethodInfoObjectMother.Create(
                _mutableType, parameters: new[] { ParameterDeclarationObjectMother.Create(typeof(Action)) });
            var differentHandlerAddRemoveMethod = MutableMethodInfoObjectMother.Create(
                _mutableType, parameters: new[] { ParameterDeclarationObjectMother.Create(typeof(Func <int>)) });
            var event_ = _mutableType.AddEvent2("Event", addMethod: addRemoveMethod, removeMethod: addRemoveMethod);

            Assert.That(() => _factory.CreateEvent(_mutableType, "OtherName", 0, addRemoveMethod, addRemoveMethod, null), Throws.Nothing);
            Assert.That(
                () => _factory.CreateEvent(_mutableType, event_.Name, 0, differentHandlerAddRemoveMethod, differentHandlerAddRemoveMethod, null),
                Throws.Nothing);
            Assert.That(
                () => _factory.CreateEvent(_mutableType, event_.Name, 0, addRemoveMethod, addRemoveMethod, null),
                Throws.InvalidOperationException.With.Message.EqualTo("Event with equal name and signature already exists."));
        }
Пример #16
0
        public void AddConstructor()
        {
            var attributes = (MethodAttributes)7;
            var parameters = ParameterDeclarationObjectMother.CreateMultiple(2);
            Func <ConstructorBodyCreationContext, Expression> bodyProvider = ctx => null;
            var fakeConstructor = MutableConstructorInfoObjectMother.Create();

            _mutableMemberFactoryMock
            .Expect(mock => mock.CreateConstructor(_mutableType, attributes, parameters, bodyProvider))
            .Return(fakeConstructor);

            var result = _mutableType.AddConstructor(attributes, parameters, bodyProvider);

            _mutableMemberFactoryMock.VerifyAllExpectations();
            Assert.That(result, Is.SameAs(fakeConstructor));
            Assert.That(_mutableType.AddedConstructors, Is.EqualTo(new[] { result }));
        }
Пример #17
0
        public void CreateMethod_Static()
        {
            var name                  = "StaticMethod";
            var attributes            = MethodAttributes.Static;
            var returnType            = ReflectionObjectMother.GetSomeType();
            var parameterDeclarations = ParameterDeclarationObjectMother.CreateMultiple(2);

            Func <MethodBodyCreationContext, Expression> bodyProvider = ctx =>
            {
                Assert.That(ctx.IsStatic, Is.True);

                return(ExpressionTreeObjectMother.GetSomeExpression(returnType));
            };
            var method = CallCreateMethod(_mutableType, name, attributes, returnType, parameterDeclarations, bodyProvider);

            Assert.That(method.IsStatic, Is.True);
        }
Пример #18
0
        public void CreateProperty_Accessors()
        {
            var name       = "Property";
            var attributes = (PropertyAttributes)7;
            var type       = ReflectionObjectMother.GetSomeType();
            var getMethod  = MutableMethodInfoObjectMother.Create(declaringType: _mutableType, returnType: type);
            var setMethod  = MutableMethodInfoObjectMother.Create(
                declaringType: _mutableType, parameters: new[] { ParameterDeclarationObjectMother.Create(type) });

            var result = _factory.CreateProperty(_mutableType, name, attributes, getMethod, setMethod);

            Assert.That(result.DeclaringType, Is.SameAs(_mutableType));
            Assert.That(result.Name, Is.EqualTo(name));
            Assert.That(result.Attributes, Is.EqualTo(attributes));
            Assert.That(result.MutableGetMethod, Is.SameAs(getMethod));
            Assert.That(result.MutableSetMethod, Is.SameAs(setMethod));
        }
Пример #19
0
        public void CreateMethod_ThrowsIfAlreadyExists()
        {
            Func <MethodBodyCreationContext, Expression> bodyProvider = ctx => Expression.Empty();
            var method           = _mutableType.AddMethod("Method", 0, typeof(void), ParameterDeclarationObjectMother.CreateMultiple(2), bodyProvider);
            var methodParameters = method.GetParameters().Select(p => new ParameterDeclaration(p.ParameterType, p.Name, p.Attributes));

            Assert.That(() => CallCreateMethod(_mutableType, "OtherName", 0, method.ReturnType, methodParameters, bodyProvider), Throws.Nothing);

            Assert.That(
                () => CallCreateMethod(_mutableType, method.Name, 0, typeof(int), methodParameters, ctx => Expression.Constant(7)), Throws.Nothing);

            Assert.That(
                () => CallCreateMethod(_mutableType, method.Name, 0, method.ReturnType, ParameterDeclarationObjectMother.CreateMultiple(3), bodyProvider),
                Throws.Nothing);

            Assert.That(
                () => CallCreateMethod(_mutableType, method.Name, 0, method.ReturnType, methodParameters, bodyProvider),
                Throws.InvalidOperationException.With.Message.EqualTo("Method with equal name and signature already exists."));
        }
Пример #20
0
        public void CreateConstructor_ThrowsIfAlreadyExists()
        {
            _mutableType.AddConstructor(parameters: ParameterDeclaration.None);

            Func <ConstructorBodyCreationContext, Expression> bodyProvider = ctx => Expression.Empty();

            Assert.That(
                () => _factory.CreateConstructor(_mutableType, 0, ParameterDeclarationObjectMother.CreateMultiple(2), bodyProvider),
                Throws.Nothing);

            Assert.That(
                () =>
                _factory.CreateConstructor(_mutableType, MethodAttributes.Static, ParameterDeclaration.None, bodyProvider),
                Throws.Nothing);

            Assert.That(
                () => _factory.CreateConstructor(_mutableType, 0, ParameterDeclaration.None, bodyProvider),
                Throws.InvalidOperationException.With.Message.EqualTo("Constructor with equal signature already exists."));
        }
Пример #21
0
        public void AddMethod_GenericMethodDefinition()
        {
            var baseTypeConstraint  = typeof(DomainType);
            var interfaceConstraint = typeof(IDisposable);

            Assert.That(baseTypeConstraint.GetInterfaces(), Is.Not.Empty);
            Assert.That(baseTypeConstraint.GetInterfaces(), Has.No.Member(interfaceConstraint));

            var genericParameter = MutableGenericParameterObjectMother.Create(
                name: "TParam",
                genericParameterAttributes: (GenericParameterAttributes)7,
                constraints: new[] { baseTypeConstraint, interfaceConstraint });
            var method = MutableMethodInfoObjectMother.Create(
                genericParameters: new[] { genericParameter },
                returnType: genericParameter,
                parameters: new[] { ParameterDeclarationObjectMother.Create(genericParameter, "genericParam") });

            var methodBuilderMock = new Mock <IMethodBuilder> (MockBehavior.Strict);

            _typeBuilderMock.Setup(mock => mock.DefineMethod(method.Name, method.Attributes)).Returns(methodBuilderMock.Object);
            methodBuilderMock.Setup(mock => mock.RegisterWith(_emittableOperandProviderMock.Object, method));

            var genericParameterBuilderMock = new Mock <IGenericTypeParameterBuilder> (MockBehavior.Strict);

            methodBuilderMock.Setup(mock => mock.DefineGenericParameters(new[] { "TParam" })).Returns(new[] { genericParameterBuilderMock.Object }).Verifiable();
            genericParameterBuilderMock.Setup(mock => mock.RegisterWith(_emittableOperandProviderMock.Object, genericParameter)).Verifiable();
            genericParameterBuilderMock.Setup(mock => mock.SetGenericParameterAttributes((GenericParameterAttributes)7)).Verifiable();
            genericParameterBuilderMock.Setup(mock => mock.SetBaseTypeConstraint(baseTypeConstraint)).Verifiable();
            genericParameterBuilderMock.Setup(mock => mock.SetInterfaceConstraints(new[] { interfaceConstraint })).Verifiable();
            SetupDefineCustomAttribute(genericParameterBuilderMock, genericParameter);

            methodBuilderMock.Setup(mock => mock.SetReturnType(genericParameter)).Verifiable();
            methodBuilderMock.Setup(mock => mock.SetParameters(new Type[] { genericParameter })).Verifiable();
            SetupDefineParameter(methodBuilderMock, 0, null, ParameterAttributes.None);
            SetupDefineParameter(methodBuilderMock, 1, "genericParam", ParameterAttributes.None);

            _emitter.AddMethod(_context, method);

            methodBuilderMock.Verify();
            genericParameterBuilderMock.Verify();
        }
Пример #22
0
        public void CreateProperty_Accessors_ThrowsIfAlreadyExists()
        {
            var returnType = ReflectionObjectMother.GetSomeType();
            var getMethod  = MutableMethodInfoObjectMother.Create(declaringType: _mutableType, returnType: returnType);
            var property   = _mutableType.AddProperty2("Property", getMethod: getMethod);

            Assert.That(() => _factory.CreateProperty(_mutableType, "OtherName", 0, getMethod, null), Throws.Nothing);

            var differentPropertyType = ReflectionObjectMother.GetSomeOtherType();
            var getMethod2            = MutableMethodInfoObjectMother.Create(declaringType: _mutableType, returnType: differentPropertyType);

            Assert.That(() => _factory.CreateProperty(_mutableType, property.Name, 0, getMethod2, null), Throws.Nothing);

            var differentIndexParameters = ParameterDeclarationObjectMother.CreateMultiple(2);
            var getMethod3 = MutableMethodInfoObjectMother.Create(declaringType: _mutableType, returnType: returnType, parameters: differentIndexParameters);

            Assert.That(() => _factory.CreateProperty(_mutableType, property.Name, 0, getMethod3, null), Throws.Nothing);

            Assert.That(
                () => _factory.CreateProperty(_mutableType, property.Name, 0, getMethod, null),
                Throws.InvalidOperationException.With.Message.EqualTo("Property with equal name and signature already exists."));
        }
Пример #23
0
        public void CreateConstructor()
        {
            var attributes = MethodAttributes.Public;
            var parameters =
                new[]
            {
                ParameterDeclarationObjectMother.Create(typeof(string), "param1"),
                ParameterDeclarationObjectMother.Create(typeof(int), "param2")
            };
            var fakeBody = ExpressionTreeObjectMother.GetSomeExpression(typeof(object));
            Func <ConstructorBodyCreationContext, Expression> bodyProvider = ctx =>
            {
                Assert.That(ctx.This.Type, Is.SameAs(_mutableType));
                Assert.That(ctx.IsStatic, Is.False);
                Assert.That(ctx.Parameters.Select(p => p.Type), Is.EqualTo(new[] { typeof(string), typeof(int) }));
                Assert.That(ctx.Parameters.Select(p => p.Name), Is.EqualTo(new[] { "param1", "param2" }));

                return(fakeBody);
            };

            var ctor = _factory.CreateConstructor(_mutableType, attributes, parameters.AsOneTime(), bodyProvider);

            Assert.That(ctor.DeclaringType, Is.SameAs(_mutableType));
            Assert.That(ctor.Name, Is.EqualTo(".ctor"));
            Assert.That(ctor.Attributes, Is.EqualTo(attributes | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName));
            var expectedParameterInfos =
                new[]
            {
                new { ParameterType = parameters[0].Type },
                new { ParameterType = parameters[1].Type }
            };
            var actualParameterInfos = ctor.GetParameters().Select(pi => new { pi.ParameterType });

            Assert.That(actualParameterInfos, Is.EqualTo(expectedParameterInfos));
            var expectedBody = Expression.Block(typeof(void), fakeBody);

            ExpressionTreeComparer.CheckAreEqualTrees(expectedBody, ctor.Body);
        }
Пример #24
0
        public void Initialization()
        {
            var declaringType = MutableTypeObjectMother.Create();
            var name          = "abc";
            var attributes    = (MethodAttributes)7 | MethodAttributes.Virtual;
            var returnType    = ReflectionObjectMother.GetSomeType();
            var parameters    = ParameterDeclarationObjectMother.CreateMultiple(2);
            var baseMethod    = ReflectionObjectMother.GetSomeVirtualMethod();
            var body          = ExpressionTreeObjectMother.GetSomeExpression(returnType);

            var method = new MutableMethodInfo(
                declaringType, name, attributes, new MutableGenericParameter[0], returnType, parameters.AsOneTime(), baseMethod, body);

            Assert.That(method.DeclaringType, Is.SameAs(declaringType));
            Assert.That(method.MutableDeclaringType, Is.SameAs(declaringType));
            Assert.That(method.Name, Is.EqualTo(name));
            Assert.That(method.Attributes, Is.EqualTo(attributes));
            Assert.That(method.IsGenericMethod, Is.False);

            CustomParameterInfoTest.CheckParameter(method.ReturnParameter, method, -1, null, returnType, ParameterAttributes.None);
            Assert.That(method.MutableReturnParameter, Is.SameAs(method.ReturnParameter));

            var actualParameters = method.GetParameters();

            Assert.That(actualParameters, Has.Length.EqualTo(2));
            CustomParameterInfoTest.CheckParameter(actualParameters[0], method, 0, parameters[0].Name, parameters[0].Type, parameters[0].Attributes);
            CustomParameterInfoTest.CheckParameter(actualParameters[1], method, 1, parameters[1].Name, parameters[1].Type, parameters[1].Attributes);
            Assert.That(method.MutableParameters, Is.EqualTo(actualParameters));

            var paramExpressions = method.ParameterExpressions;

            Assert.That(paramExpressions, Has.Count.EqualTo(2));
            Assert.That(paramExpressions[0], Has.Property("Name").EqualTo(parameters[0].Name).And.Property("Type").SameAs(parameters[0].Type));
            Assert.That(paramExpressions[1], Has.Property("Name").EqualTo(parameters[1].Name).And.Property("Type").SameAs(parameters[1].Type));

            Assert.That(method.BaseMethod, Is.SameAs(baseMethod));
            Assert.That(method.Body, Is.SameAs(body));
        }
Пример #25
0
        public void AddProperty_Simple()
        {
            var name               = "Property";
            var type               = ReflectionObjectMother.GetSomeType();
            var indexParameters    = ParameterDeclarationObjectMother.CreateMultiple(2);
            var accessorAttributes = (MethodAttributes)7;
            Func <MethodBodyCreationContext, Expression> getBodyProvider = ctx => null;
            Func <MethodBodyCreationContext, Expression> setBodyProvider = ctx => null;
            var fakeProperty = MutablePropertyInfoObjectMother.CreateReadWrite();

            _mutableMemberFactoryMock
            .Expect(mock => mock.CreateProperty(_mutableType, name, type, indexParameters, accessorAttributes, getBodyProvider, setBodyProvider))
            .Return(fakeProperty);

            var result = _mutableType.AddProperty(name, type, indexParameters, accessorAttributes, getBodyProvider, setBodyProvider);

            _mutableMemberFactoryMock.VerifyAllExpectations();
            Assert.That(result, Is.SameAs(fakeProperty));
            Assert.That(_mutableType.AddedProperties, Is.EqualTo(new[] { result }));
            Assert.That(_mutableType.AddedMethods, Is.EqualTo(new[] { result.MutableGetMethod, result.MutableSetMethod }));
            Assert.That(result.MutableGetMethod.Attributes, Is.EqualTo(accessorAttributes));
            Assert.That(result.MutableSetMethod.Attributes, Is.EqualTo(accessorAttributes));
        }
Пример #26
0
        public void AddProperty_Simple_WriteOnlyProperty()
        {
            var type = ReflectionObjectMother.GetSomeType();
            Func <MethodBodyCreationContext, Expression> setBodyProvider = ctx => null;
            var fakeSetMethod = MutableMethodInfoObjectMother.Create(parameters: new[] { ParameterDeclarationObjectMother.Create(type) });
            var fakeProperty  = MutablePropertyInfoObjectMother.Create(setMethod: fakeSetMethod);

            Assert.That(fakeProperty.MutableGetMethod, Is.Null);
            _mutableMemberFactoryMock
            .Stub(stub => stub.CreateProperty(_mutableType, "Property", type, ParameterDeclaration.None, MethodAttributes.Public, null, setBodyProvider))
            .Return(fakeProperty);

            _mutableType.AddProperty("Property", type, setBodyProvider: setBodyProvider);

            Assert.That(_mutableType.AddedMethods, Is.EqualTo(new[] { fakeSetMethod }));
        }
Пример #27
0
 private MutableMethodInfo CreateInitializationMethod(MutableType declaringType)
 {
     return(MutableMethodInfoObjectMother.Create(
                declaringType, returnType: typeof(void), parameters: new[] { ParameterDeclarationObjectMother.Create(typeof(InitializationSemantics)) }));
 }
Пример #28
0
        public void CreateProperty_Providers_WriteOnly()
        {
            var type = ReflectionObjectMother.GetSomeType();
            Func <MethodBodyCreationContext, Expression> setBodyProvider = ctx => ExpressionTreeObjectMother.GetSomeExpression(typeof(void));
            var fakeSetMethod = MutableMethodInfoObjectMother.Create(parameters: new[] { ParameterDeclarationObjectMother.Create(type) });

            _methodFactoryMock
            .Setup(
                stub => stub.CreateMethod(
                    It.IsAny <MutableType>(),
                    "set_Property",
                    It.IsAny <MethodAttributes>(),
                    It.IsAny <IEnumerable <GenericParameterDeclaration> >(),
                    It.IsAny <Func <GenericParameterContext, Type> >(),
                    It.IsAny <Func <GenericParameterContext, IEnumerable <ParameterDeclaration> > >(),
                    It.IsAny <Func <MethodBodyCreationContext, Expression> >()))
            .Returns(fakeSetMethod);

            var result = _factory.CreateProperty(
                _mutableType,
                "Property",
                type,
                ParameterDeclaration.None,
                0,
                getBodyProvider: null,
                setBodyProvider: setBodyProvider);

            Assert.That(result.MutableGetMethod, Is.Null);
        }
Пример #29
0
        public void CreateProperty_Providers()
        {
            var name               = "Property";
            var propertyType       = ReflectionObjectMother.GetSomeType();
            var indexParameters    = ParameterDeclarationObjectMother.CreateMultiple(2).ToList();
            var accessorAttributes = (MethodAttributes)7;
            var setterParameters   = indexParameters.Concat(new[] { ParameterDeclarationObjectMother.Create(propertyType, "value") }).ToList();
            Func <MethodBodyCreationContext, Expression> getBodyProvider = ctx => null;
            Func <MethodBodyCreationContext, Expression> setBodyProvider = ctx => null;

            var fakeGetMethod = MutableMethodInfoObjectMother.Create(returnType: propertyType, parameters: indexParameters);
            var fakeSetMethod = MutableMethodInfoObjectMother.Create(parameters: setterParameters);

            _methodFactoryMock
            .Setup(
                mock => mock.CreateMethod(
                    _mutableType,
                    "get_Property",
                    accessorAttributes | MethodAttributes.SpecialName,
                    GenericParameterDeclaration.None,
                    It.IsAny <Func <GenericParameterContext, Type> >(),
                    It.IsAny <Func <GenericParameterContext, IEnumerable <ParameterDeclaration> > >(),
                    getBodyProvider))
            .Callback(
                (
                    MutableType declaringType,
                    string nameArgument,
                    MethodAttributes attributes,
                    IEnumerable <GenericParameterDeclaration> genericParameters,
                    Func <GenericParameterContext, Type> returnTypeProvider,
                    Func <GenericParameterContext, IEnumerable <ParameterDeclaration> > parameterProvider,
                    Func <MethodBodyCreationContext, Expression> bodyProvider) =>
            {
                var returnType = returnTypeProvider(null);
                Assert.That(returnType, Is.SameAs(propertyType));

                var parameters = parameterProvider(null).ToList();
                Assert.That(parameters.Select(p => p.Type), Is.EqualTo(indexParameters.Select(p => p.Type)));
                Assert.That(parameters.Select(p => p.Name), Is.EqualTo(indexParameters.Select(p => p.Name)));
            })
            .Returns(fakeGetMethod);
            _methodFactoryMock
            .Setup(
                mock => mock.CreateMethod(
                    _mutableType,
                    "set_Property",
                    (accessorAttributes | MethodAttributes.SpecialName),
                    GenericParameterDeclaration.None,
                    It.IsAny <Func <GenericParameterContext, Type> >(),
                    It.IsAny <Func <GenericParameterContext, IEnumerable <ParameterDeclaration> > >(),
                    setBodyProvider))
            .Callback(
                (
                    MutableType declaringType,
                    string nameArgument,
                    MethodAttributes attributes,
                    IEnumerable <GenericParameterDeclaration> genericParameters,
                    Func <GenericParameterContext, Type> returnTypeProvider,
                    Func <GenericParameterContext, IEnumerable <ParameterDeclaration> > parameterProvider,
                    Func <MethodBodyCreationContext, Expression> bodyProvider) =>
            {
                var returnType = returnTypeProvider(null);
                Assert.That(returnType, Is.SameAs(typeof(void)));

                var parameters = parameterProvider(null).ToList();
                Assert.That(parameters.Select(p => p.Type), Is.EqualTo(setterParameters.Select(p => p.Type)));
                Assert.That(parameters.Select(p => p.Name), Is.EqualTo(setterParameters.Select(p => p.Name)));
            })
            .Returns(fakeSetMethod)
            .Verifiable();

            var result = _factory.CreateProperty(
                _mutableType, name, propertyType, indexParameters.AsOneTime(), accessorAttributes, getBodyProvider, setBodyProvider);

            _methodFactoryMock.Verify();
            Assert.That(result.DeclaringType, Is.SameAs(_mutableType));
            Assert.That(result.Name, Is.EqualTo(name));
            Assert.That(result.Attributes, Is.EqualTo(PropertyAttributes.None));
            Assert.That(result.PropertyType, Is.SameAs(propertyType));
            Assert.That(result.MutableGetMethod, Is.SameAs(fakeGetMethod));
            Assert.That(result.MutableSetMethod, Is.SameAs(fakeSetMethod));
        }
Пример #30
0
        public void AddProperty_ReadOnly_WriteOnly()
        {
            var staticGetMethod   = MutableMethodInfoObjectMother.Create(attributes: MethodAttributes.Static, returnType: typeof(int));
            var setMethod         = MutableMethodInfoObjectMother.Create(parameters: new[] { ParameterDeclarationObjectMother.Create(typeof(long)) });
            var readOnlyProperty  = MutablePropertyInfoObjectMother.Create(getMethod: staticGetMethod);
            var writeOnlyProperty = MutablePropertyInfoObjectMother.Create(setMethod: setMethod);

            Assert.That(readOnlyProperty.MutableSetMethod, Is.Null);
            Assert.That(writeOnlyProperty.MutableGetMethod, Is.Null);

            var methodBuilder = MockRepository.GenerateStub <IMethodBuilder>();

            _context.MethodBuilders.Add(readOnlyProperty.MutableGetMethod, methodBuilder);
            _context.MethodBuilders.Add(writeOnlyProperty.MutableSetMethod, methodBuilder);

            var propertyBuilderMock1 = MockRepository.GenerateStrictMock <IPropertyBuilder>();
            var propertyBuilderMock2 = MockRepository.GenerateStrictMock <IPropertyBuilder>();

            _typeBuilderMock
            .Expect(mock => mock.DefineProperty(readOnlyProperty.Name, readOnlyProperty.Attributes, staticGetMethod.CallingConvention, typeof(int), Type.EmptyTypes))
            .Return(propertyBuilderMock1);
            _typeBuilderMock
            .Expect(mock => mock.DefineProperty(writeOnlyProperty.Name, writeOnlyProperty.Attributes, setMethod.CallingConvention, typeof(long), Type.EmptyTypes))
            .Return(propertyBuilderMock2);
            propertyBuilderMock1.Expect(mock => mock.SetGetMethod(methodBuilder));
            propertyBuilderMock2.Expect(mock => mock.SetSetMethod(methodBuilder));

            _emitter.AddProperty(_context, readOnlyProperty);
            _emitter.AddProperty(_context, writeOnlyProperty);

            _typeBuilderMock.VerifyAllExpectations();
            propertyBuilderMock1.VerifyAllExpectations();
            propertyBuilderMock2.VerifyAllExpectations();
        }