Example #1
0
		/// <summary>
		/// Constructs a <see cref="UnexpectedInvocationException"/> with the given parameters.
		/// </summary>
		/// <param name="factory">The MockFactory that threw this exception</param>
		/// <param name="invocation">The unexpected invocation</param>
		/// <param name="expectations">The expectations collection to describe</param>
		/// <param name="message">A message to help the user understand what was unexpected</param>
		internal UnexpectedInvocationException(MockFactory factory, Invocation invocation, IExpectationList expectations, string message)
		{
			if (factory == null)
				throw new ArgumentNullException("factory");
			if (invocation == null)
				throw new ArgumentNullException("invocation");
			if (expectations == null) 
				throw new ArgumentNullException("expectations");

			Factory = factory;

			var writer = new DescriptionWriter();
			writer.WriteLine();
			if (invocation.IsPropertySetAccessor)
				writer.WriteLine(UNEXPECTED_PROPERTY_SETTER_PREFIX);
			else if (invocation.IsPropertyGetAccessor)
				writer.WriteLine(UNEXPECTED_PROPERTY_GETTER_PREFIX);
			else
				writer.WriteLine(MESSAGE_PREFIX);
			writer.Write("  ");
			((ISelfDescribing)invocation).DescribeTo(writer);
			writer.Write(message);
			//expectations.DescribeActiveExpectationsTo(writer);
			//expectations.DescribeUnmetExpectationsTo(writer);
			expectations.DescribeTo(writer);

			_message = writer.ToString();
		}
		public void Process(Invocation invocation)
		{
			foreach (var kvp in this.values)
			{
				invocation.Args[kvp.Key] = kvp.Value;
			}
		}
Example #3
0
        private async Task Run(IRtmpConnection connection)
        {
            var count = 1;
            var token = _tokenSource.Token;
            while (!token.IsCancellationRequested)
            {
                await Task.Delay(TimeSpan.FromMilliseconds(120000), token);
                if (token.IsCancellationRequested)
                    return;

                var date = DateTime.UtcNow.ToString("ddd MMM d yyyy HH:mm:ss 'GMTZ'");
                try
                {
                    var session = _sessionManager.CurrentSession;
                    if (session == null)
                        continue;

                    var invoke = new Invocation<int>("loginService", "performLCDSHeartBeat",
                                                     session.accountSummary.accountId, session.token, count, date);
                    await invoke.Execute(connection);
                }
                catch (AggregateException agg)
                {
                    agg.Handle(e => e is TaskCanceledException);
                }

                count++;
            }
            _tokenSource = null;
            _heartbeat = null;
        }
		public void Process(Invocation invocation)
		{
			++calls;

			Telerik.JustMock.DebugView.TraceEvent(IndentLevel.DispatchResult, () => String.Format("Calls so far: {0}", calls));
			Assert(null, this.UpperBound, calls, null);
		}
		public void Process(Invocation invocation)
		{
			var returnValue = CallOverride(invocation);
			if (implementationOverride.Method.ReturnType != typeof(void) && !this.ignoreDelegateReturnValue)
				invocation.ReturnValue = returnValue;
			invocation.UserProvidedImplementation = true;
		}
		public object CallOverride(Invocation invocation)
		{
			var args = implementationOverride.Method.GetParameters().Length > 0 && invocation.Args != null ? invocation.Args : Empty;

			var paramsCount = invocation.Method.GetParameters().Length;
			var implementationParamsCount = implementationOverride.Method.GetParameters().Length;

			if (invocation.Method.IsExtensionMethod() && paramsCount - 1 == implementationParamsCount)
			{
				args = args.Skip(1).ToArray();
			}

			int extraParamCount = 1 + (implementationOverride.Target != null && implementationOverride.Method.IsStatic ? 1 : 0);
			if (!invocation.Method.IsStatic && extraParamCount + paramsCount == implementationParamsCount)
			{
				args = new[] { invocation.Instance }.Concat(args).ToArray();
			}

			try
			{
				var returnValue = ProfilerInterceptor.GuardExternal(() => overrideInvoker(args, this.implementationOverride));
				return returnValue;
			}
			catch (InvalidCastException ex)
			{
				throw new MockException("The implementation callback has an incorrect signature", ex);
			}
		}
Example #7
0
		public void Process(Invocation invocation)
		{
			if (!invocation.UserProvidedImplementation
				&& !invocation.Recording
				&& (invocation.Method.GetReturnType() != typeof(void) || !throwOnlyOnValueReturningMethods)
				&& !(invocation.Method is ConstructorInfo))
				throw new StrictMockException(invocation.Method.DeclaringType);
		}
		public void Process(Invocation invocation)
		{
			if (ShouldCallOriginal(invocation))
			{
				invocation.UserProvidedImplementation = true;
				invocation.CallOriginal = true;
			}
		}
Example #9
0
        public async void Can_automatically_cancel_the_invocation_after_a_fixed_timespan()
        {
            var connection = new MockRtmpConnection {ShouldTimeout = true};

            var invocation = new Invocation<object>(Invocation.EndpointName, "service", "method");

            await invocation.Execute(connection, TimeSpan.FromSeconds(1));
        }
