コード例 #1
0
        public void Register(object proxy, ICallRouter callRouter)
        {
            if (proxy is ICallRouter) return;
            if (proxy is ICallRouterProvider) return;

            _callRouterMappings.AddOrUpdate(proxy, callRouter, (o,c) => callRouter);
        }
コード例 #2
0
 public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, object[] constructorArguments)
 {
     var isDelegate = typeToProxy.IsSubclassOf(typeof(Delegate));
     return isDelegate 
         ? _delegateFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, constructorArguments)
         : _dynamicProxyFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, constructorArguments);
 }
コード例 #3
0
 public DelegateCall(ICallRouter callRouter, Type delegateType, Type returnType, IParameterInfo[] parameterInfos)
 {
     _callRouter     = callRouter;
     _delegateType   = delegateType;
     _returnType     = returnType;
     _parameterInfos = parameterInfos;
     _methodToInvoke = GetMethodToInvoke();
 }
コード例 #4
0
 public WhenCalled(ISubstitutionContext context, T substitute, Action <T> call, MatchArgs matchArgs)
 {
     _substitute   = substitute;
     _call         = call;
     _matchArgs    = matchArgs;
     _callRouter   = context.GetCallRouterFor(substitute);
     _routeFactory = context.RouteFactory;
 }
コード例 #5
0
ファイル: ProxyFactory.cs プロジェクト: toddswift/NSubstitute
        public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, object[] constructorArguments)
        {
            var isDelegate = typeToProxy.IsDelegate();

            return(isDelegate
                ? _delegateFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, constructorArguments)
                : _dynamicProxyFactory.GenerateProxy(callRouter, typeToProxy, additionalInterfaces, constructorArguments));
        }
コード例 #6
0
 private CastleForwardingInterceptor CreateForwardingInterceptor(ICallRouter callRouter)
 {
     return(new CastleForwardingInterceptor(
                new CastleInvocationMapper(
                    _callFactory,
                    _argSpecificationDequeue),
                callRouter));
 }
コード例 #7
0
 public void Register(object proxy, ICallRouter callRouter)
 {
     if (proxy is ICallRouter)
     {
         return;
     }
     _callRouterMappings.Add(proxy, callRouter);
 }
コード例 #8
0
 void RaiseEventIfSet(ICallRouter callRouter)
 {
     if (_getArgumentsForRaisingEvent.Value != null)
     {
         callRouter.SetRoute <RaiseEventRoute>(_getArgumentsForRaisingEvent.Value);
         _getArgumentsForRaisingEvent.Value = null;
     }
 }
コード例 #9
0
 public override void Context()
 {
     _substitute = new object();
     _routerForSubstitute = mock<ICallRouter>();
     var context = mock<ISubstitutionContext>();
     context.stub(x => x.GetCallRouterFor(_substitute)).Return(_routerForSubstitute);
     temporarilyChange(() => SubstitutionContext.Current).to(context);
 }
コード例 #10
0
 public override void Context()
 {
     base.Context();
     _proxy           = new object();
     _constructorArgs = new[] { new object() };
     _callRouter      = mock <ICallRouter>();
     _callRouterFactory.stub(x => x.Create(_context, SubstituteConfig.OverrideAllCalls)).Return(_callRouter);
 }
コード例 #11
0
            public override void Context()
            {
                _substitute          = new object();
                _routerForSubstitute = mock <ICallRouter>();
                var context = mock <ISubstitutionContext>();

                context.stub(x => x.GetCallRouterFor(_substitute)).Return(_routerForSubstitute);
                temporarilyChange(() => SubstitutionContext.Current).to(context);
            }
コード例 #12
0
 void RaiseEventIfSet(ICallRouter callRouter)
 {
     if (_getArgumentsForRaisingEvent.Value != null)
     {
         var routes = new RouteFactory();
         callRouter.SetRoute(x => routes.RaiseEvent(x, _getArgumentsForRaisingEvent.Value));
         _getArgumentsForRaisingEvent.Value = null;
     }
 }
