private ObjectMethodExecutorCompiledFastClosure(MethodInfo methodInfo, TypeInfo targetTypeInfo, object[] parameterDefaultValues)
        {
            if (methodInfo == null)
            {
                throw new ArgumentNullException(nameof(methodInfo));
            }

            MethodInfo       = methodInfo;
            MethodParameters = methodInfo.GetParameters();
            TargetTypeInfo   = targetTypeInfo;
            MethodReturnType = methodInfo.ReturnType;

            var isAwaitable = CoercedAwaitableInfo.IsTypeAwaitable(MethodReturnType, out var coercedAwaitableInfo);

            IsMethodAsync   = isAwaitable;
            AsyncResultType = isAwaitable ? coercedAwaitableInfo.AwaitableInfo.ResultType : null;

            // Upstream code may prefer to use the sync-executor even for async methods, because if it knows
            // that the result is a specific Task<T> where T is known, then it can directly cast to that type
            // and await it without the extra heap allocations involved in the _executorAsync code path.
            _executor = GetExecutor(methodInfo, targetTypeInfo);

            if (IsMethodAsync)
            {
                _executorAsync = GetExecutorAsync(methodInfo, targetTypeInfo, coercedAwaitableInfo);
            }

            _parameterDefaultValues = parameterDefaultValues;
        }
        internal MethodDispatcher(MethodInfo method)
        {
            Precondition.Require(method, () => Error.ArgumentNull("method"));

            _methodExecutor = CreateExecutorDelegate(method);
            _method         = method;
        }
Esempio n. 3
0
        async public Task execut_func_with_task_and_return_result_value_task()
        {
            Func <bool, Task <bool> > action = _ => Task.FromResult(true);
            var result = await MethodExecutor.CreateExecutor(action.Method).ExecuteAsync(action.Target, true);

            Assert.True((bool)result);
        }
        public void ShouldTakeScreenShotUsingCustomScreenShotMethod()
        {
            var mockSandBox = new Mock <ISandbox>();
            var method      = new Mock <MethodInfo>();

            method.Setup(info => info.DeclaringType).Returns(GetType());
            method.Setup(info => info.Name).Returns("ShouldTakeScreenShotUsingCustomScreenShotMethod");
            var parameterInfo = new Mock <ParameterInfo>();

            parameterInfo.Setup(info => info.ParameterType).Returns(typeof(string));
            method.Setup(info => info.GetParameters()).Returns(() => new[] { parameterInfo.Object });

            var result = new ExecutionResult {
                Success = false, ExceptionMessage = "Some Error", StackTrace = "StackTrace"
            };

            mockSandBox.Setup(sandbox => sandbox.ExecuteMethod(method.Object, "Bar")).Returns(result);

            byte[] bytes = { 0x20, 0x20 };
            mockSandBox.Setup(sandbox => sandbox.TryScreenCapture(out bytes)).Returns(true);

            var executionResult = new MethodExecutor(mockSandBox.Object).Execute(method.Object, "Bar");

            mockSandBox.VerifyAll();
            Assert.True(executionResult.Failed);
            Assert.True(executionResult.HasScreenShot);
            Assert.AreEqual(2, executionResult.ScreenShot.Length);
        }
Esempio n. 5
0
        public void execute_static_method_with_args_and_return()
        {
            var method   = typeof(MethodExecutorTests).GetMethod(nameof(Invoke), (BindingFlags)(0 - 1));
            var isAssert = (bool)MethodExecutor.CreateExecutor(method).Execute(target: null, parameters: true);

            Assert.True(isAssert);
        }
Esempio n. 6
0
 private void ApplyEvent(IAggregateEvent evt)
 {
     if (!MethodExecutor.ExecuteMethodForSingleParam(this, evt))
     {
         throw new MissingMethodException(string.Format("Aggregate {0} does not support a method that can be called with {1}", this, evt));
     }
 }