Example #10
0
        public async void Can_return_faults_when_a_service_call_fails()
        {
            var connection = new MockRtmpConnection {ShouldSucceed = false};

            var failure = new Func<Fault, Exception>(fault => new InvalidOperationException());
            var invocation = new Invocation<object>(Invocation.EndpointName, "service", "method", null, failure);
            await invocation.Execute(connection);
        }
		public void Process(Invocation invocation)
		{
			if ((!invocation.Recording || invocation.RetainBehaviorDuringRecording)
				&& !invocation.UserProvidedImplementation)
			{
				invocation.UserProvidedImplementation = true;
				invocation.CallOriginal = true;
			}
		}
Example #12
0
		public object Invoke(object target, MethodInfo methodInfo, object[] parameters)
		{
			var i = new Invocation(
				methodInfo.Name,
				methodInfo.ReturnType,
				parameters);

			return Invoke(i);
		}
		public void Process(Invocation invocation)
		{
			var method = invocation.Method;
			if (method is ConstructorInfo && method.IsPrivate && method.IsStatic)
			{
				var mixin = MocksRepository.GetMockMixinFromInvocation(invocation);
				invocation.CallOriginal = mixin == null || !mixin.IsStaticConstructorMocked;
			}
		}
		public void Process(Invocation invocation)
		{
			if (invocation.IsReturnValueSet)
				return;

			var returnType = invocation.Method.GetReturnType();
			if (returnType == typeof(void) || returnType.IsValueType)
				return;

			if (invocation.Method.Name == "ToString"
				&& invocation.Method.GetParameters().Length == 0
				&& invocation.UserProvidedImplementation)
				return;
			if (invocation.Method.Name == "GetType"
				&& invocation.Method.GetReturnType() == typeof(Type)
				&& invocation.Method.GetParameters().Length == 0)
				return;

			object mock = null;
			List<KeyValuePair<object, object>> mocksList;
			if (mocks.TryGetValue(invocation.Method, out mocksList))
			{
				// can't put the key part in a Dictionary,
				// because we can't be sure that GetHashCode() works
				mock = mocksList.FirstOrDefault(kvp => Equals(kvp.Key, invocation.Instance)).Value;
			}

			if (mock == null)
			{
				var parentMock = invocation.MockMixin;
				var repository = parentMock.Repository;

				if (MustReturnMock(invocation) || this.type == RecursiveMockingBehaviorType.ReturnDefault)
				{
					mock = CreateMock(returnType, repository, invocation);
				}

				if (mock == null)
					return;

				if (mocksList == null)
				{
					mocksList = new List<KeyValuePair<object, object>>();
					mocks.Add(invocation.Method, mocksList);
				}
				mocksList.Add(new KeyValuePair<object, object>(invocation.Instance, mock));

				var mockMixin = MocksRepository.GetMockMixin(mock, null);
				if (parentMock != null && mockMixin != null)
					parentMock.DependentMocks.Add(mock);
			}

			invocation.ReturnValue = mock;
			invocation.CallOriginal = false;
			invocation.UserProvidedImplementation = true;
		}
		public void Process(Invocation invocation)
		{
			var method = invocation.Method;
			if (method is ConstructorInfo && !method.IsStatic)
			{
				var mixin = invocation.MockMixin;
				invocation.CallOriginal = mixin != null ? !mixin.IsInstanceConstructorMocked : true;
				invocation.UserProvidedImplementation = true;
			}
		}
Example #16
0
 public void Intercept(Invocation methodInvoke)
 {
     // 执行目标方法
     methodInvoke.Invoke();
     // 如果输出流方式或包含输出流方式
     if (methodInvoke.MethodMetaData.OutputType == TypeCategory.BinaryType && methodInvoke.RetValue != null) {
         TransferFile tfile = ((TransferFile)methodInvoke.RetValue);
         NDWR.Util.Kit.SetAbsCache(tfile.ID, tfile);
         methodInvoke.RetValue = tfile.ID;
     }
 }
		public void Process(Invocation invocation)
		{
			var mockMixin = invocation.MockMixin;
			if (mockMixin == null)
			{
				mockMixin = invocation.Repository.CreateExternalMockMixin(null, invocation.Instance, Behavior.CallOriginal);
				mockMixin.IsInstanceConstructorMocked = true;
			}

			invocation.CallOriginal = !mockMixin.IsInstanceConstructorMocked;
		}
Example #18
0
        public async void Can_execute_a_service_call()
        {
            var connection = new MockRtmpConnection {ShouldSucceed = true};

            var successful = false;
            var success = new Action<object>(o => successful = true);
            var invocation = new Invocation<object>(Invocation.EndpointName, "service", "method", success, null);
            var result = await invocation.Execute(connection);

            Assert.That(result, Is.Not.Null);
            Assert.That(successful, Is.True);
        }
