public IHttpActionResult Delete(string label)
        {
            try
            {
                ICallContext callContext = GetCallContext();

                var itemToDelete = ItemsRepository.GetByLabel(label);
                if (itemToDelete == null)
                {
                    return(NotFound());
                }

                itemToDelete = ItemsRepository.Delete(callContext, itemToDelete);
                if (itemToDelete == null)
                {
                    return(BadRequest());
                }

                return(Ok(ModelFactory.Create(itemToDelete)));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
        {
            var method = invocation.Method;

            // Only if there is no corresponding setup for `ToString()`
            if (IsObjectMethod(method, "ToString") && !ctx.OrderedCalls.Any(c => IsObjectMethod(c.Method, "ToString")))
            {
                invocation.ReturnValue = ctx.Mock.ToString() + ".Object";
                return(InterceptionAction.Stop);
            }

            // Only if there is no corresponding setup for `GetHashCode()`
            if (IsObjectMethod(method, "GetHashCode") && !ctx.OrderedCalls.Any(c => IsObjectMethod(c.Method, "GetHashCode")))
            {
                invocation.ReturnValue = ctx.Mock.GetHashCode();
                return(InterceptionAction.Stop);
            }

            // Only if there is no corresponding setup for `Equals()`
            if (IsObjectMethod(method, "Equals") && !ctx.OrderedCalls.Any(c => IsObjectMethod(c.Method, "Equals")))
            {
                invocation.ReturnValue = ReferenceEquals(invocation.Arguments.First(), ctx.Mock.Object);
                return(InterceptionAction.Stop);
            }

            return(InterceptionAction.Continue);
        }
		public override void AfterCall(ICallContext callContext)
		{
			Console.WriteLine("> Leaving {0}", callContext.Method.Name);
			if (callContext.CallFailed) {
				Console.WriteLine("  Exception: {0}", callContext.Exception);
			}
		}
Exemple #4
0
 public override void BeforeCall(ICallContext callContext)
 {
     callContext.SetProperty("transactionScope", new TransactionScope(this.Option, new TransactionOptions()
     {
         IsolationLevel = this.IsolationLevel, Timeout = TimeSpan.FromMilliseconds(this.TimeoutMs)
     }));
 }
 public TelemetryClient(ILogger <object> logger, ICallContext callContext, AppConfig appConfig, IAuthProvider authProvider)
     : base(logger)
 {
     this.AppConfig    = appConfig ?? throw new ArgumentNullException(nameof(appConfig));
     this.AuthProvider = authProvider;
     this.CallContext  = callContext;
 }
Exemple #6
0
 public CallContext(CallContext parent)
 {
     m_parentContext = parent;
     m_entryLogger   = parent.Logger;
     m_callEntry     = parent.CurrentCallEntry;
     m_break         = false;
 }
 internal void AddInvocation(ICallContext invocation)
 {
     lock (actualInvocations)
     {
         actualInvocations.Add(invocation);
     }
 }
        public void EndSession(bool succesfully)
        {
            ICallContext currentContext = this.callContextFactory.RetrieveCallContext();

            IDocumentSession session = currentContext[SessionStateKey] as IDocumentSession;

            if (session == null)
            {
                logger.Debug("There is no session into the current context.");
                return;
            }

            try
            {
                if (succesfully)
                {
                    logger.Debug("Saving changes");
                    session.SaveChanges();
                }
                else
                {
                    logger.Debug("An error occured, so I'm not flushing the changes");
                }
            }
            finally
            {
                session.Dispose();
                currentContext[SessionStateKey] = null;
                logger.Debug("Session Removed");
            }
        }
 public DataProviderBase(
     ICallContext callContext,
     AppDbContext appDbContext
     )
 {
     this.AppDbContext = appDbContext;
 }
Exemple #10
0
        public bool Open([Implicit] ICallContext context)
        {
            if (!m_open)
            {
                TPCANStatus result = PCANBasic.Initialize(m_handle, ToPCANBaudrate(m_baudrate), TPCANType.PCAN_TYPE_ISA, 0, 0);
                if (this.UpdateStatusFromOperation(result) == TPCANStatus.PCAN_ERROR_OK)
                {
                    if (context != null && context.LoggingEnabled)
                    {
                        context.Logger.Log("Open", "Opened successfully");
                    }
                    m_open = true;

                    if (m_receiverThread == null)
                    {
                        m_receiverThread = new Thread(new ThreadStart(this.ReceiveThreadHandler));
                        m_receiverThread.Start();
                        //Core.Main.ServiceManager.Get<>
                    }

                    return(true);
                }
                else
                {
                    if (context != null)
                    {
                        context.Logger.LogError("PCAN", "Open failed");
                    }
                }
            }
            return(false);
        }
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
        {
            if (FluentMockContext.IsActive)
            {
                localctx.Call = null;
            }
            else
            {
                IProxyCall lastMatchingSetup = null;
                IProxyCall lastMatchingSetupForSameMethod = null;
                foreach (var setup in ctx.OrderedCalls)
                {
                    if (setup.Matches(invocation))
                    {
                        lastMatchingSetup = setup;
                        if (setup.Method == invocation.Method)
                        {
                            lastMatchingSetupForSameMethod = setup;
                        }
                    }
                }
                localctx.Call = lastMatchingSetupForSameMethod ?? lastMatchingSetup;
            }

            if (localctx.Call != null)
            {
                localctx.Call.EvaluatedSuccessfully();
            }
            else if (!FluentMockContext.IsActive && ctx.Behavior == MockBehavior.Strict)
            {
                throw new MockException(MockException.ExceptionReason.NoSetup, ctx.Behavior, invocation);
            }

            return(InterceptionAction.Continue);
        }
        public long Fcn([Implicit] ICallContext context, long i)    // i = 4
        {
            context.Logger.Log("HighLayerCodeModule.Fcn", $"i: {i}");
            var mid = this.MidLayer.Fcn(context, 8L);

            return(mid + this.IntProp * 3L + i * 11L);    // mid(8) + 41 * 3 + 4 * 11
        }
Exemple #13
0
 public CallContext(ScriptCallContext parent, CallEntry callEntry, bool breakSet)
 {
     m_parentContext = parent;
     m_entryLogger   = parent.Logger;
     m_callEntry     = callEntry;
     m_break         = breakSet;
 }
        public long Fcn([Implicit] ICallContext context, long i)    // i = 8
        {
            context.Logger.Log("MidLayerCodeModule.Fcn", $"i: {i}");
            var low = this.LowLayer.Fcn(context, 19L);

            return(low + this.IntProp * 100 + i * 9L);   // low(19) + 2 * 100 + 8 * 9 = 1481
        }
        public DatabaseInitializer(
            ICallContext callContext,
            AppDbContext appDbContext,
            AppConfig appConfig,
            IAuthProvider authProvider,
            ColorDataProvider colorDataProvider,
            BikeModelDataProvider bikeModelDataProvider,
            UserDataProvider userDataProvider,
            BikeDataProvider bikeDataProvider
            )
            : base(callContext, appDbContext, appConfig)
        {
            AppDbContext.OnModelCreatingCallback = this.OnModelCreating;

            ObjectInitializers = new IDatabaseInitializer[] {
                // Schema
                // Tables
                // Views
                new Schema.Views.V_User(callContext, appDbContext, appConfig),
                // Functions
                new Schema.Functions.ufn_GeoDistanceMiles(callContext, appDbContext, appConfig),
                // Data
                new InitialData.AspNetRoles(callContext, appDbContext, appConfig, authProvider),
                new InitialData.AspNetUsers(callContext, appDbContext, appConfig, authProvider),
                new InitialData.Colors(callContext, appDbContext, appConfig, colorDataProvider),
                new InitialData.BikeModels(callContext, appDbContext, appConfig, bikeModelDataProvider),
                new InitialData.Bikes(callContext, appDbContext, appConfig, colorDataProvider, bikeModelDataProvider, userDataProvider, bikeDataProvider)
            };
        }
Exemple #16
0
 public UserDataProvider(
     ICallContext callContext,
     AppDbContext appDbContext
     )
     : base(callContext, appDbContext)
 {
 }
Exemple #17
0
 public void DumpToLog([Implicit] ICallContext context)
 {
     if (context.LoggingEnabled)
     {
         var logger = context.Logger;
         logger.Log("ReportData.DumpToLog", "<some data to go>");
     }
 }
Exemple #18
0
 public ItemExpired CheckExpiration(DateTime date, ICallContext callContext)
 {
     if (this.Expiration < date)
     {
         return(new ItemExpired(callContext, Label, Expiration));
     }
     return(null);
 }
Exemple #19
0
 public override void AfterCall(ICallContext callContext)
 {
     Console.WriteLine("> Leaving {0}", callContext.Method.Name);
     if (callContext.CallFailed)
     {
         Console.WriteLine("  Exception: {0}", callContext.Exception);
     }
 }
		public void TestCleanup()
		{
			ICallContext context = CallContextManagerInstance.CallContextOverride;

			ICallContext existingContext = context.ExistingCallContext();
			Correlation.CorrelationEnd();
			context.EndCallContext();
		}
Exemple #21
0
 public IMessage GetNext([Implicit] ICallContext context, TimeSpan timeout)
 {
     if (m_queue.TryTake(out IMessage message, timeout))
     {
         return(message);
     }
     return(null);
 }
Exemple #22
0
 internal DatabaseInitializerBase(
     ICallContext callContext,
     AppDbContext appDbContext,
     AppConfig appConfig)
     : base(callContext, appDbContext)
 {
     this.AppConfig = appConfig;
 }
Exemple #23
0
 internal V_User(
     ICallContext callContext,
     AppDbContext appDbContext,
     AppConfig appConfig
     )
     : base(callContext, appDbContext, appConfig)
 {
 }
 internal ufn_GeoDistanceMiles(
     ICallContext callContext,
     AppDbContext appDbContext,
     AppConfig appConfig
     )
     : base(callContext, appDbContext, appConfig)
 {
 }
Exemple #25
0
        public Auditor(ICallContext callContext, IBusEndpointFactory busFactory)
        {
            Guard.Against.Null(callContext, nameof(callContext));
            Guard.Against.Null(busFactory, nameof(busFactory));

            this.callContext = callContext;
            this.bus         = busFactory.Create <AuditMessage>();
        }
Exemple #26
0
 public void SendDirect([Implicit] ICallContext context, string text)
 {
     if (context != null && context.LoggingEnabled)
     {
         context.Logger.Log("SerialTestConnection", "SendDirect: \"" + text + "\"");
     }
     DoSendDirect(text);
 }
Exemple #27
0
 public UserManager(
     ICallContext callContext,
     UserDataProvider userDataProvider
     )
     : base(callContext)
 {
     this.UserDataProvider = userDataProvider;
 }
Exemple #28
0
 public AuditFunctions(IMediator mediator,
                       ICallContext callContext,
                       IMapper mapper)
     : base(mediator,
            callContext)
 {
     this.mapper = mapper;
 }
        /// <summary>
        /// End a request
        /// </summary>
        private void EndRequest()
        {
            ICallContext context = CallContextManagerInstance.CallContextOverride;

            ICallContext existingContext = context.ExistingCallContext();

            Correlation.CorrelationEnd();
            context.EndCallContext();
        }
Exemple #30
0
 internal AspNetUsers(
     ICallContext callContext,
     AppDbContext appDbContext,
     AppConfig appConfig,
     IAuthProvider authProvider
     ) : base(callContext, appDbContext, appConfig)
 {
     this.AuthProvider = authProvider;
 }
Exemple #31
0
 /// <summary>
 /// Initializes a new instance of <see cref="TenantManager"/>
 /// </summary>
 /// <param name="callContext"><see cref="ICallContext"/> for holding current <see cref="ITenant"/></param>
 /// <param name="tenantPopulator"><see cref="ITenantPopulator"/> for populating new tenants</param>
 /// <param name="tenantIdResolver"><see cref="ICanResolveTenantId">Tenant Id resolver</see></param>
 public TenantManager(
     ICallContext callContext,
     ITenantPopulator tenantPopulator,
     ICanResolveTenantId tenantIdResolver)
 {
     _callContext      = callContext;
     _tenantPopulator  = tenantPopulator;
     _tenantIdResolver = tenantIdResolver;
 }
        /// <summary>
        /// Method called after a call is issued.
        /// </summary>
        public override void AfterCall(ICallContext callContext)
        {
            // Should happen only on constructor methods which are not supported:
            if (callContext.Instance == null)
                return;

            // Call IInterceptible.AfterCall method, or throw exception:
            var instance = callContext.Instance as IInterceptible;
            if (instance != null)
                instance.AfterCall(callContext);
            else
                throw new InvalidOperationException(String.Format("{0} should implement IInterceptible.", callContext.Instance.GetType()));
        }
Exemple #33
0
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
        {
            this.ctx = ctx;
            if (!FluentMockContext.IsActive)
            {
                //Special case for events
                if (invocation.Method.IsEventAttach())
                {
                    var delegateInstance = (Delegate)invocation.Arguments[0];
                    // TODO: validate we can get the event?
                    var eventInfo = this.GetEventFromName(invocation.Method.Name.Substring(4));

                    if (ctx.Mock.CallBase && !eventInfo.DeclaringType.IsInterface)
                    {
                        invocation.InvokeBase();
                    }
                    else if (delegateInstance != null)
                    {
                        ctx.AddEventHandler(eventInfo, (Delegate)invocation.Arguments[0]);
                    }

                    return InterceptionAction.Stop;
                }
                else if (invocation.Method.IsEventDetach())
                {
                    var delegateInstance = (Delegate)invocation.Arguments[0];
                    // TODO: validate we can get the event?
                    var eventInfo = this.GetEventFromName(invocation.Method.Name.Substring(7));

                    if (ctx.Mock.CallBase && !eventInfo.DeclaringType.IsInterface)
                    {
                        invocation.InvokeBase();
                    }
                    else if (delegateInstance != null)
                    {
                        ctx.RemoveEventHandler(eventInfo, (Delegate)invocation.Arguments[0]);
                    }

                    return InterceptionAction.Stop;
                }

                // Save to support Verify[expression] pattern.
                // In a fluent invocation context, which is a recorder-like
                // mode we use to evaluate delegates by actually running them,
                // we don't want to count the invocation, or actually run
                // previous setups.
                ctx.AddInvocation(invocation);
            }
            return InterceptionAction.Continue;
        }
		/// <summary>
		/// Will search the index using the specified query.
		/// </summary>
		/// <param name="callContext"></param>
		/// <param name="query"></param>
        public IndexResponse Search( ICallContext callContext, IQuery query, UUID accessPointGUID )
        {
			if( accessPointGUID != null )
                query.Query = string.Format("({0})+AND+(ap{1}_PubStart:[*+TO+NOW]+AND+ap{1}_PubEnd:[NOW+TO+*])", query.Query, accessPointGUID);
            else
            {
				var folders = callContext.PortalApplication.GetModule<MCM.Module.FolderModule>().Get( callContext, null, null, null, (uint) FolderPermission.Read );

                query.Query = string.Format( "({0})+AND+({1})", query.Query, string.Join( "+OR+", folders.Select( folder => string.Format( "FolderTree:{0}", folder.ID ) ) ) );
            }

            var response = callContext.IndexManager.GetIndex( "CHAOS.MCM.Module.AMCMModule" ).Get<UUIDResult>( query );

            return new IndexResponse( response );
        }
 private void ThrowIfReturnValueRequired(IProxyCall call, ICallContext invocation)
 {
     if (ctx.Behavior != MockBehavior.Loose &&
         invocation.Method != null &&
         invocation.Method.ReturnType != null &&
         invocation.Method.ReturnType != typeof(void))
     {
         var methodCall = call as MethodCallReturn;
         if (methodCall == null || !methodCall.HasReturnValue)
         {
             throw new MockException(
                 MockException.ExceptionReason.ReturnValueRequired,
                 ctx.Behavior,
                 invocation);
         }
     }
 }
		public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
        {
			if (invocation.Method != null && invocation.Method.ReturnType != null &&
                    invocation.Method.ReturnType != typeof(void))
            {
                Mock recursiveMock;
                if (ctx.Mock.InnerMocks.TryGetValue(invocation.Method, out recursiveMock))
                {
                    invocation.ReturnValue = recursiveMock.Object;
                }
                else
                {
                    invocation.ReturnValue = ctx.Mock.DefaultValueProvider.ProvideDefault(invocation.Method);
                }
                return InterceptionAction.Stop;
            }
            return InterceptionAction.Continue;
        }
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptStrategyContext ctx)
        {
            this.ctx = ctx;
            if (ctx.CurrentCall != null)
            {
                ctx.CurrentCall.SetOutParameters(invocation);

                // We first execute, as there may be a Throws 
                // and therefore we might never get to the 
                // next line.
                ctx.CurrentCall.Execute(invocation);
                ThrowIfReturnValueRequired(ctx.CurrentCall, invocation);
                return InterceptionAction.Stop;
            }
            else
            {
                return InterceptionAction.Continue;
            }
        }
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptStrategyContext ctx)
        {
            if (invocation.Method.DeclaringType == typeof(object) ||
                invocation.Method.DeclaringType.IsClass && !invocation.Method.IsAbstract && ctx.Mock.CallBase
                )
            {
                // Invoke underlying implementation.

                // For mocked classes, if the target method was not abstract, 
                // invoke directly.
                // Will only get here for Loose behavior.
                // TODO: we may want to provide a way to skip this by the user.
                invocation.InvokeBase();
                return InterceptionAction.Stop;
            }
            else
            {
                return InterceptionAction.Continue;
            }
        }
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
        {
            if (invocation.Method.DeclaringType == typeof(object) || // interface proxy
                ctx.Mock.ImplementedInterfaces.Contains(invocation.Method.DeclaringType) && !invocation.Method.IsEventAttach() && !invocation.Method.IsEventDetach() && ctx.Mock.CallBase || // class proxy with explicitly implemented interfaces. The method's declaring type is the interface and the method couldn't be abstract
                invocation.Method.DeclaringType.IsClass && !invocation.Method.IsAbstract && ctx.Mock.CallBase // class proxy
                )
            {
                // Invoke underlying implementation.

                // For mocked classes, if the target method was not abstract, 
                // invoke directly.
                // Will only get here for Loose behavior.
                // TODO: we may want to provide a way to skip this by the user.
                invocation.InvokeBase();
                return InterceptionAction.Stop;
            }
            else
            {
                return InterceptionAction.Continue;
            }
        }
		internal void AddInvocation(ICallContext invocation)
		{
			lock (actualInvocations)
			{
				actualInvocations.Add(invocation);
			}
		}
		public void Intercept(ICallContext invocation)
		{

            lock (Mock) // this solves issue #249
            {
                var interceptionContext = new InterceptStrategyContext(Mock
                                                                    , targetType
                                                                    , invocationLists
                                                                    , actualInvocations
                                                                    , behavior
                                                                    , orderedCalls
                                                                    );
                foreach (var strategy in InterceptionStrategies())
                {
                    if (InterceptionAction.Stop == strategy.HandleIntercept(invocation, interceptionContext))
                    {
                        break;
                    }
                }
            }
		}
        internal void AddInvocation(ICallContext invocation)
        {
            lock (actualInvocations)
            {
                actualInvocations.Add(invocation);
            }

            lock (Mock.CallSequence)
            {
                Mock.CallSequence.Add(invocation, Mock);
            }
        }
		internal MockException(ExceptionReason reason, MockBehavior behavior,
			ICallContext invocation, string message)
			: base(GetMessage(behavior, invocation, message))
		{
			this.reason = reason;
		}
		internal MockException(ExceptionReason reason, MockBehavior behavior,
			ICallContext invocation)
			: this(reason, behavior, invocation,
				Properties.Resources.ResourceManager.GetString(reason.ToString()))
		{
		}
		private static string GetMessage(
			MockBehavior behavior,
			ICallContext invocation,
			string message)
		{
			return string.Format(
				CultureInfo.CurrentCulture,
				Resources.MockExceptionMessage,
				invocation.Format(),
				behavior,
				message
			);
		}
 public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
 {
     return invocation.Method.IsDestructor() ? InterceptionAction.Stop : InterceptionAction.Continue;
 }
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
        {
            localctx.Call = FluentMockContext.IsActive ? (IProxyCall)null : ctx.OrderedCalls.LastOrDefault(c => c.Matches(invocation));
            if (localctx.Call != null)
            {
                localctx.Call.EvaluatedSuccessfully();
            }
            else if (!FluentMockContext.IsActive && ctx.Behavior == MockBehavior.Strict)
            {
                throw new MockException(MockException.ExceptionReason.NoSetup, ctx.Behavior, invocation);
            }

            return InterceptionAction.Continue;
        }