コード例 #13
0
        private object DelegateProxy(Type delegateType, ICallRouter callRouter)
        {
            var delegateContainer = _delegateContainerCache.GetOrAdd(delegateType, GenerateDelegateContainerInterface);
            var invokeMethod      = delegateContainer.GetMethod(MethodNameInsideProxyContainer);

            var proxy = _objectProxyFactory.GenerateProxy(callRouter, delegateContainer, Type.EmptyTypes, null);

            return(invokeMethod.CreateDelegate(delegateType, proxy));
        }
コード例 #14
0
 void RaiseEventIfSet(ICallRouter callRouter)
 {
     if (_getArgumentsForRaisingEvent.Value != null)
     {
         var routes = new RouteFactory();
         callRouter.SetRoute(x => routes.RaiseEvent(x, _getArgumentsForRaisingEvent.Value));
         _getArgumentsForRaisingEvent.Value = null;
     }
 }
コード例 #15
0
        public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, object[] constructorArguments)
        {
            VerifyClassHasNotBeenPassedAsAnAdditionalInterface(additionalInterfaces);

            var interceptor = new CastleForwardingInterceptor(new CastleInvocationMapper(), callRouter);
            var proxyGenerationOptions = GetOptionsToMixinCallRouter(callRouter);
            var proxy = CreateProxyUsingCastleProxyGenerator(typeToProxy, additionalInterfaces, constructorArguments, interceptor, proxyGenerationOptions);
            interceptor.StartIntercepting();
            return proxy;
        }
        public static string DiagName(this ICallRouter callRouter, DiagContextInternal ctx)
        {
            var name = $"<{callRouter.GetObjectId(ctx)}";

            if (ctx.TryGetSubstituteForRouter(callRouter, out object substitute))
            {
                name += $"#{substitute.SubstituteId(ctx)}";
            }

            return($"{name}>");
        }
コード例 #17
0
        public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, object[] constructorArguments, ProxyBuilder builder)
        {
            VerifyClassHasNotBeenPassedAsAnAdditionalInterface(additionalInterfaces);

            var interceptor            = new CastleForwardingInterceptor(new CastleInvocationMapper(), callRouter);
            var proxyGenerationOptions = GetOptionsToMixinCallRouter(callRouter);
            var proxy = CreateProxyUsingCastleProxyGenerator(typeToProxy, additionalInterfaces, constructorArguments, interceptor, proxyGenerationOptions, builder);

            interceptor.StartIntercepting();
            return(proxy);
        }
コード例 #18
0
ファイル: WhenCalledSpecs.cs プロジェクト: phiree/NSubstitute
            public override void Context()
            {
                _call = mock <Action <IFoo> >();
                _callbackWithArguments = args => { };
                _matchArgs             = MatchArgs.AsSpecifiedInCall;

                _context    = mock <ISubstitutionContext>();
                _substitute = mock <IFoo>();
                _callRouter = mock <ICallRouter>();

                _context.stub(x => x.GetCallRouterFor(_substitute)).Return(_callRouter);
            }
コード例 #19
0
        public Func <ISubstituteState, IRoute>?UseNextRoute(ICallRouter callRouter)
        {
            var value = _nextRouteFactory.Value;

            if (value != null && ReferenceEquals(callRouter, value.Item1))
            {
                _nextRouteFactory.Value = null;
                return(value.Item2);
            }

            return(null);
        }
コード例 #20
0
        private ProxyGenerationOptions GetOptionsToMixinCallRouterProvider(ICallRouter callRouter)
        {
            var options = new ProxyGenerationOptions(_allMethodsExceptCallRouterCallsHook);

            // Previously we mixed in the callRouter instance directly, and now we create a wrapper around it.
            // The reason is that we want SubstitutionContext.GetCallRouterFor(substitute) to return us the
            // original callRouter object, rather than the substitute object (as it implemented the ICallRouter interface directly).
            // That need appeared due to the ThreadLocalContext.SetNextRoute() API, which compares the passed callRouter instance by reference.
            options.AddMixinInstance(new StaticCallRouterProvider(callRouter));

            return(options);
        }