Example #19
0
 public void Intercept(Invocation methodInvoke)
 {
     try {
         methodInvoke.Invoke();
     } catch (Exception ex) {
         methodInvoke.SystemErrors.Add(
             new RspError(SystemError.ServiceException, ex.Message)
         );
         log.Error("ExceptionInterceptor捕获到异常", ex);
         //throw ex;
     }
 }
		public void Process(Invocation invocation)
		{
			if (invocation.Method.IsVirtual
				&& typeof(object).GetMethods().Any(method =>
					method.Name == invocation.Method.Name
					&& method.ReturnType == invocation.Method.GetReturnType()
					&& method.GetParameters().Select(p => p.ParameterType).SequenceEqual(invocation.Method.GetParameters().Select(p => p.ParameterType))
				))
			{
				invocation.CallOriginal = true;
			}
		}
Example #21
0
        public async Task Logout(IRtmpConnection connection)
        {
            if (CurrentSession == null)
                return;
            if (string.IsNullOrWhiteSpace(CurrentSession.token))
                return;

            var invoke = new Invocation<AcknowledgeMessage>("loginService", "logout", CurrentSession.token);
            var message = await invoke.Execute(connection);

            return;
        }
		public void Process(Invocation invocation)
		{
			var mockMethod = invocation.Method;
			var inheritanceChain = mockMethod.GetInheritanceChain();

			var delegatedImplMethod = inheritanceChain.FirstOrDefault(method => types.Any(t => method.DeclaringType.IsAssignableFrom(t)));
			if (delegatedImplMethod != null)
			{
				invocation.ReturnValue = delegatedImplMethod.Invoke(implementer, invocation.Args);
				invocation.UserProvidedImplementation = true;
			}
		}
        protected override void Analyze(Invocation invocation, string invocationPointer)
        {
            if (invocation.StartTime > invocation.EndTime)
            {
                string endTimePointer = invocationPointer.AtProperty(SarifPropertyName.EndTime);

                LogResult(
                    endTimePointer,
                    nameof(RuleResources.SARIF007_Default),
                    FormatDateTime(invocation.EndTime),
                    FormatDateTime(invocation.StartTime));
            }
        }
Example #24
0
		public void Process(Invocation invocation)
		{
			this.wasCalled = true;
			this.calledInWrongOrder = (this.LastIdInOrder != this.arrangementId - 1);
			this.LastIdInOrder = this.arrangementId;

			this.InOrderExecutionLog += invocation.InputToString() + " called at:\n" + MockingContext.GetStackTrace("    ");

			if (this.calledInWrongOrder)
			{
				MockingContext.Fail("Last call executed out of order. Order of calls so far:\n{1}", invocation.InputToString(), InOrderExecutionMessage);
			}
		}
Example #25
0
        public void Track(MethodBase method, object[] arguments, IInternalSetup setup)
        {
            Invocation invocation = new Invocation(setup, arguments);

            _invocations.AddOrUpdate(
                method,
                new List<Invocation> { invocation },
                (key, existing) =>
                {
                    existing.Add(invocation);
                    return existing;
                });
        }
Example #26
0
        public async Task<LolSession> Login(IRtmpConnection connection, AuthenticationCredentials credentials)
        {
            Credentials = credentials;

            var invoke = new Invocation<LolSession>("loginService", "login", credentials);
            CurrentSession = await invoke.Execute(connection);

            await AuthorizeSession(connection, CurrentSession);

            if (_action != null)
                _action();

            return CurrentSession;
        }
Example #27
0
        public async void Can_manually_cancel_the_invocation()
        {
            var connection = new MockRtmpConnection {ShouldTimeout = true};

            var invocation = new Invocation<object>(Invocation.EndpointName, "service", "method");
            using (var tcs = new CancellationTokenSource())
            {
                var task = invocation.Execute(connection, tcs.Token);

                // immediately cancel
                tcs.Cancel();

                await task;
            }
        }
		public void Process(Invocation invocation)
		{
			if (!invocation.UserProvidedImplementation
				&& !invocation.Recording
				&& (invocation.Method.GetReturnType() != typeof(void) || !throwOnlyOnValueReturningMethods)
				&& !(invocation.Method is ConstructorInfo))
			{
				if (strictnessViolationMessage == null)
					strictnessViolationMessage = new StringBuilder();
				strictnessViolationMessage.AppendFormat("Called unarranged member '{0}' on strict mock of type '{1}'\n",
					invocation.Method, invocation.Method.DeclaringType);

				throw new StrictMockException(invocation.Method.DeclaringType);
			}
		}
		public void Process(Invocation invocation)
		{
			var method = invocation.Method;

			var candidateEvent = method.GetEventFromAddOrRemove();
			if (candidateEvent == null)
				return;

			invocation.UserProvidedImplementation = true;

			var delg = (Delegate)invocation.Args[0];
			if (candidateEvent.GetAddMethod() == invocation.Method)
				this.AddEventHandler(candidateEvent, delg);
			else
				this.RemoveEventHandler(candidateEvent, delg);
		}