Esempio n. 7
0
        public void ShouldNotTakeScreenShotWhenDisabled()
        {
            var mockSandBox = new Mock <ISandbox>();
            var gaugeMethod = new GaugeMethod {
                Name = "ShouldNotTakeScreenShotWhenDisabled", ParameterCount = 1
            };

            var result = new ExecutionResult
            {
                Success          = false,
                ExceptionMessage = "Some Error",
                StackTrace       = "StackTrace"
            };

            mockSandBox.Setup(sandbox => sandbox.ExecuteMethod(gaugeMethod, It.IsAny <string[]>())).Returns(result);

            var screenshotEnabled = Utils.TryReadEnvValue("SCREENSHOT_ON_FAILURE");

            Environment.SetEnvironmentVariable("SCREENSHOT_ON_FAILURE", "false");

            var executionResult = new MethodExecutor(mockSandBox.Object).Execute(gaugeMethod, "Bar", "String");

            mockSandBox.VerifyAll();
            Assert.False(executionResult.ScreenShot == null);
            Environment.SetEnvironmentVariable("SCREENSHOT_ON_FAILURE", screenshotEnabled);
        }
        public void ShouldNotTakeScreenShotWhenDisabled()
        {
            var mockSandBox = new Mock <ISandbox>();
            var method      = new Mock <MethodInfo>();

            method.Setup(info => info.DeclaringType).Returns(GetType());
            method.Setup(info => info.Name).Returns("ShouldNotTakeScreenShotWhenDisabled");
            var parameterInfo = new Mock <ParameterInfo>();

            parameterInfo.Setup(info => info.ParameterType).Returns(typeof(string));
            method.Setup(info => info.GetParameters()).Returns(() => new[] { parameterInfo.Object });

            var result = new ExecutionResult {
                Success = false, ExceptionMessage = "Some Error", StackTrace = "StackTrace"
            };

            mockSandBox.Setup(sandbox => sandbox.ExecuteMethod(method.Object, "Bar")).Returns(result);

            var screenshotEnabled = Utils.TryReadEnvValue("SCREENSHOT_ENABLED");

            Environment.SetEnvironmentVariable("SCREENSHOT_ENABLED", "false");

            var executionResult = new MethodExecutor(mockSandBox.Object).Execute(method.Object, "Bar");

            mockSandBox.VerifyAll();
            Assert.False(executionResult.HasScreenShot);
            Environment.SetEnvironmentVariable("SCREENSHOT_ENABLED", screenshotEnabled);
        }
Esempio n. 9
0
        public async Task MethodParameterTypeMismatchThrows()
        {
            var methodExecutor = new MethodExecutor <object>(
                new ReadOnlyDictionary <long, ObjectDescriptor>(
                    new Dictionary <long, ObjectDescriptor>()
            {
                { 1, ObjectDescriptor.Create().WithMethods(new List <MethodDescriptor>()
                    {
                        MethodDescriptor.Create().WithId(2).WithParameterCount(1).WithParameters(new List <MethodParameterDescriptor>
                        {
                            new MethodParameterDescriptor(typeof(string), false)
                        }).Get()
                    }).WithId(1).Get() }
            }), context => { context.ObjectValue = context.NativeValue; });

            var result = await methodExecutor.Execute(new MethodExecution <object>()
            {
                ObjectId   = 1,
                MethodId   = 2,
                Parameters = new object[] { 1 }
            });

            Assert.Equal("Parameter mismatch.", result.Error);
            Assert.False(result.Success);
        }
        internal MethodDispatcher(MethodInfo method)
        {
            Precondition.Require(method, () => Error.ArgumentNull("method"));

            _methodExecutor = CreateExecutorDelegate(method);
            _method = method;
        }
Esempio n. 11
0
        public async Task AsyncMethodExceptionPassedAlong()
        {
            var methodExecutor = new MethodExecutor <object>(
                new ReadOnlyDictionary <long, ObjectDescriptor>(
                    new Dictionary <long, ObjectDescriptor>()
            {
                { 1, ObjectDescriptor.Create().WithMethods(new List <MethodDescriptor>()
                    {
                        MethodDescriptor.Create()
                        .WithId(2)
                        .WithParameterCount(1)
                        .WithParameters(new List <MethodParameterDescriptor>
                        {
                            new MethodParameterDescriptor(typeof(string), false)
                        })
                        .WithExecute((o, a) => Task.FromException(new NotSupportedException("Error")))
                        .Get()
                    }).WithId(1).Get() }
            }), context => { });

            const string Value  = "expected";
            var          result = await methodExecutor.Execute(new MethodExecution <object>()
            {
                ObjectId   = 1,
                MethodId   = 2,
                Parameters = new object[] { Value }
            });

            Assert.Equal("Error", result.Error);
            Assert.False(result.Success);
        }
Esempio n. 12
0
        public async Task MethodCallExceptionPassedAlong()
        {
            var method = typeof(SimpleClassWithExceptions).GetMethod("ThrowException");

            var methodExecutor = new MethodExecutor <object>(
                new ReadOnlyDictionary <long, ObjectDescriptor>(
                    new Dictionary <long, ObjectDescriptor>
            {
                { 1, ObjectDescriptor.Create()
                  .WithObject(new SimpleClassWithExceptions())
                  .WithMethods(new List <MethodDescriptor>
                    {
                        MethodDescriptor.Create()
                        .WithId(2)
                        .WithParameterCount(0)
                        .WithParameters(new List <MethodParameterDescriptor>
                        {
                        })
                        .WithExecute((o, a) => method.Invoke(o, a))
                        .Get()
                    }).WithId(1).Get() }
            }), context => { });

            var result = await methodExecutor.Execute(new MethodExecution <object>
            {
                ObjectId   = 1,
                MethodId   = 2,
                Parameters = new object[] { }
            });

            Assert.Equal("Error", result.Error);
            Assert.False(result.Success);
        }