コード例 #21
0
        public void SetNextRoute(ICallRouter callRouter, Func <ISubstituteState, IRoute> nextRouteFactory)
        {
            if (callRouter == null)
            {
                throw new ArgumentNullException(nameof(callRouter));
            }
            if (nextRouteFactory == null)
            {
                throw new ArgumentNullException(nameof(nextRouteFactory));
            }

            _nextRouteFactory.Value = Tuple.Create(callRouter, nextRouteFactory);
        }
コード例 #22
0
        public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, object[] constructorArguments)
        {
            VerifyClassHasNotBeenPassedAsAnAdditionalInterface(additionalInterfaces);

            var interceptor = _interceptorFactory.CreateForwardingInterceptor(callRouter);
            var proxyGenerationOptions = GetOptionsToMixinCallRouter(callRouter);
            if (typeToProxy.IsInterface)
            {
                VerifyNoConstructorArgumentsGivenForInterface(constructorArguments);
                return _proxyGenerator.CreateInterfaceProxyWithoutTarget(typeToProxy, additionalInterfaces, proxyGenerationOptions, interceptor);
            }
            return _proxyGenerator.CreateClassProxy(typeToProxy, additionalInterfaces, proxyGenerationOptions, constructorArguments, interceptor);
        }
コード例 #23
0
 public override void Context()
 {
     _sub = mock<IFoo>();
     _substitutionContext = mock<ISubstitutionContext>();
     _callRouter = mock<ICallRouter>();
     _substitutionContext.stub(x => x.GetCallRouterFor(_sub))
                         .IgnoreArguments()
                         .Return(_callRouter);
     _callRouter.stub(x => x.SetReturnForType(It.IsAny<Type>(), It.IsAny<IReturn>()))
                .IgnoreArguments()
                .WhenCalled(x => _returnValueSet = (IReturn)x.Arguments[1]);
     temporarilyChange(() => SubstitutionContext.Current).to(_substitutionContext);
 }
コード例 #24
0
 public override void Context()
 {
     _sub = mock <IFoo>();
     _substitutionContext = mock <ISubstitutionContext>();
     _callRouter          = mock <ICallRouter>();
     _substitutionContext.stub(x => x.GetCallRouterFor(_sub))
     .IgnoreArguments()
     .Return(_callRouter);
     _callRouter.stub(x => x.SetReturnForType(It.IsAny <Type>(), It.IsAny <IReturn>()))
     .IgnoreArguments()
     .WhenCalled(x => _returnValueSet = (IReturn)x.Arguments[1]);
     temporarilyChange(() => SubstitutionContext.Current).to(_substitutionContext);
 }
コード例 #25
0
        public void Register(object proxy, ICallRouter callRouter)
        {
            if (proxy is ICallRouter)
            {
                return;
            }
            if (proxy is ICallRouterProvider)
            {
                return;
            }

            _callRouterMappings.AddOrUpdate(proxy, callRouter, (o, c) => callRouter);
        }
コード例 #26
0
        public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, object[] constructorArguments)
        {
            if (HasItems(additionalInterfaces))
            {
                throw new SubstituteException(
                          "Can not specify additional interfaces when substituting for a delegate. You must specify only a single delegate type if you need to substitute for a delegate.");
            }
            if (HasItems(constructorArguments))
            {
                throw new SubstituteException("Can not provide constructor arguments when substituting for a delegate.");
            }

            return(DelegateProxy(typeToProxy, callRouter));
        }
コード例 #27
0
ファイル: DelegateCall.cs プロジェクト: rkanagy/NSubstitute
 public DelegateCall(ICallRouter callRouter,
                     Type delegateType,
                     Type returnType,
                     IParameterInfo[] parameterInfos,
                     ICallFactory callFactory,
                     IArgumentSpecificationDequeue argSpecificationDequeue)
 {
     CallRouter               = callRouter;
     _delegateType            = delegateType;
     _returnType              = returnType;
     _parameterInfos          = parameterInfos;
     _callFactory             = callFactory;
     _argSpecificationDequeue = argSpecificationDequeue;
     MethodToInvoke           = GetMethodToInvoke();
 }