Example #30
0
		public void Process(Invocation invocation)
		{
			if (!invocation.UserProvidedImplementation
				&& !invocation.Recording
				&& (invocation.Method.GetReturnType() != typeof(void) || !throwOnlyOnValueReturningMethods)
				&& !(invocation.Method is ConstructorInfo)
				&& !invocation.InArrange)
			{
				if (strictnessViolationMessage == null)
					strictnessViolationMessage = new StringBuilder();
				strictnessViolationMessage.AppendFormat(
					throwOnlyOnValueReturningMethods ? MissingReturnValueMessage : GenericErrorMessage,
					invocation.Method, invocation.Method.DeclaringType);

				throw new StrictMockException(strictnessViolationMessage.ToString());
			}
		}
Example #31
0
        private static Run CreateRun(
            IEnumerable <string> analysisTargets,
            OptionallyEmittedData dataToInsert,
            IEnumerable <string> invocationTokensToRedact,
            IEnumerable <string> invocationPropertiesToLog,
            string defaultFileEncoding = null)
        {
            var run = new Run
            {
                Invocations     = new List <Invocation>(),
                DefaultEncoding = defaultFileEncoding
            };

            if (analysisTargets != null)
            {
                run.Artifacts = new List <Artifact>();

                foreach (string target in analysisTargets)
                {
                    Uri uri = new Uri(UriHelper.MakeValidUri(target), UriKind.RelativeOrAbsolute);

                    var fileData = Artifact.Create(
                        new Uri(target, UriKind.RelativeOrAbsolute),
                        dataToInsert);

                    var fileLocation = new ArtifactLocation
                    {
                        Uri = uri
                    };

                    fileData.Location = fileLocation;

                    // This call will insert the file object into run.Files if not already present
                    fileData.Location.Index = run.GetFileIndex(fileData.Location, addToFilesTableIfNotPresent: true, dataToInsert);
                }
            }

            var invocation = Invocation.Create(dataToInsert.HasFlag(OptionallyEmittedData.EnvironmentVariables), invocationPropertiesToLog);

            // TODO we should actually redact across the complete log file context
            // by a dedicated rewriting visitor or some other approach.

            if (invocationTokensToRedact != null)
            {
                invocation.CommandLine = Redact(invocation.CommandLine, invocationTokensToRedact);
                invocation.Machine     = Redact(invocation.Machine, invocationTokensToRedact);
                invocation.Account     = Redact(invocation.Account, invocationTokensToRedact);

                if (invocation.WorkingDirectory != null)
                {
                    invocation.WorkingDirectory.Uri = Redact(invocation.WorkingDirectory.Uri, invocationTokensToRedact);
                }

                if (invocation.EnvironmentVariables != null)
                {
                    string[] keys = invocation.EnvironmentVariables.Keys.ToArray();

                    foreach (string key in keys)
                    {
                        string value = invocation.EnvironmentVariables[key];
                        invocation.EnvironmentVariables[key] = Redact(value, invocationTokensToRedact);
                    }
                }
            }

            run.Invocations.Add(invocation);
            return(run);
        }
 public int Run(string a, string b)
 {
     Calls.Add(Invocation.Split(a, b));
     return(88);
 }
Example #33
0
        public void Process(Invocation invocation)
        {
            if (invocation.IsReturnValueSet)
            {
                return;
            }

            var returnType = invocation.Method.GetReturnType();

            if (returnType == typeof(void) || returnType.IsValueType)
            {
                return;
            }

            if (invocation.Method.Name == "ToString" &&
                invocation.Method.GetParameters().Length == 0 &&
                invocation.UserProvidedImplementation)
            {
                return;
            }
            if (invocation.Method.Name == "GetType" &&
                invocation.Method.GetReturnType() == typeof(Type) &&
                invocation.Method.GetParameters().Length == 0)
            {
                return;
            }

            object mock = null;
            List <KeyValuePair <object, object> > mocksList;

            if (mocks.TryGetValue(invocation.Method, out mocksList))
            {
                // can't put the key part in a Dictionary,
                // because we can't be sure that GetHashCode() works
                mock = mocksList.FirstOrDefault(kvp => Equals(kvp.Key, invocation.Instance)).Value;
            }

            if (mock == null)
            {
                var parentMock = invocation.MockMixin;
                var repository = parentMock.Repository;

                if (MustReturnMock(invocation) || this.type == RecursiveMockingBehaviorType.ReturnDefault)
                {
                    mock = CreateMock(returnType, repository, invocation);
                }

                if (mock == null)
                {
                    return;
                }

                if (mocksList == null)
                {
                    mocksList = new List <KeyValuePair <object, object> >();
                    mocks.Add(invocation.Method, mocksList);
                }
                mocksList.Add(new KeyValuePair <object, object>(invocation.Instance, mock));

                var mockMixin = MocksRepository.GetMockMixin(mock, null);
                if (parentMock != null && mockMixin != null)
                {
                    parentMock.DependentMocks.Add(mock);
                }
            }

            invocation.ReturnValue  = mock;
            invocation.CallOriginal = false;
            invocation.UserProvidedImplementation = true;
        }