Esempio n. 13
0
        public void ShouldExecuteHooksAndNotTakeScreenshotOnFailureWhenDisabled()
        {
            var mockSandBox   = new Mock <ISandbox>();
            var hooksStrategy = new HooksStrategy();
            var result        = new ExecutionResult
            {
                Success          = false,
                ExceptionMessage = "Some Error",
                StackTrace       = "StackTrace"
            };

            mockSandBox.Setup(sandbox =>
                              sandbox.ExecuteHooks("hooks", hooksStrategy, new List <string>(), It.IsAny <Gauge.CSharp.Lib.ExecutionContext>())
                              ).Returns(result).Verifiable();

            var screenshotEnabled = Utils.TryReadEnvValue("SCREENSHOT_ON_FAILURE");

            Environment.SetEnvironmentVariable("SCREENSHOT_ON_FAILURE", "false");

            var protoExecutionResult =
                new MethodExecutor(mockSandBox.Object).ExecuteHooks("hooks", hooksStrategy, new List <string>(), new Gauge.CSharp.Lib.ExecutionContext());

            mockSandBox.VerifyAll();
            Assert.False(protoExecutionResult.ScreenShot == null);
            Environment.SetEnvironmentVariable("SCREENSHOT_ON_FAILURE", screenshotEnabled);
        }
Esempio n. 14
0
        public void ShouldTakeScreenShotUsingCustomScreenShotMethod()
        {
            var mockSandBox = new Mock <ISandbox>();
            var gaugeMethod = new GaugeMethod
            {
                Name           = "ShouldTakeScreenShotUsingCustomScreenShotMethod",
                ParameterCount = 1
            };

            var result = new ExecutionResult
            {
                Success          = false,
                ExceptionMessage = "Some Error",
                StackTrace       = "StackTrace"
            };

            mockSandBox.Setup(sandbox => sandbox.ExecuteMethod(gaugeMethod, It.IsAny <string[]>())).Returns(result);

            byte[] bytes = { 0x20, 0x20 };
            mockSandBox.Setup(sandbox => sandbox.TryScreenCapture(out bytes)).Returns(true);

            var executionResult = new MethodExecutor(mockSandBox.Object).Execute(gaugeMethod, "Bar", "String");

            mockSandBox.VerifyAll();
            Assert.True(executionResult.Failed);
            Assert.True(executionResult.ScreenShot != null);
            Assert.AreEqual(2, executionResult.ScreenShot.Length);
        }
Esempio n. 15
0
        public void execute_method_with_args_and_return()
        {
            var isAssert             = false;
            Func <bool, bool> action = _ => _;

            isAssert = (bool)MethodExecutor.CreateExecutor(action.Method).Execute(action.Target, true);
            Assert.True(isAssert);
        }
Esempio n. 16
0
        public void execute_method_without_args_with_return()
        {
            var         isAssert = false;
            Func <bool> action   = () => true;

            isAssert = (bool)MethodExecutor.CreateExecutor(action.Method).Execute(action.Target);
            Assert.True(isAssert);
        }
Esempio n. 17
0
        public void execute_method_without_args_and_return()
        {
            var    isAssert = false;
            Action action   = () => isAssert = true;

            MethodExecutor.CreateExecutor(action.Method).Execute(action.Target);
            Assert.True(isAssert);
        }
        public void WhenExecutingAMethod_ThenTheMethodIsCalled()
        {
            var obj = new ExecutableObject();

            MethodExecutor.ExecuteMethod(obj, 123);

            Assert.AreEqual(123, obj.TheValue);
        }
Esempio n. 19
0
        async public Task execut_action_with_task_and_return_null_value_task()
        {
            var isAssert             = false;
            Func <bool, Task> action = _ => { isAssert = true; return(Task.CompletedTask); };
            await MethodExecutor.CreateExecutor(action.Method).ExecuteAsync(action.Target, true);

            Assert.True(isAssert);
        }
Esempio n. 20
0
        public void execute_method_without_return_with_args()
        {
            var           isAssert = false;
            Action <bool> action   = _ => isAssert = _;

            MethodExecutor.CreateExecutor(action.Method).Execute(action.Target, true);
            Assert.True(isAssert);
        }