コード例 #28
0
        public Func <ISubstituteState, IRoute> UseNextRoute(ICallRouter callRouter)
        {
            if (callRouter == null)
            {
                throw new ArgumentNullException(nameof(callRouter));
            }

            var value = _nextRouteFactory.Value;

            if (value != null && ReferenceEquals(callRouter, value.Item1))
            {
                _nextRouteFactory.Value = null;
                return(value.Item2);
            }

            return(null);
        }
コード例 #29
0
        private object DelegateProxy(Type delegateType, ICallRouter callRouter)
        {
            var delegateMethodToProxy = delegateType.GetMethod("Invoke");

            var proxyParameterTypes  = delegateMethodToProxy.GetParameters().Select(x => new ParameterInfoWrapper(x)).ToArray();
            var delegateCall         = new DelegateCall(callRouter, delegateType, delegateMethodToProxy.ReturnType, proxyParameterTypes);
            var invokeOnDelegateCall = delegateCall.MethodToInvoke;

            ParameterExpression[] proxyParameters          = delegateMethodToProxy.GetParameters().Select(x => Expression.Parameter(x.ParameterType, x.Name)).ToArray();
            Expression[]          proxyParametersAsObjects = proxyParameters.Select(x => (Expression)Expression.Convert(x, typeof(object))).ToArray();
            var  bodyExpressions = new List <Expression>();
            bool isVoid          = delegateMethodToProxy.ReturnType == typeof(void);
            var  arguments       = Expression.Variable(typeof(object[]), "arguments");
            var  result          = isVoid ? null : Expression.Variable(delegateMethodToProxy.ReturnType, "result");

            bodyExpressions.Add(Expression.Assign(arguments, Expression.NewArrayInit(typeof(object), proxyParametersAsObjects)));

            Expression callInvokeOnDelegateCallInstance = Expression.Call(Expression.Constant(delegateCall), invokeOnDelegateCall, arguments);

            if (!isVoid)
            {
                callInvokeOnDelegateCallInstance = Expression.Assign(result, Expression.Convert(callInvokeOnDelegateCallInstance, delegateMethodToProxy.ReturnType));
            }

            bodyExpressions.Add(callInvokeOnDelegateCallInstance);

            for (var index = 0; index < proxyParameters.Length; index++)
            {
                var parameter = proxyParameters[index];
                if (parameter.IsByRef)
                {
                    var assignment = Expression.Assign(parameter, Expression.Convert(Expression.ArrayAccess(arguments, Expression.Constant(index)), parameter.Type));
                    bodyExpressions.Add(assignment);
                }
            }

            if (!isVoid)
            {
                bodyExpressions.Add(result);
            }

            var variables       = isVoid ? new[] { arguments } : new[] { arguments, result };
            var proxyExpression = Expression.Lambda(delegateType, Expression.Block(variables, bodyExpressions), proxyParameters);

            return(proxyExpression.Compile());
        }