Example #34
0
        internal Run CreateRun(RunVersionOne v1Run)
        {
            Run run = null;

            if (v1Run != null)
            {
                if (v1Run.TryGetProperty("sarifv2/run", out run))
                {
                    return(run);
                }
                else
                {
                    _currentV1Run = v1Run;

                    _v1FileKeytoV2IndexMap = CreateFileKeyToIndexMapping(v1Run.Files);
                    _v1RuleKeyToV2IndexMap = CreateRuleKeyToIndexMapping(v1Run.Rules);

                    RunAutomationDetails   id           = null;
                    RunAutomationDetails[] aggregateIds = null;

                    if (v1Run.Id != null || v1Run.StableId != null)
                    {
                        id = new RunAutomationDetails
                        {
                            Guid = v1Run.Id,
                            Id   = v1Run.StableId != null ? v1Run.StableId + "/" : null
                        };
                    }

                    if (v1Run.AutomationId != null)
                    {
                        aggregateIds = new[] { new RunAutomationDetails {
                                                   Id = v1Run.AutomationId + "/"
                                               } };
                    }

                    run = new Run()
                    {
                        AutomationDetails = id,
                        RunAggregates     = aggregateIds,
                        BaselineGuid      = v1Run.BaselineId,
                        Properties        = v1Run.Properties,
                        Language          = v1Run.Tool?.Language ?? "en-US",
                        Tool       = CreateTool(v1Run.Tool),
                        ColumnKind = ColumnKind.Utf16CodeUnits
                    };

                    _currentRun = run;

                    if (v1Run.Rules != null)
                    {
                        run.Tool.Driver.Rules = new List <ReportingDescriptor>();

                        foreach (var pair in v1Run.Rules)
                        {
                            run.Tool.Driver.Rules.Add(CreateRule(pair.Value));
                        }
                    }

                    if (v1Run.Files != null)
                    {
                        run.Artifacts = new List <Artifact>();

                        foreach (KeyValuePair <string, FileDataVersionOne> pair in v1Run.Files)
                        {
                            FileDataVersionOne fileDataVersionOne = pair.Value;
                            if (fileDataVersionOne.Uri == null)
                            {
                                fileDataVersionOne.Uri = new Uri(pair.Key, UriKind.RelativeOrAbsolute);
                            }

                            run.Artifacts.Add(CreateFileData(fileDataVersionOne, pair.Key));
                        }
                    }

                    if (v1Run.LogicalLocations != null)
                    {
                        // Pass 1 over results. In this phase, we're simply collecting fully qualified names that
                        // may be duplicated in the logical locations dictionary. We're doing this so that we
                        // can properly construct the v2 logical instances in the converted array (i.e., we can't
                        // populate the v2 logicalLocation.FullyQualifiedName property in cases where the
                        // v1 key is a synthesized value and not actually the fully qualified name)
                        var visitor = new VersionOneLogicalLocationKeyToLogicalLocationDataVisitor();
                        visitor.VisitRunVersionOne(v1Run);

                        _v1KeyToFullyQualifiedNameMap           = visitor.LogicalLocationKeyToFullyQualifiedNameMap;
                        _v1LogicalLocationKeyToDecoratedNameMap = visitor.LogicalLocationKeyToDecoratedNameMap;

                        run.LogicalLocations = new List <LogicalLocation>();
                        HashSet <string> populatedKeys = new HashSet <string>();

                        foreach (KeyValuePair <string, LogicalLocationVersionOne> pair in v1Run.LogicalLocations)
                        {
                            PopulateLogicalLocation(
                                run,
                                v1Run.LogicalLocations,
                                _v1LogicalLocationKeyToDecoratedNameMap,
                                _v1KeyToFullyQualifiedNameMap,
                                pair.Key,
                                pair.Value,
                                populatedKeys);
                        }
                    }

                    // Even if there is no v1 invocation, there may be notifications
                    // in which case we will need a v2 invocation to contain them
                    Invocation invocation = CreateInvocation(v1Run.Invocation,
                                                             v1Run.ToolNotifications,
                                                             v1Run.ConfigurationNotifications);

                    if (invocation != null)
                    {
                        run.Invocations = new List <Invocation>()
                        {
                            invocation
                        };
                    }

                    if (v1Run.Results != null)
                    {
                        run.Results = new List <Result>();

                        foreach (ResultVersionOne v1Result in v1Run.Results)
                        {
                            Result result = CreateResult(v1Result);
                            run.Results.Add(result);
                        }
                    }

                    // Stash the entire v1 run in this v2 run's property bag
                    if (EmbedVersionOneContentInPropertyBag)
                    {
                        run.SetProperty($"{FromPropertyBagPrefix}/run", v1Run);
                    }
                }
            }

            _currentRun = null;

            return(run);
        }
 public int Run(IList <string> args)
 {
     Calls.Add(Invocation.List(args));
     return(99);
 }
Example #36
0
 protected bool Equals(Invocation other)
 {
     return(Equals(Args, other.Args) && Equals(Function, other.Function));
 }
 public abstract bool MatchesIgnoringIsActive(Invocation invocation);
Example #38
0
        public void CantSetParameterValueForNonOutOrRefParameter()
        {
            var invocation = new Invocation(target, typeof(IMyInterface).GetMethod("MethodWithInputValue"), null, new object[1], null, 0);

            Assert.Throws <InvalidOperationException>(() => invocation.ParameterValues[0] = 0);
        }
