Example #1
0
        internal static PropertyInfo ResolveProperty(Type type, string name, bool ignoreCase, object[] indexArgs, bool hasInstance, object setterValue = null, bool getter = true)
        {
            var candidates = type.GetAllProperties().Where(prop => MockingUtil.StringEqual(prop.Name, name, ignoreCase)).ToArray();

            if (candidates.Length == 1)
            {
                return(candidates[0]);
            }

            if (!getter)
            {
                Array.Resize(ref indexArgs, indexArgs.Length + 1);
                indexArgs[indexArgs.Length - 1] = setterValue;
            }

            var propMethods = candidates
                              .Select(prop => getter ? prop.GetGetMethod(true) : prop.GetSetMethod(true))
                              .Where(m => m != null && CanCall(m, hasInstance))
                              .ToArray();

            indexArgs = indexArgs ?? MockingUtil.NoObjects;
            object state;
            var    foundGetter = MockingUtil.BindToMethod(MockingUtil.AllMembers, propMethods, ref indexArgs, null, null, null, out state);

            return(candidates.First(prop => (getter ? prop.GetGetMethod(true) : prop.GetSetMethod(true)) == foundGetter));
        }
        public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
        {
            var wrapper   = this.Value as ExpressionContainer;
            var valueExpr = wrapper.Expression;

            var typeArgs = MockingUtil.TryGetTypeArgumentsFromBinder(binder);

            var candidateMethods = valueExpr.Type.GetAllMethods()
                                   .Where(m => MockingUtil.StringEqual(m.Name, binder.Name, binder.IgnoreCase) && m.IsStatic == wrapper.IsStatic)
                                   .Where(m => m.GetParameters().Length >= args.Length)
                                   .Select(m =>
            {
                if (typeArgs == null)
                {
                    return(MockingUtil.TrySpecializeGenericMethod(m, args.Select(a => a.RuntimeType).ToArray()) ?? m);
                }
                else
                {
                    return(MockingUtil.TryApplyTypeArguments(m, typeArgs));
                }
            })
                                   .Where(m => m != null)
                                   .Where(m =>
            {
                var methodParams = m.GetParameters();
                for (int i = 0; i < args.Length; ++i)
                {
                    var matcher = UnwrapMatcher(args[i]);
                    if (matcher != null)
                    {
                        var argType = matcher.ReturnType;
                        if (!methodParams[i].ParameterType.IsAssignableFrom(argType))
                        {
                            return(false);
                        }
                    }
                }
                return(true);
            })
                                   .ToArray();

            if (candidateMethods.Length == 0 && args.Length == 0)
            {
                return(DoBindGetMember(binder.ReturnType, binder.Name, binder.IgnoreCase));
            }

            var methodArgs = args.Select(a =>
            {
                var matcher = UnwrapMatcher(a);
                return(matcher != null ? matcher.ReturnType.GetDefaultValue() : a.Value);
            }).ToArray();

            object state;
            var    method = (MethodInfo)MockingUtil.BindToMethod(MockingUtil.Default, candidateMethods, ref methodArgs, null, null, null, out state);

            var memberExpr = Expression.Call(!wrapper.IsStatic ? valueExpr : null, method, args.Select(FromArg).ToArray());

            return(CreateRecorder(memberExpr, binder.ReturnType, BindingRestrictions.GetInstanceRestriction(this.Expression, this.Value)));
        }
        /// <summary>
        /// Calls the specified method by name.
        /// </summary>
        /// <param name="name">The name of the method to call.</param>
        /// <param name="args">Arguments to pass to the method.</param>
        /// <returns>The value returned by the specified method.</returns>
        public object CallMethod(string name, params object[] args)
        {
            return(ProfilerInterceptor.GuardInternal(() =>
            {
                args = args ?? MockingUtil.NoObjects;
                var candidates = type.GetAllMethods()
                                 .Where(m => m.Name == name && CanCall(m))
                                 .ToArray();
                object state;
                var method = MockingUtil.BindToMethod(MockingUtil.AllMembers,
                                                      candidates, ref args, null, null, null, out state);

                return CallInvoke(method, args);
            }));
        }