コード例 #30
0
        public object GenerateComponentProxy(ICallRouter callRouter, Type type, GameObject gameObject)
        {
            var interceptor            = new CastleForwardingInterceptor(new CastleInvocationMapper(), callRouter);
            var proxyGenerationOptions = GetOptionsToMixinCallRouter(callRouter);

            // We can't instantiate the proxy using _proxyGenerator.CreateClassProxy
            // because components cannot be created using the 'new' operator. They must be added to a GameObject instead.
            // So instead, we use reflection to generate the proxy type from the ProxyGenerator
            // and then add it to the GameObect ourselves.
            MethodInfo method = _proxyGenerator.GetType().GetMethod("CreateClassProxyType",
                                                                    BindingFlags.Instance |
                                                                    BindingFlags.NonPublic);

            object[] args      = new object[] { type, null, proxyGenerationOptions };
            Type     proxyType = (Type)method.Invoke(_proxyGenerator, args);

            // Add the proxy component type fo the GameObject.
            var proxy = gameObject.AddComponent(proxyType);

            // We still need to call the constructor generated for the proxy type so that the proxy has access
            // to the interceptors and other proxy options.
            // Use reflection to generate the argument list for the proxy class.
            MethodInfo argsMethod = _proxyGenerator.GetType().GetMethod("BuildArgumentListForClassProxy",
                                                                        BindingFlags.Instance |
                                                                        BindingFlags.NonPublic);

            // Get the constructor arguments for the proxy type.
            args = new object[] { proxyGenerationOptions, new IInterceptor[] { interceptor } };
            List <object> arguments = (List <object>)argsMethod.Invoke(_proxyGenerator, args);

            // Now, we need to use reflection to manually find the correct constructor
            // to call for the proxy type and call it.
            ConstructorInfo[] constructors = proxyType.GetConstructors();
            foreach (ConstructorInfo constructor in constructors)
            {
                if (constructor.GetParameters().Length == arguments.Count)
                {
                    constructor.Invoke(proxy, arguments.ToArray());
                }
            }

            interceptor.StartIntercepting();

            return(proxy);
        }
コード例 #31
0
        private object GenerateTypeProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, object[] constructorArguments)
        {
            VerifyClassHasNotBeenPassedAsAnAdditionalInterface(additionalInterfaces);

            var proxyIdInterceptor    = new ProxyIdInterceptor(typeToProxy);
            var forwardingInterceptor = CreateForwardingInterceptor(callRouter);

            var proxyGenerationOptions = GetOptionsToMixinCallRouterProvider(callRouter);

            var proxy = CreateProxyUsingCastleProxyGenerator(
                typeToProxy,
                additionalInterfaces,
                constructorArguments,
                new IInterceptor[] { proxyIdInterceptor, forwardingInterceptor },
                proxyGenerationOptions);

            forwardingInterceptor.SwitchToFullDispatchMode();
            return(proxy);
        }
コード例 #32
0
        public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces,
                                    object[] constructorArguments)
        {
            var diagCallRouter = new DiagnosticsCallRouter(callRouter, _ctx);
            var result         = _impl.GenerateProxy(diagCallRouter, typeToProxy, additionalInterfaces, constructorArguments);

            _ctx.RegisterPrimaryProxyType(result, typeToProxy);

            LogAndTrace(
                $"GenerateProxy(callRouter: {callRouter.DiagName(_ctx)}, " +
                $"typeToProxy: {typeToProxy.FullName}, " +
                $"additionalInterfaces: {additionalInterfaces.Print(x => x.FullName)}, " +
                $"constructorArguments: {constructorArguments.Print(a => a.GetObjectId(_ctx))}) " +
                $"=> {result.SubstituteId(_ctx)}");

            _ctx.MapRouterToSubstitute(callRouter, result);
            _ctx.MapRouterToSubstitute(diagCallRouter, result);
            _ctx.MapRouterToDiagRouter(callRouter, diagCallRouter);

            return(result);
        }
コード例 #33
0
        object CreateStaticProxy(Type typeToProxy, ICallRouter callRouter)
        {
            if (!m_Routers.TryAdd(typeToProxy, callRouter))
            {
                throw new SubstituteException("Cannot substitute the same type twice (did you forget to Dispose() your previous substitute?)");
            }

            return(new SubstituteStatic.Proxy(new DelegateDisposable(() =>
            {
                if (!m_Routers.TryGetValue(typeToProxy, out var found))
                {
                    throw new SubstituteException("Unexpected static unmock of an already-unmocked type");
                }

                if (found != callRouter)
                {
                    throw new SubstituteException("Discovered unexpected call router attached in static mock context");
                }

                m_Routers.Remove(typeToProxy);
            })));
        }
