public void Resulting_spec_should_be_satisfied_if_call_method_and_arg_specs_are_satisfied() { var specifiedMethod = _call.GetMethodInfo(); var args = CreateArgsThatMatchArgSpecsFromFactory(); var callThatShouldMatch = CreateStubCall(specifiedMethod, args); Assert.That(_result.IsSatisfiedBy(callThatShouldMatch)); }
private string FormatCall(ICall call, bool isAcrossMultipleTargets, TypeInstanceNumberLookup instanceLookup) { var s = _callFormatter.Format(call.GetMethodInfo(), FormatArgs(call.GetArguments())); if (!isAcrossMultipleTargets) return s; var target = call.Target(); var methodInfo = call.GetMethodInfo(); return FormatCallForInstance(instanceLookup, target, methodInfo, s); }
public TArgument Arg <TArgument>(int index) { if (index < 0 || index >= _call.GetArguments().Length) { throw new InvalidOperationException("Method '" + _call.GetMethodInfo().Name + "' do not have that many arguments."); } if (_call.GetArguments()[index] is TArgument) { return((TArgument)_call.GetArguments()[index]); } throw new InvalidOperationException("Argument " + index + " of '" + _call.GetMethodInfo().Name + "' cannot be converted to '" + typeof(TArgument) + "'."); }
public RouteAction Handle(ICall call) { var methodInfo = call.GetMethodInfo(); var eventInfo = FindEventInfo(methodInfo); if (eventInfo == null) { throw new CouldNotRaiseEventException(); } object?[] eventArguments = _getEventArguments(call); var handlers = _eventHandlerRegistry.GetHandlers(eventInfo.Name); foreach (Delegate handler in handlers) { try { handler.DynamicInvoke(eventArguments); } catch (TargetInvocationException e) { throw e.InnerException !; } } return(RouteAction.Continue());
public RouteAction Handle(ICall call) { var methodInfo = call.GetMethodInfo(); var eventInfo = methodInfo.DeclaringType.GetEvents().FirstOrDefault( x => (x.GetAddMethod() == methodInfo) || (x.GetRemoveMethod() == methodInfo)); if (eventInfo == null) { throw new CouldNotRaiseEventException(); } var handlers = _eventHandlerRegistry.GetHandlers(eventInfo.Name); var eventArguments = _getEventArguments(call); foreach (Delegate handler in handlers) { try { handler.DynamicInvoke(eventArguments); } catch (TargetInvocationException e) { throw e.InnerException; } } return(RouteAction.Continue()); }
public bool IsSatisfiedBy(ICall call) { if (_methodInfo != call.GetMethodInfo()) return false; if (HasDifferentNumberOfArguments(call)) return false; if (NonMatchingArguments(call).Any()) return false; return true; }
public RouteAction Handle(ICall call) { var mockedDbContext = call.Target(); var invokedMethod = call.GetMethodInfo(); var arguments = call.GetArguments(); var modelType = GetModelType(invokedMethod); if (modelType == null) { return(RouteAction.Return(invokedMethod.ReturnType.GetDefaultValue())); } Logger.LogDebug("Setting up model '{type}'", modelType); var modelEntityType = _allModelEntityTypes.SingleOrDefault(x => x.ClrType.Equals(modelType)); if (modelEntityType == null) { throw new InvalidOperationException(string.Format(ExceptionMessages.CannotCreateDbSetTypeNotIncludedInModel, invokedMethod.GetGenericArguments().Single().Name)); } var setUpModelMethod = typeof(NoSetUpHandler <TDbContext>).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) .Single(x => x.Name.Equals(modelEntityType.FindPrimaryKey() != null ? "SetUpModel" : "SetUpReadOnlyModel")); setUpModelMethod.MakeGenericMethod(modelType).Invoke(this, new[] { mockedDbContext }); return(RouteAction.Return(invokedMethod.Invoke(mockedDbContext, arguments?.ToArray()))); }
/// <summary> /// Assert that <paramref name="call"/> has one generic argument, of type <typeparamref name="TExpected"/> /// </summary> /// <typeparam name="TExpected">Generic argument</typeparam> /// <param name="call">Call</param> /// <exception cref="GenericArgumentException"></exception> internal static void AssertGenericArgument <TExpected>(ICall call) { // Check correct number of generic arguments var args = call.GetMethodInfo().GetGenericArguments(); if (args.Length == 0) { throw new GenericArgumentException("Expected one generic argument but found none."); } if (args.Length > 1) { throw new GenericArgumentException($"Expected one generic argument but found {args.Length}."); } // Check generic argument var expected = typeof(TExpected); var actual = args[0]; try { Assert.Equal(expected, actual); } catch (EqualException ex) { throw new GenericArgumentException($"Expected type '{expected}' but found '{actual}'.", ex); } }
/// <inheritdoc /> public CallResultData ResolveResult(ICall callInfo) { var returnValue = this.ResolveReturnValue(callInfo); var returnMaybe = returnValue is OmitSpecimen?Maybe.Nothing <object>() : Maybe.Just(returnValue); //Resolve ref/out parameter values. var argumentValues = new List <CallResultData.ArgumentValue>(); var parameterInfos = callInfo.GetMethodInfo().GetParameters(); for (var i = 0; i < parameterInfos.Length; i++) { var parameterInfo = parameterInfos[i]; if (!parameterInfo.ParameterType.IsByRef) { continue; } // Unwrap parameter type, because it is Type& for ref/out methods. var value = this.SpecimenContext.Resolve(parameterInfo.ParameterType.GetElementType()); if (value is OmitSpecimen) { continue; } argumentValues.Add(new CallResultData.ArgumentValue(i, value)); } return(new CallResultData(returnMaybe, argumentValues)); }
public RouteAction Handle(ICall call) { // We want the proxies to respond to the base object methods (e.g. Equals, GetHashCode) if (call.GetMethodInfo().GetBaseDefinition().DeclaringType == typeof(object)) return RouteAction.Return(call.CallOriginalMethod()); return RouteAction.Continue(); }
public static string DiagName(this ICall call, DiagContextInternal ctx) { var substituteId = call.Target().SubstituteId(ctx); var callArgs = call.FormatArgs(ctx); var signature = call.GetMethodInfo().DiagName(); return($"<[{substituteId}].{callArgs} Signature: {signature}>"); }
/// <summary> /// Checks the last method invocation on the mock; /// if Add was invoked the unexpected match is set up; /// if GetOrAdd or GetOrAddAsync was invoked the unexpected match is set up and the addItemFactory result will be /// returned; /// otherwise the default value for the specified type will be returned. /// </summary> /// <param name="call"></param> /// <returns> /// if GetOrAdd or GetOrAddAsync was invoked the unexpected match is set up and the addItemFactory result will be /// returned; /// otherwise the default value for the specified type will be returned if the last method invocation has a return /// type. /// </returns> public RouteAction Handle(ICall call) { Logger.LogDebug("NoSetUpHandler invoked"); var methodInfo = call.GetMethodInfo(); var args = call.GetArguments(); if (methodInfo.Name.Equals("Add")) { //We have everything we need to set up a match, so let's do it var key = args[0].ToString(); var value = args[1]; ProjectReflectionShortcuts.SetUpCacheEntryMethod(value.GetType()).Invoke(null, new[] { _mockedCachingService, key, value }); return(RouteAction.Return(null)); } if (methodInfo.Name.Equals("GetOrAdd")) { //We have everything we need to set up a match, so let's do it var key = args[0].ToString(); var value = args[1].GetType().GetMethod("Invoke").Invoke(args[1], new object[] { new CacheEntryFake(key) }); ProjectReflectionShortcuts.SetUpCacheEntryMethod(value.GetType()).Invoke(null, new[] { _mockedCachingService, key, value }); return(RouteAction.Return(value)); } if (methodInfo.Name.Equals("GetOrAddAsync")) { //We have everything we need to set up a match, so let's do it var key = args[0].ToString(); var task = args[1].GetType().GetMethod("Invoke").Invoke(args[1], new object[] { new CacheEntryFake(key) }); var taskResult = task.GetType().GetProperty("Result").GetValue(task); ProjectReflectionShortcuts.SetUpCacheEntryMethod(taskResult.GetType()).Invoke(null, new[] { _mockedCachingService, key, taskResult }); return(RouteAction.Return(task)); } //void method if (methodInfo.ReturnType == typeof(void)) { return(RouteAction.Return(null)); } //Return default values if (methodInfo.ReturnType.IsGenericType && methodInfo.ReturnType.GetGenericTypeDefinition() == typeof(Task <>)) { var genericArgument = methodInfo.ReturnType.GetGenericArguments().Single(); var defaultValue = genericArgument.GetDefaultValue(); return(RouteAction.Return(CoreReflectionShortcuts.TaskFromResultMethod(genericArgument).Invoke(null, new[] { defaultValue }))); } return(RouteAction.Return(methodInfo.ReturnType.GetDefaultValue())); }
public ICallSpecification CreateFrom(ICall call, MatchArgs matchArgs) { var methodInfo = call.GetMethodInfo(); var argumentSpecs = call.GetArgumentSpecifications(); var arguments = call.GetOriginalArguments(); var parameterInfos = call.GetParameterInfos(); var argumentSpecificationsForCall = _argumentSpecificationsFactory.Create(argumentSpecs, arguments, parameterInfos, matchArgs); return new CallSpecification(methodInfo, argumentSpecificationsForCall); }
private string Format(ICall call) { var methodInfo = call.GetMethodInfo(); var args = methodInfo.GetParameters() .Zip(call.GetArguments(), (p, a) => new ArgAndParamInfo(p, a)) .ToArray(); return(_callFormatter.Format(methodInfo, FormatArgs(args))); }
public ICallSpecification CreateFrom(ICall call, MatchArgs matchArgs) { var methodInfo = call.GetMethodInfo(); var argumentSpecs = call.GetArgumentSpecifications(); var arguments = call.GetOriginalArguments(); var parameterInfos = call.GetParameterInfos(); var argumentSpecificationsForCall = _argumentSpecificationsFactory.Create(argumentSpecs, arguments, parameterInfos, methodInfo, matchArgs); return(new CallSpecification(methodInfo, argumentSpecificationsForCall)); }
public ICall CreateCallToPropertyGetterFromSetterCall(ICall callToSetter) { var propertyInfo = GetPropertyFromSetterCallOrNull(callToSetter); if (!PropertySetterExistsAndHasAGetMethod(propertyInfo)) { throw new InvalidOperationException("Could not find a GetMethod for \"" + callToSetter.GetMethodInfo() + "\""); } var getter = propertyInfo.GetGetMethod(); return new CallToPropertyGetter(getter, callToSetter.Target()); }
private static string DumpCallInfo(ICall cur) { var methodName = cur.GetMethodInfo().Name; var args = cur.GetArguments() .Select(a => a is string ?$"\"{a}\"" : a) .JoinWith(", "); return($"{methodName}({args})"); }
public ICall CreateCallToPropertyGetterFromSetterCall(ICall callToSetter) { var propertyInfo = GetPropertyFromSetterCallOrNull(callToSetter); if (!PropertySetterExistsAndHasAGetMethod(propertyInfo)) { throw new InvalidOperationException("Could not find a GetMethod for \"" + callToSetter.GetMethodInfo() + "\""); } var setterArgs = callToSetter.GetArguments(); var getter = propertyInfo.GetGetMethod(); var getterArgs = setterArgs.Take(setterArgs.Length - 1).ToArray(); return new Call(getter, getterArgs, callToSetter.Target(), callToSetter.GetArgumentSpecifications()); }
public bool IsSatisfiedBy(ICall call) { if (MethodInfo != call.GetMethodInfo()) return false; var arguments = call.GetArguments(); if (arguments.Length != ArgumentSpecifications.Count) return false; for (int i = 0; i < arguments.Length; i++) { var argumentMatchesSpecification = ArgumentSpecifications[i].IsSatisfiedBy(arguments[i]); if (!argumentMatchesSpecification) return false; } return true; }
private static ParameterInfo[] GetMethodParameters(ICall call) { // A workaround for the older versions of NSubstitute to retrieve the original delegate signature. // The related issue has been fixed in v4, so no tweaks are required there. // The workaround will be self disabled in v4+ due to the internal NSubstitute refactoring. if (call.Target().GetType() == DelegateCallType && DelegateTypeFieldInfo != null) { var delegateType = (Type)DelegateTypeFieldInfo.GetValue(call.Target()); return(delegateType.GetMethod("Invoke").GetParameters()); } return(call.GetMethodInfo().GetParameters()); }
static bool LogOneWarning(ICall call) { if (call.GetMethodInfo().Name != "Log") { return(false); } var args = call.GetArguments(); var logLevel = (LogLevel)args[0]; var exception = (Exception)args[3]; return(logLevel == LogLevel.Warning && exception.Message.Contains("null")); }
private static bool CanBeSubscribeUnsubscribeCall(ICall call) { var methodInfo = call.GetMethodInfo(); var methodName = methodInfo.Name; // It's safe to verify method prefix and signature as according to the ECMA-335 II.22.28: // 18. Any AddOn method for an event whose Name is xxx shall have the signature: void add_xxx (<DelegateType> handler) (§I.10.4) [CLS] // 19. Any RemoveOn method for an event whose Name is xxx shall have the signature: void remove_xxx(<DelegateType> handler) (§I.10.4) [CLS] return(methodInfo.IsSpecialName && methodInfo.ReturnType == typeof(void) && (methodName.StartsWith("add_", StringComparison.Ordinal) || methodName.StartsWith("remove_", StringComparison.Ordinal))); }
/// <summary> /// Assert that <paramref name="call"/> is a call to a method called <paramref name="expected"/> /// </summary> /// <param name="call">Call</param> /// <param name="expected">Expected method name</param> /// <exception cref="MethodNameException"></exception> internal static void AssertMethodName(ICall call, string expected) { var actual = call.GetMethodInfo().Name; try { Assert.Equal(expected, actual); } catch (EqualException ex) { throw new MethodNameException($"Expected call to '{expected}' but received call to '{actual}'.", ex); } }
public object Handle(ICall call) { var methodInfo = call.GetMethodInfo(); var eventInfo = methodInfo.DeclaringType.GetEvents().First( x => (x.GetAddMethod() == methodInfo) || (x.GetRemoveMethod() == methodInfo)); var handlers = _eventHandlerRegistry.GetHandlers(eventInfo.Name); var eventArguments = _getEventArguments(call); foreach (Delegate handler in handlers) { handler.DynamicInvoke(eventArguments); } return null; }
private bool ReturnsDynamic(ICall call) { var returnParameter = call.GetMethodInfo().ReturnParameter; if (returnParameter == null) { return(false); } var dynamicAttribute = typeof(System.Runtime.CompilerServices.DynamicAttribute); var customAttributes = returnParameter.GetCustomAttributes(dynamicAttribute, false); var isDynamic = customAttributes != null && customAttributes.Any(); return(isDynamic); }
private static bool CanBeSubscribeUnsubscribeCall(ICall call) { var methodInfo = call.GetMethodInfo(); // It's safe to verify method prefix and signature as according to the ECMA-335 II.22.28: // 18. Any AddOn method for an event whose Name is xxx shall have the signature: void add_xxx (<DelegateType> handler) (§I.10.4) [CLS] // 19. Any RemoveOn method for an event whose Name is xxx shall have the signature: void remove_xxx(<DelegateType> handler) (§I.10.4) [CLS] // Notice, even though it's correct to check the SpecialName flag, we don't do that deliberately. // The reason is that some compilers (e.g. F#) might not emit this attribute and our library // misbehaves in those cases. We use slightly slower, but robust check. return(methodInfo.ReturnType == typeof(void) && (methodInfo.Name.StartsWith("add_", StringComparison.Ordinal) || methodInfo.Name.StartsWith("remove_", StringComparison.Ordinal))); }
public object Route(ICall call) { Trace($"Route(call: {call.DiagName(_ctx)})"); Log($"[Received call] " + $"Substitute: {call.Target().SubstituteId(_ctx)} " + $"Call: {call.FormatArgs(_ctx)} " + $"Signature: {call.GetMethodInfo().DiagName()} " + $"Argument specifications: {call.GetArgumentSpecifications().Print(s => s.DiagName())}"); using (new LoggingScope()) { return(_impl.Route(call)); } }
private bool ReturnsDynamic(ICall call) { #if (NET4 || NET45) var returnParameter = call.GetMethodInfo().ReturnParameter; if (returnParameter == null) { return(false); } var dynamicAttribute = typeof(System.Runtime.CompilerServices.DynamicAttribute); var isDynamic = returnParameter.GetCustomAttributes(dynamicAttribute, false).Any(); return(isDynamic); #else return(false); #endif }
public bool IsSatisfiedBy(ICall call) { if (!AreComparable(GetMethodInfo(), call.GetMethodInfo())) { return(false); } if (HasDifferentNumberOfArguments(call)) { return(false); } if (NonMatchingArguments(call).Any()) { return(false); } return(true); }
public RouteAction Handle(ICall call) { var methodInfo = call.GetMethodInfo(); if (methodInfo.Name.Equals("Query") || methodInfo.Name.Equals("Set")) { throw new InvalidOperationException(string.Format(ExceptionMessages.CannotCreateDbSetTypeNotIncludedInModel, methodInfo.GetGenericArguments().Single().Name)); } if (methodInfo.ReturnType == typeof(void)) { return(RouteAction.Return(null)); } return(RouteAction.Return(methodInfo.ReturnType.GetDefaultValue())); }
private object ResolveReturnValue(ICall call) { if (call.GetReturnType() == typeof(void)) { return(null); } // If this is a call to a property getter, we resolve value via the 'PropertyInfo' request. var propertyInfo = call.GetMethodInfo().GetPropertyFromGetterCallOrNull(); if (propertyInfo != null) { return(this.SpecimenContext.Resolve(propertyInfo)); } return(this.SpecimenContext.Resolve(call.GetReturnType())); }
public RouteAction Handle(ICall call) { var property = call.GetMethodInfo().GetPropertyFromGetterCallOrNull(); if (property is null) { return(RouteAction.Continue()); } var service = _context.ResolveOptional(call.GetReturnType()); if (service is null) { return(RouteAction.Continue()); } return(RouteAction.Return(service)); }
public void MoveLogsSuccessfulMove() { // Arrange GroupFile file = new GroupFile(); ILogger <FileModifier> logger = Substitute.For <ILogger <FileModifier> >(); FileModifier uut = this.FileModifierWithDefaultMocks( logger: logger); // Act uut.Move(file, "destination"); // Assert ICall loggerCall = Assert.Single(logger.ReceivedCalls()); Assert.Equal("Log", loggerCall.GetMethodInfo().Name); Assert.Equal(LogLevel.Information, loggerCall.GetOriginalArguments().First()); }
private bool ReturnsDynamic(ICall call) { var returnParameter = call.GetMethodInfo().ReturnParameter; if (returnParameter == null) { return(false); } bool isDynamic; #if SYSTEM_REFLECTION_CUSTOMATTRIBUTES_IS_ARRAY isDynamic = returnParameter.GetCustomAttributes(DynamicAttributeType, inherit: false).Length != 0; #else var customAttributes = returnParameter.GetCustomAttributes(DynamicAttributeType, inherit: false); isDynamic = customAttributes != null && customAttributes.Any(); #endif return(isDynamic); }
public ICallSpecification CreateFrom(ICall call) { var result = new CallSpecification(call.GetMethodInfo()); var argumentSpecs = _context.DequeueAllArgumentSpecifications(); var arguments = call.GetArguments(); if (argumentSpecs.Count == 0) { AddArgumentSpecsToCallSpec(result, arguments.Select(x => (IArgumentSpecification) new ArgumentEqualsSpecification(x))); } else if (argumentSpecs.Count == arguments.Length) { AddArgumentSpecsToCallSpec(result, argumentSpecs); } else { throw new AmbiguousArgumentsException( "Cannot determine argument specifications to use. Please use specifications for all arguments."); } return result; }
public RouteAction Handle(ICall call) { var methodInfo = call.GetMethodInfo(); var eventInfo = methodInfo.DeclaringType.GetEvents().First( x => (x.GetAddMethod() == methodInfo) || (x.GetRemoveMethod() == methodInfo)); var handlers = _eventHandlerRegistry.GetHandlers(eventInfo.Name); var eventArguments = _getEventArguments(call); foreach (Delegate handler in handlers) { try { handler.DynamicInvoke(eventArguments); } catch (TargetInvocationException e) { PreserveStackTrace(e.InnerException); throw e.InnerException; } } return RouteAction.Continue(); }
public void MoveLogsFailedMove() { // Arrange GroupFile file = new GroupFile(); ILogger <FileModifier> logger = Substitute.For <ILogger <FileModifier> >(); IFileOperationsAbstraction ops = Substitute.For <IFileOperationsAbstraction>(); ops.When((x) => x.MoveFile(Arg.Any <string>(), Arg.Any <string>())) .Do((callInfo) => throw new Exception()); FileModifier uut = this.FileModifierWithDefaultMocks( logger: logger, fileOps: ops); // Act uut.Move(file, "destination"); // Assert ICall loggerCall = Assert.Single(logger.ReceivedCalls()); Assert.Equal("Log", loggerCall.GetMethodInfo().Name); Assert.Equal(LogLevel.Error, loggerCall.GetOriginalArguments().First()); }
private Predicate<EventInfo> IsEventUnsubscription(ICall call) { return x => call.GetMethodInfo() == x.GetRemoveMethod(); }
public void Should_set_required_call_properties() { Assert.That(_result.GetMethodInfo(), Is.EqualTo(_method)); Assert.That(_result.GetArguments(), Is.EqualTo(_args)); Assert.That(_result.Target(), Is.SameAs(_target)); }
public RouteAction Handle(ICall call) { var returnValue = _defaultForType.GetDefaultFor(call.GetMethodInfo().ReturnType); return RouteAction.Return(returnValue); }
private string Format(ICall call) { return _callFormatter.Format(call.GetMethodInfo(), FormatArgs(call.GetArguments())); }
public ICall CreateCallToPropertyGetterFromSetterCall(ICall callToSetter) { var propertyInfo = GetPropertyFromSetterCallOrNull(callToSetter); if (!PropertySetterExistsAndHasAGetMethod(propertyInfo)) { throw new InvalidOperationException("Could not find a GetMethod for \"" + callToSetter.GetMethodInfo() + "\""); } var setterArgs = callToSetter.GetArguments(); var getter = propertyInfo.GetGetMethod(); var getterArgs = setterArgs.Take(setterArgs.Length - 1).ToArray(); return(new Call(getter, getterArgs, callToSetter.Target(), callToSetter.GetArgumentSpecifications())); }
private PropertyInfo GetPropertyFromSetterCallOrNull(ICall call) { return(call.GetMethodInfo().GetPropertyFromSetterCallOrNull()); }
private PropertyInfo GetPropertyFromSetterCallOrNull(ICall call) { var methodInfo = call.GetMethodInfo(); var properties = methodInfo.DeclaringType.GetProperties(); return properties.FirstOrDefault(x => x.GetSetMethod() == methodInfo); }
private IEnumerable<EventInfo> GetEvents(ICall call, Func<ICall, Predicate<EventInfo>> createPredicate) { var predicate = createPredicate(call); return call.GetMethodInfo().DeclaringType.GetEvents().Where(x => predicate(x)); }
private Predicate<EventInfo> IsEventSubscription(ICall call) { return x => call.GetMethodInfo() == x.GetAddMethod(); }
private PropertyInfo GetPropertyFromSetterCallOrNull(ICall call) { return call.GetMethodInfo().GetPropertyFromSetterCallOrNull(); }
public string Format(ICall call, ICallSpecification withRespectToCallSpec) { return Format(call.GetMethodInfo(), call.GetArguments(), withRespectToCallSpec.NonMatchingArgumentIndicies(call)); }
public string Format(ICall call) { return CallFormatter.Format(call.GetMethodInfo(), FormatArguments(call.GetArguments())); }