Example #39
0
        public void ParameterAndGenericArgumentsListsHasRestrictedAccess()
        {
            var item = new object();
            var type = typeof(object);

            var invocation =
                new Invocation(
                    target,
                    typeof(IMyInterface).GetMethod("MethodWithGenericArguments"),
                    new List <Type> {
                type
            },
                    new List <object> {
                item
            },
                    null,
                    0);

            var parameterValues  = invocation.ParameterValues;
            var genericArguments = invocation.GenericArguments;

            AssertIsNotSupported(() => parameterValues.Add(item));
            AssertIsNotSupported(() => genericArguments.Add(type));

            AssertIsNotSupported(() => parameterValues.Remove(item));
            AssertIsNotSupported(() => genericArguments.Remove(type));

            AssertIsNotSupported(() => parameterValues.RemoveAt(0));
            AssertIsNotSupported(() => genericArguments.RemoveAt(0));

            AssertIsNotSupported(() => parameterValues.Insert(0, item));
            AssertIsNotSupported(() => genericArguments.Insert(0, type));

            AssertIsNotSupported(parameterValues.Clear);
            AssertIsNotSupported(parameterValues.Clear);


            Assert.AreEqual(1, parameterValues.Count);
            Assert.AreEqual(1, genericArguments.Count);

            Assert.IsTrue(parameterValues.Contains(item));
            Assert.IsTrue(genericArguments.Contains(type));

            Assert.AreEqual(0, parameterValues.IndexOf(item));
            Assert.AreEqual(0, genericArguments.IndexOf(type));

            Assert.AreEqual(item, parameterValues[0]);
            Assert.AreEqual(type, genericArguments[0]);

            parameterValues[0] = item;
            AssertIsNotSupported(() => genericArguments[0] = type);

            var arrayCopy = new object[1];

            parameterValues.CopyTo(arrayCopy, 0);
            Assert.AreEqual(item, arrayCopy[0]);

            var arrayCopy2 = new Type[1];

            genericArguments.CopyTo(arrayCopy2, 0);
            Assert.AreEqual(type, arrayCopy2[0]);

            var enumerator = ((System.Collections.IEnumerable)parameterValues).GetEnumerator();

            Assert.IsTrue(enumerator.MoveNext());
            Assert.AreEqual(item, enumerator.Current);
            Assert.IsFalse(enumerator.MoveNext());

            var enumerator2 = ((System.Collections.IEnumerable)genericArguments).GetEnumerator();

            Assert.IsTrue(enumerator2.MoveNext());
            Assert.AreEqual(type, enumerator2.Current);
            Assert.IsFalse(enumerator2.MoveNext());

            Assert.IsFalse(parameterValues.IsReadOnly);
            Assert.IsFalse(genericArguments.IsReadOnly);
        }
Example #40
0
        public void CantSetParameterValueToNonAssignableValue()
        {
            var invocation = new Invocation(target, typeof(IMyInterface).GetMethod("MethodWithOutAndRefValues"), null, new object[2], null, 0);

            Assert.Throws <InvalidOperationException>(() => invocation.ParameterValues[0] = new object());
        }
Example #41
0
        public void CantSetReturnValueForMethodWithoutReturnValue()
        {
            var invocation = new Invocation(target, typeof(IMyInterface).GetMethod("MethodWithoutReturnValue"), null, new object[2], null, 0);

            Assert.Throws <InvalidOperationException>(() => invocation.ReturnValue = 0);
        }