コード例 #34
0
        public object GenerateProxy(ICallRouter callRouter, Type typeToProxy, Type[] additionalInterfaces, object[] constructorArguments)
        {
            VerifyClassHasNotBeenPassedAsAnAdditionalInterface(additionalInterfaces);

            var proxyIdInterceptor    = new ProxyIdInterceptor(typeToProxy);
            var forwardingInterceptor = new CastleForwardingInterceptor(
                new CastleInvocationMapper(
                    new CallFactory(),
                    _argSpecificationDequeue),
                callRouter);

            var proxyGenerationOptions = GetOptionsToMixinCallRouter(callRouter);
            var proxy = CreateProxyUsingCastleProxyGenerator(
                typeToProxy,
                additionalInterfaces,
                constructorArguments,
                new IInterceptor[] { proxyIdInterceptor, forwardingInterceptor },
                proxyGenerationOptions);

            forwardingInterceptor.SwitchToFullDispatchMode();
            return(proxy);
        }
コード例 #35
0
 public void LastCallRouter(ICallRouter callRouter)
 {
     _lastCallRouter.Value = callRouter;
     RaiseEventIfSet(callRouter);
 }
 public void SetLastCallRouter(ICallRouter callRouter)
 {
     Trace($"SetLastCallRouter(callRouter: {callRouter.DiagName(_ctx)})");
     _impl.SetLastCallRouter(_ctx.MapToDiagRouter(callRouter));
 }
コード例 #37
0
 public void LastCallShouldReturn(IReturn value, MatchArgs matchArgs)
 {
     if (_lastCallRouter == null) throw new CouldNotSetReturnException();
     _lastCallRouter.LastCallShouldReturn(value, matchArgs);
     _lastCallRouter = null;
 }
コード例 #38
0
 public void LastCallRouter(ICallRouter callRouter)
 {
     innerContext.LastCallRouter(callRouter);
 }
コード例 #39
0
 public virtual IInterceptor CreateForwardingInterceptor(ICallRouter forwardToCallRouter)
 {
     return new CastleForwardingInterceptor(new CastleInvocationMapper(), forwardToCallRouter);
 }
コード例 #40
0
 public void LastCallRouter(ICallRouter callRouter)
 {
     _lastCallRouter.Value = callRouter;
     RaiseEventIfSet(callRouter);
 }
 public void SetNextRoute(ICallRouter callRouter, Func <ISubstituteState, IRoute> nextRouteFactory)
 {
     Trace(
         $"SetNextRoute(callRouter: {callRouter.DiagName(_ctx)}, nextRouteFactory: {nextRouteFactory.DiagName()})");
     _impl.SetNextRoute(_ctx.MapToDiagRouter(callRouter), nextRouteFactory);
 }
コード例 #42
0
 private ProxyGenerationOptions GetOptionsToMixinCallRouter(ICallRouter callRouter)
 {
     var options = new ProxyGenerationOptions(_ignoreCallRouterCallsHook);
     options.AddMixinInstance(callRouter);
     return options;
 }
コード例 #43
0
 public DelegateCall(ICallRouter callRouter, Type[] parameterTypes)
 {
     _callRouter = callRouter;
     _parameterTypes = parameterTypes;
 }
コード例 #44
0
 public void Register(object proxy, ICallRouter callRouter)
 {
     if (proxy is ICallRouter) return;
     _callRouterMappings.Add(proxy, callRouter);
 }
コード例 #45
0
 void RaiseEventIfSet(ICallRouter callRouter)
 {
     if (_getArgumentsForRaisingEvent.Value != null)
     {
         callRouter.SetRoute<RaiseEventRoute>(_getArgumentsForRaisingEvent.Value);
         _getArgumentsForRaisingEvent.Value = null;
     }
 }
コード例 #46
0
 public CastleForwardingInterceptor(CastleInvocationMapper invocationMapper, ICallRouter callRouter)
 {
     _invocationMapper = invocationMapper;
     _callRouter = callRouter;
 }
コード例 #47
0
ファイル: DelegateCall.cs プロジェクト: trumpi/NSubstitute
 public DelegateCall(ICallRouter callRouter, IParameterInfo[] parameterInfos)
 {
     _callRouter = callRouter;
     _parameterInfos = parameterInfos;
 }