Exemple #48
0
			public MockInvocation(Mock mock, ICallContext invocation, Match matcher)
			{
				this.Mock = mock;
				this.Invocation = invocation;
				this.Match = matcher;
				defaultValue = mock.DefaultValue;
				// Temporarily set mock default value to Mock so that recursion works.
				mock.DefaultValue = DefaultValue.Mock;
			}
 public void Intercept(ICallContext invocation)
 {
     CurrentInterceptContext localCtx = new CurrentInterceptContext();
     foreach (var strategy in InterceptionStrategies())
     {
         if (InterceptionAction.Stop == strategy.HandleIntercept(invocation, InterceptionContext, localCtx))
         {
             break;
         }
     }
 }
Exemple #50
0
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
        {
            var method = invocation.Method;

            // Only if there is no corresponding setup for `ToString()`
            if (IsObjectMethod(method, "ToString") && !ctx.OrderedCalls.Any(c => IsObjectMethod(c.Method, "ToString")))
            {
                invocation.ReturnValue = ctx.Mock.ToString() + ".Object";
                return InterceptionAction.Stop;
            }

            // Only if there is no corresponding setup for `GetHashCode()`
            if (IsObjectMethod(method, "GetHashCode") && !ctx.OrderedCalls.Any(c => IsObjectMethod(c.Method, "GetHashCode")))
            {
                invocation.ReturnValue = ctx.Mock.GetHashCode();
                return InterceptionAction.Stop;
            }

            // Only if there is no corresponding setup for `Equals()`
            if (IsObjectMethod(method, "Equals") && !ctx.OrderedCalls.Any(c => IsObjectMethod(c.Method, "Equals")))
            {
                invocation.ReturnValue = ReferenceEquals(invocation.Arguments.First(), ctx.Mock.Object);
                return InterceptionAction.Stop;
            }

            return InterceptionAction.Continue;
        }
		public void Intercept(ICallContext invocation)
		{
			if (invocation.Method.IsDestructor())
			{
				return;
			}

			// Track current invocation if we're in "record" mode in a fluent invocation context.
			if (FluentMockContext.IsActive)
			{
				FluentMockContext.Current.Add(this.Mock, invocation);
			}

			// TODO: too many ifs in this method.
			// see how to refactor with strategies.
			if (invocation.Method.DeclaringType.IsGenericType() &&
			  invocation.Method.DeclaringType.GetGenericTypeDefinition() == typeof(IMocked<>))
			{
				// "Mixin" of IMocked<T>.Mock
				invocation.ReturnValue = this.Mock;
				return;
			}
			else if (invocation.Method.DeclaringType == typeof(IMocked))
			{
				// "Mixin" of IMocked.Mock
				invocation.ReturnValue = this.Mock;
				return;
			}

			// Special case for events.
			if (!FluentMockContext.IsActive)
			{
				if (invocation.Method.IsEventAttach())
				{
					var delegateInstance = (Delegate)invocation.Arguments[0];
					// TODO: validate we can get the event?
					var eventInfo = this.GetEventFromName(invocation.Method.Name.Substring(4));

					if (this.Mock.CallBase)
					{
						invocation.InvokeBase();
					}
					else if (delegateInstance != null)
					{
						this.AddEventHandler(eventInfo, (Delegate)invocation.Arguments[0]);
					}

					return;
				}
				else if (invocation.Method.IsEventDetach())
				{
					var delegateInstance = (Delegate)invocation.Arguments[0];
					// TODO: validate we can get the event?
					var eventInfo = this.GetEventFromName(invocation.Method.Name.Substring(7));

					if (this.Mock.CallBase)
					{
						invocation.InvokeBase();
					}
					else if (delegateInstance != null)
					{
						this.RemoveEventHandler(eventInfo, (Delegate)invocation.Arguments[0]);
					}

					return;
				}

				// Save to support Verify[expression] pattern.
				// In a fluent invocation context, which is a recorder-like 
				// mode we use to evaluate delegates by actually running them, 
				// we don't want to count the invocation, or actually run 
				// previous setups.
				actualInvocations.Add(invocation);
			}

			var call = FluentMockContext.IsActive ? (IProxyCall)null : orderedCalls.LastOrDefault(c => c.Matches(invocation));
			if (call == null && !FluentMockContext.IsActive && behavior == MockBehavior.Strict)
			{
				throw new MockException(MockException.ExceptionReason.NoSetup, behavior, invocation);
			}

			if (call != null)
			{
				call.SetOutParameters(invocation);

				// We first execute, as there may be a Throws 
				// and therefore we might never get to the 
				// next line.
				call.Execute(invocation);
				ThrowIfReturnValueRequired(call, invocation);
			}
			else if (invocation.Method.DeclaringType == typeof(object))
			{
				// Invoke underlying implementation.
				invocation.InvokeBase();
			}
			else if (invocation.Method.DeclaringType.IsClass() && !invocation.Method.IsAbstract && this.Mock.CallBase)
			{
				// For mocked classes, if the target method was not abstract, 
				// invoke directly.
				// Will only get here for Loose behavior.
				// TODO: we may want to provide a way to skip this by the user.
				invocation.InvokeBase();
			}
			else if (invocation.Method != null && invocation.Method.ReturnType != null &&
				invocation.Method.ReturnType != typeof(void))
			{
				Mock recursiveMock;
				if (this.Mock.InnerMocks.TryGetValue(invocation.Method, out recursiveMock))
				{
					invocation.ReturnValue = recursiveMock.Object;
				}
				else
				{
					invocation.ReturnValue = this.Mock.DefaultValueProvider.ProvideDefault(invocation.Method);
				}
			}
		}
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
        {
            var method = invocation.Method;

            if (method.DeclaringType == typeof(Object) && method.Name == "ToString")
            {
                invocation.ReturnValue = ctx.Mock.ToString() + ".Object";
                return InterceptionAction.Stop;
            }

            return InterceptionAction.Continue;
        }
 /// <summary>
 /// Method called after a call is issued.
 /// </summary>
 public abstract void AfterCall(ICallContext callContext);
        public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
        {
            var method = invocation.Method;

            if (typeof(IMocked).IsAssignableFrom(method.DeclaringType) && method.Name == "get_Mock")
            {
                invocation.ReturnValue = ctx.Mock;
                return InterceptionAction.Stop;
            }

            return InterceptionAction.Continue;
        }
 internal void Add(ICallContext invocation, Mock target)
 {
     recordedCalls.Add(invocation, target);
 }
 public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx)
 {
     // Track current invocation if we're in "record" mode in a fluent invocation context.
     if (FluentMockContext.IsActive)
     {
         FluentMockContext.Current.Add(ctx.Mock, invocation);
     }
     return InterceptionAction.Continue;
 }
 public override void BeforeCall(ICallContext callContext)
 {
     callContext.SetProperty("datetimefactory", System.Current.DateTime);
     System.Current.DateTime = mock;
 }
 public override void AfterCall(ICallContext callContext)
 {
     System.Current.DateTime = (IDateTimeFactory)callContext.GetProperty("datetimefactory", null);
 }
Exemple #59
0
		public void Add(Mock mock, ICallContext invocation)
		{
			invocations.Add(new MockInvocation(mock, invocation, LastMatch));
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="DexterCallContextFactory"/> class.
 /// </summary>
 /// <param name="contextWeb">The context web.</param>
 /// <param name="contextAsync">The context async.</param>
 public ArashiCallContextFactory(IWebCallContext contextWeb, IAsyncCallContext contextAsync)
 {
     this.contextWeb = contextWeb;
      this.contextAsync = contextAsync;
 }