Example #42
0
        public void CantSetReturnValueToNonAssignableValue()
        {
            var invocation = new Invocation(target, typeof(IMyInterface).GetMethod("Method"), null, new object[0], default(int), 0);

            Assert.Throws <InvalidOperationException>(() => invocation.ReturnValue = null);
        }
 public abstract bool Perform(Invocation invocation);
 void IAction.Invoke(Invocation invocation)
 {
     invocation.SetterResult = invocation.Arguments[invocation.Arguments.Length - 1];
 }
 public abstract bool Matches(Invocation invocation);
        public override void Execute(Invocation invocation)
        {
            Debug.Assert(invocation.Method != null);
            Debug.Assert(invocation.Method.ReturnType != null);

            var method = invocation.Method;

            if (this.mock.CallBase)
            {
#if FEATURE_DEFAULT_INTERFACE_IMPLEMENTATIONS
                var tryCallDefaultInterfaceImplementation = false;
#endif

                var declaringType = method.DeclaringType;
                if (declaringType.IsInterface)
                {
                    if (this.mock.MockedType.IsInterface)
                    {
                        // Case 1: Interface method of an interface proxy.

#if FEATURE_DEFAULT_INTERFACE_IMPLEMENTATIONS
                        // Fall through to invoke default implementation (if one exists).
                        tryCallDefaultInterfaceImplementation = true;
#else
                        // There is no base method to call, so fall through.
#endif
                    }
                    else
                    {
                        Debug.Assert(mock.MockedType.IsClass);
                        Debug.Assert(mock.ImplementsInterface(declaringType));

                        // Case 2: Explicitly implemented interface method of a class proxy.

                        if (this.mock.InheritedInterfaces.Contains(declaringType))
                        {
                            // Case 2a: Re-implemented interface.
                            // The base class has its own implementation. Only call base method if it isn't an event accessor.
                            if (!method.IsEventAddAccessor() && !method.IsEventRemoveAccessor())
                            {
                                invocation.ReturnValue = invocation.CallBase();
                                return;
                            }
                        }
                        else
                        {
                            Debug.Assert(this.mock.AdditionalInterfaces.Contains(declaringType));

                            // Case 2b: Additional interface.

#if FEATURE_DEFAULT_INTERFACE_IMPLEMENTATIONS
                            // Fall through to invoke default implementation (if one exists).
                            tryCallDefaultInterfaceImplementation = true;
#else
                            // There is no base method to call, so fall through.
#endif
                        }
                    }
                }
                else
                {
                    Debug.Assert(declaringType.IsClass);

                    // Case 3: Non-interface method of a class proxy.
                    // Only call base method if it isn't abstract.
                    if (!method.IsAbstract)
                    {
                        invocation.ReturnValue = invocation.CallBase();
                        return;
                    }
                }

#if FEATURE_DEFAULT_INTERFACE_IMPLEMENTATIONS
                if (tryCallDefaultInterfaceImplementation && !method.IsAbstract)
                {
                    // Invoke default implementation.
                    invocation.ReturnValue = invocation.CallBase();
                    return;
                }
#endif
            }

            if (method.ReturnType != typeof(void))
            {
                var returnValue = this.mock.GetDefaultValue(method, out var innerMock);
                if (innerMock != null && invocation.MatchingSetup == null)
                {
                    var setup = new InnerMockSetup(originalExpression: null, this.mock, expectation: MethodExpectation.CreateFrom(invocation), returnValue);
                    this.mock.MutableSetups.Add(setup);
                    setup.Execute(invocation);
                }
                else
                {
                    invocation.ReturnValue = returnValue;
                }
            }
        }
 public abstract bool ContainsOrderedExpectationFor(Invocation invocation);
Example #48
0
 public void Before <TParam, TResult>(Invocation <TParam, TResult> invocation)
 => StartWatch(invocation);
 public int Run(string a)
 {
     Calls.Add(Invocation.Split(a));
     return(89);
 }
Example #50
0
        private object CreateMock(Type returnType, MocksRepository repository, Invocation invocation)
        {
            var parentMock = invocation.MockMixin;
            var replicator = parentMock as IMockReplicator;

            object mock = null;

            if (returnType.IsArray)
            {
                mock = Array.CreateInstance(returnType.GetElementType(), Enumerable.Repeat(0, returnType.GetArrayRank()).ToArray());
            }

            var idictionaryType = returnType.GetImplementationOfGenericInterface(typeof(IDictionary <,>));

            if (mock == null && idictionaryType != null)
            {
                var dictType = typeof(Dictionary <,>).MakeGenericType(idictionaryType.GetGenericArguments());
                mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(dictType));
            }

            var ienumerableType = returnType.GetImplementationOfGenericInterface(typeof(IEnumerable <>));

            if (mock == null && ienumerableType != null)
            {
                var listType = typeof(List <>).MakeGenericType(ienumerableType.GetGenericArguments());
                mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(listType));
            }

            if (mock == null && typeof(Task).IsAssignableFrom(returnType))
            {
                var elementType = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>)
                                        ? returnType.GetGenericArguments()[0] : typeof(object);
                var taskResultValue = MustReturnMock(invocation)
                                        ? CreateMock(elementType, repository, invocation)
                                        : elementType.GetDefaultValue();

                Expression <Func <Task <object> > > taskFromResult = () => MockingUtil.TaskFromResult((object)null);
                mock = ((MethodCallExpression)taskFromResult.Body).Method
                       .GetGenericMethodDefinition()
                       .MakeGenericMethod(elementType)
                       .Invoke(null, new object[] { taskResultValue });
            }

#if !PORTABLE
            if (mock == null && returnType.IsByRef)
            {
                var             delegateType = typeof(object).Assembly.GetType("Telerik.JustMock.RefDelegate`1").MakeGenericType(new [] { returnType.GetElementType() });
                ConstructorInfo constructor  = delegateType.GetConstructor(new[] { typeof(object), typeof(IntPtr) });

                MethodInfo genericMethodInfo = this.GetType().GetMethod("GetDefaultRef", BindingFlags.NonPublic | BindingFlags.Instance);
                MethodInfo methodInfo        = genericMethodInfo.MakeGenericMethod(returnType.GetElementType());

                mock = constructor.Invoke(new object[] { this, methodInfo.MethodHandle.GetFunctionPointer() });
            }