Esempio n. 21
0
        protected override ProtoExecutionResult.Builder ExecuteHooks(Message request)
        {
            var protoExecutionResultBuilder = base.ExecuteHooks(request);
            var allPendingMessages          = MethodExecutor.GetAllPendingMessages();

            protoExecutionResultBuilder.AddRangeMessage(allPendingMessages);
            return(protoExecutionResultBuilder);
        }
Esempio n. 22
0
        protected override ProtoExecutionResult ExecuteHooks(Message request)
        {
            var protoExecutionResult = base.ExecuteHooks(request);
            var allPendingMessages   = MethodExecutor.GetAllPendingMessages().Where(m => m != null);

            protoExecutionResult.Message.AddRange(allPendingMessages);
            return(protoExecutionResult);
        }
Esempio n. 23
0
        public IEnumerable <IDomainNotification> Handle(IDomainNotification evt)
        {
            this.updatedReadModels.Clear();

            MethodExecutor.ExecuteMethod(this, evt.Event);

            return(this.updatedReadModels);
        }
Esempio n. 24
0
        async public Task Rewrap_executor()
        {
            Func <bool, Task <bool> > action = _ => Task.FromResult(true);
            var exec = MethodExecutor.CreateExecutor(action.Method);
            var f    = (Func <object[], object>)((args) => exec.ExecuteAsync(action, args));
            var d    = DelegateExecutorHelper.Wrap <Func <bool, Task <bool> > >(exec, f);

            Assert.Equal(await action.Invoke(true), await d.Invoke(true));
        }
Esempio n. 25
0
        private void ExecuteConfigure()
        {
            var configureMethod = GetType().GetMethod("Configure", BindingFlags.NonPublic | BindingFlags.Instance);

            if (configureMethod != null)
            {
                MethodExecutor.Execute(DiContainer, this, configureMethod);
            }
        }
Esempio n. 26
0
        public void Load(string name, MethodInfo methodInfo)
        {
            MethodExecutor executor;

            if (methods.TryGetValue(name, out executor) && executor.PreparedMethod == methodInfo) return;

            executor = new MethodExecutor(methodInfo, instances.GetInstance(methodInfo), name);

            methods[name] = executor;
        }
        public void WhenExecutingAMethodOnASecondInstance_ThenTheMethodIsCalledOnTheSecondInstance()
        {
            var first  = new ExecutableObject();
            var second = new ExecutableObject();

            MethodExecutor.ExecuteMethod(first, 123);
            MethodExecutor.ExecuteMethod(second, 456);

            Assert.AreEqual(456, second.TheValue);
        }
Esempio n. 28
0
        public IEnumerable <IDataChangeEvent> Handle(INotificationEvent evt)
        {
            this.updatedReadModels.Clear();

            // now, for each domain event, call a method that takes the event and call it
            // todo: should we check for not handling the event or not.  read model builders probably don't need to
            // handle *everthing*
            MethodExecutor.ExecuteMethodForParams(this, evt.Event);

            return(this.updatedReadModels);
        }
        public void WhenExecutingAMethod1000Times_ThenTheSpeedIsOK()
        {
            var obj = new ExecutableObject();

            for (int i = 0; i < 1000; i++)
            {
                MethodExecutor.ExecuteMethod(obj, i);
            }

            Assert.True(true);
        }
Esempio n. 30
0
        public void test_executor_members()
        {
            var    isAssert = false;
            Action action   = () => isAssert = true;
            var    executor = MethodExecutor.CreateExecutor(action.Method);

            Assert.Equal(action.Method, executor.MethodInfo);
            Assert.Equal(action.Target.GetType().GetTypeInfo(), executor.TargetTypeInfo);
            Assert.True(action.Method.GetParameters().SequenceEqual(executor.MethodParameters));
            Assert.Equal(action.Method.ReturnType, executor.MethodReturnType);
        }
Esempio n. 31
0
        public IEnumerable <IDomainNotification> Process(IEnumerable <IAggregateEvent> events)
        {
            this.updatedReadModels.Clear();

            foreach (var evt in events)
            {
                MethodExecutor.ExecuteMethod(this, evt);
            }

            return(this.updatedReadModels);
        }
Esempio n. 32
0
        public async Task NonExistentObjectError()
        {
            var methodExecutor = new MethodExecutor <object>(
                new ReadOnlyDictionary <long, ObjectDescriptor>(new Dictionary <long, ObjectDescriptor>()),
                context => { });
            var result = await methodExecutor.Execute(new MethodExecution <object>()
            {
                ObjectId = 1
            });

            Assert.Equal("Invalid object.", result.Error);
            Assert.False(result.Success);
        }
 public MethodDispatcher(MethodInfo methodInfo)
 {
     _executor = GetExecutor(methodInfo);
     MethodInfo = methodInfo;
 }