Example #4
0
        /// <summary>
        /// Calls the specified method by name.
        /// </summary>
        /// <param name="name">The name of the method to call.</param>
        /// <param name="args">Arguments to pass to the method.</param>
        /// <returns>The value returned by the specified method.</returns>
        public object CallMethod(string name, params object[] args)
        {
            return(ProfilerInterceptor.GuardInternal(() =>
            {
                args = args ?? MockingUtil.NoObjects;
                var candidates = type.GetAllMethods()
                                 .Where(m => m.Name == name && CanCall(m, this.instance != null))
                                 .Select(m => MockingUtil.TrySpecializeGenericMethod(m, args.Select(a => a != null ? a.GetType() : null).ToArray()) ?? m)
                                 .ToArray();
                object state;
                var method = MockingUtil.BindToMethod(MockingUtil.AllMembers,
                                                      candidates, ref args, null, null, null, out state);

                return CallInvoke(method, args);
            }));
        }
Example #5
0
        /// <summary>
        /// Calls the specified generic method by name.
        /// </summary>
        /// <param name="name">The name of the method to call.</param>
        /// <param name="typeArguments">The type arguments to specialize the generic method.</param>
        /// <param name="args">Arguments to pass to the method.</param>
        /// <returns>The value returned by the specified method.</returns>
        public object CallMethodWithTypeArguments(string name, ICollection <Type> typeArguments, params object[] args)
        {
            return(ProfilerInterceptor.GuardInternal(() =>
            {
                var candidates = type.GetAllMethods()
                                 .Where(m => m.Name == name && CanCall(m, this.instance != null))
                                 .Select(m => MockingUtil.TryApplyTypeArguments(m, typeArguments.ToArray()))
                                 .Where(m => m != null)
                                 .ToArray();

                args = args ?? MockingUtil.NoObjects;
                object state;
                var method = MockingUtil.BindToMethod(MockingUtil.AllMembers,
                                                      candidates, ref args, null, null, null, out state);

                return CallInvoke(method, args);
            }));
        }
Example #6
0
        private static bool NodeMatchesFilter(CallPattern callPattern, IMatcherTreeNode node)
        {
            var filter = callPattern.Filter;

            if (filter == null)
            {
                return(true);
            }

            var args     = new List <object>();
            var nodeIter = node;

            while (nodeIter != null)
            {
                var valueMatcher = nodeIter.Matcher as IValueMatcher;
                if (valueMatcher != null)
                {
                    args.Add(valueMatcher.Value);
                }
                nodeIter = nodeIter.Parent;
            }

            if (!callPattern.Method.IsStatic && filter.Method.GetParameters().Length + 1 == args.Count)
            {
                args.RemoveAt(args.Count - 1);
            }

            args.Reverse();
            var argsArray = args.ToArray();

            object state;

            MockingUtil.BindToMethod(MockingUtil.Default, new[] { filter.Method }, ref argsArray, null, null, null, out state);

            var filterFunc = MockingUtil.MakeFuncCaller(filter);
            var isMatch    = (bool)ProfilerInterceptor.GuardExternal(() => filterFunc(argsArray, filter));

            DebugView.TraceEvent(IndentLevel.Matcher, () => String.Format("Matcher predicate {0} call to {2} with arguments ({1})",
                                                                          isMatch ? "passed" : "rejected", String.Join(", ", args.Select(x => x.ToString()).ToArray()),
                                                                          callPattern.Method));

            return(isMatch);
        }
Example #7
0
        public void RaiseEvent(EventInfo evt, object[] delegateArguments)
        {
            Delegate existing;

            eventHandlers.TryGetValue(evt, out existing);

            if (existing != null)
            {
                try
                {
                    object state;
                    MockingUtil.BindToMethod(MockingUtil.Default, new[] { existing.Method }, ref delegateArguments, null, null, null, out state);
                }
                catch (MissingMethodException ex)
                {
                    throw new MockException(String.Format("Event signature {0} is incompatible with argument types ({1})",
                                                          existing.Method, String.Join(", ", delegateArguments.Select(x => x != null ? x.GetType().ToString() : "null").ToArray())
                                                          ), ex);
                }

                var invoker = MockingUtil.MakeFuncCaller(existing);
                ProfilerInterceptor.GuardExternal(() => invoker(delegateArguments, existing));
            }
        }