#endif

            if (mock == null && MustReturnMock(invocation, checkPropertyOnTestFixture: true))
            {
                if (typeof(String) == returnType)
                {
                    mock = String.Empty;
                }
                else
                {
                    try
                    {
                        mock = replicator.CreateSimilarMock(repository, returnType, null, true, null);
                    }
                    catch (MockException)
                    { }
                }
            }

            return(mock);
        }
 public int Run()
 {
     Calls.Add(Invocation.Split());
     return(79);
 }
        /// <summary>
        /// Invoke the action asynchronously
        /// </summary>
        /// <remarks>Returns immediately and will run the client-specified callback when the action
        /// later completes.  Any output arguments can then be retrieved by calling
        /// EndRestore().</remarks>
        /// <param name="aCallback">Delegate to run when the action completes.
        /// This is guaranteed to be run but may indicate an error</param>
        public void BeginRestore(CallbackAsyncComplete aCallback)
        {
            Invocation invocation = iService.Invocation(iActionRestore, aCallback);

            iService.InvokeAction(invocation);
        }
Example #53
0
 protected override void ExecuteCore(Invocation invocation)
 {
     invocation.Return(this.returnValue);
 }
        /// <summary>
        /// Invoke the action asynchronously
        /// </summary>
        /// <remarks>Returns immediately and will run the client-specified callback when the action
        /// later completes.  Any output arguments can then be retrieved by calling
        /// EndApply().</remarks>
        /// <param name="aCallback">Delegate to run when the action completes.
        /// This is guaranteed to be run but may indicate an error</param>
        public void BeginApply(CallbackAsyncComplete aCallback)
        {
            Invocation invocation = iService.Invocation(iActionApply, aCallback);

            iService.InvokeAction(invocation);
        }
Example #55
0
 public void AfterReturning <TParam, TResult>(Invocation <TParam, TResult> invocation)
 => StopWatch(invocation);
Example #56
0
 /// <summary>
 /// 复制调用中参数的信息
 /// </summary>
 /// <param name="invocation">The invocation.</param>
 /// <param name="arguments">The arguments.</param>
 /// <returns></returns>
 public Invocation CopyArguments(Invocation invocation, List <KeyValuePair <string, object> > arguments)
 {
     invocation.Arguments = arguments == null ? new KeyValuePair <string, object> [0] : arguments.ToArray();
     return(invocation);
 }
Example #57
0
 public void AfterThrowing <TParam, TResult>(Invocation <TParam, TResult> invocation, ref Exception exception)
 => StopWatch(invocation);
Example #58
0
 public override void Execute(Invocation invocation)
 {
     throw this.exception;
 }
Example #59
0
            /// <summary>
            /// Parses an invocation from a TSV Line
            /// </summary>
            /// <remarks>
            /// This code is version aware. For now we only have one version and we'll treat all future line format versions
            /// as unsupported (indisinguisable from wrong file formats). This will make new lines not show up in old
            /// consumers. Updated version should support reading old ones.
            /// </remarks>
            public static bool TryParseTsvLine(string line, out Invocation invocation, out string errorDetails)
            {
                invocation = default;
                if (string.IsNullOrEmpty(line))
                {
                    errorDetails = "empty line";
                    return(false);
                }

                var parts = line.Split('\t');

                // Check for line format version
                if (parts.Length < 1 || !int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var lineVersion))
                {
                    errorDetails = "Error extracting line version";
                    return(false);
                }

                switch (lineVersion)
                {
                case 0:
                    if (parts.Length != 8)
                    {
                        errorDetails = "Unexpected number of parts for v1: " + parts.Length;
                        return(false);
                    }

                    var sessionId = parts[1];
                    if (string.IsNullOrEmpty(sessionId))
                    {
                        errorDetails = "Failed to parse sessionId";
                        return(false);
                    }

                    if (!DateTime.TryParseExact(parts[2], "O", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var buildStartTimeUtc))
                    {
                        errorDetails = "Failed to parse activityId";
                        return(false);
                    }

                    var primaryConfigFile = parts[3];
                    if (string.IsNullOrEmpty(primaryConfigFile))
                    {
                        errorDetails = "Failed to parse primaryConfigFile";
                        return(false);
                    }

                    var logsFolder = parts[4];
                    if (string.IsNullOrEmpty(logsFolder))
                    {
                        errorDetails = "Failed to parse logsFolder";
                        return(false);
                    }

                    var engineVersion = parts[5];
                    if (string.IsNullOrEmpty(engineVersion))
                    {
                        errorDetails = "Failed to parse engineVersion";
                        return(false);
                    }

                    var engineBinFolder = parts[6];
                    if (string.IsNullOrEmpty(engineBinFolder))
                    {
                        errorDetails = "Failed to parse engineBinFolder";
                        return(false);
                    }

                    var engineCommitId = parts[7];
                    if (string.IsNullOrEmpty(engineCommitId))
                    {
                        errorDetails = "Failed to parse engineCommitId";
                        return(false);
                    }

                    invocation = new Invocation(
                        lineVersion,
                        sessionId,
                        buildStartTimeUtc.ToUniversalTime(),
                        primaryConfigFile,
                        logsFolder,
                        engineVersion,
                        engineBinFolder,
                        engineCommitId
                        );
                    errorDetails = null;
                    return(true);

                default:
                    // Unsupported line format version
                    errorDetails = "Unsupported version:" + lineVersion;
                    return(false);
                }
            }
Example #60
0
 public override T Execute <T>(Invocation <T> invocation)
 {
     return(execute(invocation, 0));
 }