private async Task AssertSecureControllerAccess(ClaimsPrincipal user, string method, int expectedStatusCode, IAuthorizationPolicyStore policyStore = null) { var ctrl = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.SecureController)).GetControllers(null).Single(); if (policyStore != null) { var options = LiteApiOptions.Default; foreach (var policy in policyStore.GetPolicyNames()) { options.AuthorizationPolicyStore.SetPolicy(policy, policyStore.GetPolicy(policy)); } ctrl.Filters = null; // force refresh init with new policy store foreach (var action in ctrl.Actions) { action.Filters = null; } ctrl.Init(new LiteApiOptionsAccessor(options)); } var actionCtx = ctrl.Actions.Single(x => string.Compare(method, x.Name, StringComparison.OrdinalIgnoreCase) == 0); var invoker = new ActionInvoker(new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new ModelBinderCollection( new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever()), new JsonSerializer()); var httpCtx = new Fakes.FakeHttpContext(); httpCtx.User = user; httpCtx.Request.Path = "/api/secure/" + method; await invoker.Invoke(httpCtx, actionCtx); Assert.Equal(expectedStatusCode, httpCtx.Response.StatusCode); }
public async Task Should_not_run_binders_where_instance_does_not_apply() { var requestGraph = RequestGraph.CreateFor <IHandler>(x => x.Params(null, null)); var requestContext = requestGraph.GetRequestContext(); requestGraph.AddRequestBinder1(c => SetArguments(c, (a, p) => a[0] = "binder1")); requestGraph.AddRequestBinder2(c => SetArguments(c, (a, p) => a[1] += "binder2"), instanceAppliesTo: x => false); var invoker = new ActionInvoker(requestContext, requestGraph.RequestBinders, requestGraph.ResponseWriters, requestGraph.Configuration); var handler = Substitute.For <IHandler>(); await invoker.Invoke(handler); var expectedArguments = new object[] { "binder1", null }; await requestGraph.ActionMethod.Invoke(handler.Received(1), expectedArguments); requestGraph.RequestBinder1.AppliesToCalled.ShouldBeTrue(); requestGraph.RequestBinder1.AppliesToContext.RequestContext.ShouldEqual(requestContext); requestGraph.RequestBinder1.AppliesToContext.ActionArguments.ShouldEqual(expectedArguments); requestGraph.RequestBinder1.BindCalled.ShouldBeTrue(); requestGraph.RequestBinder1.BindContext.RequestContext.ShouldEqual(requestContext); requestGraph.RequestBinder1.BindContext.ActionArguments.ShouldEqual(expectedArguments); requestGraph.RequestBinder2.AppliesToCalled.ShouldBeTrue(); requestGraph.RequestBinder2.AppliesToContext.RequestContext.ShouldEqual(requestContext); requestGraph.RequestBinder2.AppliesToContext.ActionArguments.ShouldEqual(expectedArguments); requestGraph.RequestBinder2.BindCalled.ShouldBeFalse(); }
private async Task AssertCall(bool isGet, string path, string query, string body, string expectedResult) { var ctrlDiscoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.RestfulController)); var ctrls = ctrlDiscoverer.GetControllers(null); var pathResolver = new PathResolver(ctrls); var httpCtx = new Fakes.FakeHttpContext(); if (isGet) { (httpCtx.Request as Fakes.FakeHttpRequest).WithPath(path); } else { (httpCtx.Request as Fakes.FakeHttpRequest).Method = "POST"; (httpCtx.Request as Fakes.FakeHttpRequest).WithPath(path); (httpCtx.Request as Fakes.FakeHttpRequest).WriteBody(body); } foreach (var q in query.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { var parts = q.Split(":".ToCharArray()); (httpCtx.Request as Fakes.FakeHttpRequest).AddQuery(parts[0], parts[1]); } var action = pathResolver.ResolveAction(httpCtx.Request); var actionInvoker = new ActionInvoker(new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object), new JsonSerializer()); await actionInvoker.Invoke(httpCtx, action); string result = httpCtx.Response.ReadBody(); Assert.Equal(expectedResult, result); }
public void InvokeFailsIfTheNameCannotBeFound() { var server = new Server("Test"); var invoker = new ActionInvoker(server); var result = invoker.Invoke("urn:ccnet:test:ghost", new InvokeArguments()); Assert.IsNotNull(result); Assert.AreEqual(RemoteResultCode.UnknownUrn, result.ResultCode); }
public void InvokeFailsIfTheArgumentsAreMissing() { var testItem = new TestItem("Baby"); var server = new Server("Test", testItem); var invoker = new ActionInvoker(server); var result = invoker.Invoke("urn:ccnet:test:baby", null); Assert.IsNotNull(result); Assert.AreEqual(RemoteResultCode.MissingArguments, result.ResultCode); }
public void InvokeFailsIfTheActionCannotBeFound() { var testItem = new TestItem("Baby"); var server = new Server("Test", testItem); var invoker = new ActionInvoker(server); var result = invoker.Invoke("urn:ccnet:test:baby", new InvokeArguments { Action = "DoesNotExist" }); Assert.IsNotNull(result); Assert.AreEqual(RemoteResultCode.UnknownAction, result.ResultCode); }
protected override async Task RunAsync(CancellationToken cancellationToken) { await base.RunAsync(cancellationToken); await ActionInvoker.Invoke <IDefaultFtpScalerAction>(c => c.InvokeFtpScaler(), new ActorRequestContext($"{this.GetType().Name}", nameof(IDefaultFtpScalerAction), Guid.NewGuid().ToString(), FlowInstanceId.NewFlowInstanceId), new ExecutableOrchestrationOrder() { ActorId = _scalerActorId, ActorServiceUri = $"{FabricRuntime.GetActivationContext().ApplicationName}/{_scalerActorServiceName}" }, cancellationToken); }
public async Task ActionInvoker_MethodWithDefaultParam_CanBeInvoked() { IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.ParametersController)); var controller = discoverer.GetControllers(null).Single(); IActionInvoker invoker = new ActionInvoker( new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object) , new JsonSerializer()); var ctx = new Fakes.FakeHttpContext(); await invoker.Invoke(ctx, controller.Actions.First(x => x.Name == "toupper"), null); string body = ctx.Response.ReadBody(); Assert.Equal("\"ABC\"", body); ctx = new Fakes.FakeHttpContext(); (ctx.Request as Fakes.FakeHttpRequest).AddQuery("a", "zxc"); await invoker.Invoke(ctx, controller.Actions.First(x => x.Name == "toupper"), null); body = ctx.Response.ReadBody(); Assert.Equal("\"ZXC\"", body); }
private HttpResponse InvokeAndGetResponse() { var ctrl = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.RawController)) .GetControllers(null)[0]; var action = ctrl.Actions[0]; var serviceProvider = Fakes.FakeServiceProvider.GetServiceProvider(); var ctrlBuilder = new ControllerBuilder(serviceProvider); var actionInvoker = new ActionInvoker(ctrlBuilder, new ModelBinderCollection(new JsonSerializer(), serviceProvider, new Fakes.FakeDefaultLiteApiOptionsRetriever()), new JsonSerializer()); var httpCtx = new Fakes.FakeHttpContext(); actionInvoker.Invoke(httpCtx, action).Wait(); return(httpCtx.Response); }
private async Task AssertCanInvokeActionWithRouteParamOfType <T>(bool dateOnly = false) { Type type = typeof(T); object value = ""; if (typeof(T) == typeof(DateTimeOffset)) { value = "2017-10-28T09:51:17+07:00"; } if (typeof(T) != typeof(string) && typeof(T) != typeof(DateTimeOffset)) { value = Activator.CreateInstance(type); } if (typeof(T) == typeof(DateTime)) { value = default(DateTime).ToString("yyyy-MM-dd HH:mm:ss"); if (dateOnly) { value = default(DateTime).ToString("yyyy-MM-dd"); } } string actionName = "Action_" + type.Name; var discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.RouteSupportedParametersController)); var ctrl = discoverer.GetControllers(null).Single(); var action = ctrl.Actions.Single(x => x.Name == actionName.ToLower()); var serializer = new JsonSerializer(); var invoker = new ActionInvoker(new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new Services.ModelBinders.ModelBinderCollection( serializer, Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever()), new JsonSerializer()); var httpCtx = new Fakes.FakeHttpContext(); httpCtx.SetActionContext(action); httpCtx.Request.Path = "/api/RouteSupportedParameters/" + actionName + "/" + value; await invoker.Invoke(httpCtx, action); string jsonResult = httpCtx.Response.ReadBody(); object result = serializer.Deserialize(jsonResult, type); if (typeof(T) == typeof(DateTime)) { value = default(DateTime); } if (typeof(T) == typeof(DateTimeOffset)) { value = DateTimeOffset.Parse(value as string); } Assert.Equal(value, result); }
public async Task CanInvokeFileUpload() { var httpCtx = GetHttpCtx(); var discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.FileUploadController)); var ctrlCtx = discoverer.GetControllers(null).Single(); var builder = new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object); var invoker = new ActionInvoker(builder, new Services.ModelBinders.ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object), new JsonSerializer()); await invoker.Invoke(httpCtx, ctrlCtx.Actions.Single()); string response = httpCtx.Response.ReadBody(); Assert.Equal("2", response); }
private async Task AssertDownloadAction(string actionName) { var httpCtx = new Fakes.FakeHttpContext(); var discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.FileDownloadController)); var ctrlCtx = discoverer.GetControllers(null).Single(); var builder = new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object); var invoker = new ActionInvoker(builder, new Services.ModelBinders.ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object), new JsonSerializer()); var action = ctrlCtx.Actions.First(x => x.Name == actionName); await invoker.Invoke(httpCtx, action); string response = httpCtx.Response.ReadBody(); Assert.Equal(actionName, response); }
public void InvokeFailsIfInputIsIncorrectType() { var testItem = new TestItem("Baby"); var server = new Server("Test", testItem); var invoker = new ActionInvoker(server); var arguments = new InvokeArguments { Action = "TestAction", Data = "<Blank xmlns=\"urn:cruisecontrol:common\" />" }; var result = invoker.Invoke("urn:ccnet:test:baby", arguments); Assert.IsNotNull(result); Assert.AreEqual(RemoteResultCode.InvalidInput, result.ResultCode); }
public void InvokeFailsIfInputIsMissing() { var testItem = new TestItem("Baby"); var server = new Server("Test", testItem); var invoker = new ActionInvoker(server); var arguments = new InvokeArguments { Action = "TestAction", Data = string.Empty }; var result = invoker.Invoke("urn:ccnet:test:baby", arguments); Assert.IsNotNull(result); Assert.AreEqual(RemoteResultCode.InvalidInput, result.ResultCode); }
public async Task Action_WithRouteParametersWithCapitalLetters_CanBeInvoked() { var discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.RouteParamsController)); var ctrl = discoverer.GetControllers(null).Single(); var action = ctrl.Actions.Single(x => x.Name == "plus3"); var serializer = new JsonSerializer(); var invoker = new ActionInvoker(new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new Services.ModelBinders.ModelBinderCollection(serializer, new Moq.Mock <IServiceProvider>().Object), new JsonSerializer()); var httpCtx = new Fakes.FakeHttpContext(); httpCtx.Request.Path = "/api/v2/route/2/Plus3/4"; await invoker.Invoke(httpCtx, action); string jsonResult = httpCtx.Response.ReadBody(); object result = serializer.Deserialize(jsonResult, typeof(int)); Assert.Equal(6, result); }
private async Task AssertResponseHttpStatusCode(Contracts.Models.SupportedHttpMethods actionMethod, int expectedCode) { IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.DifferentHttpMethodsController)); var controller = discoverer.GetControllers(null).Single(); IActionInvoker invoker = new ActionInvoker( new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object) , new JsonSerializer() ); var ctx = new Fakes.FakeHttpContext(); ctx.Request.Method = actionMethod.ToString().ToLower(); (ctx.Request as Fakes.FakeHttpRequest).AddQuery("a", "2").AddQuery("b", "3").AddQuery("c", "4").AddQuery("d", "5"); await invoker.Invoke(ctx, controller.Actions.First(x => x.HttpMethod == actionMethod), null); Assert.Equal(expectedCode, ctx.Response.StatusCode); }
private async Task AssertResponseBody(Contracts.Models.SupportedHttpMethods actionMethod, string expectedResult) { IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.DifferentHttpMethodsController)); var controller = discoverer.GetControllers(null).Single(); IActionInvoker invoker = new ActionInvoker( new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new ModelBinderCollection(new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever()) , new JsonSerializer()); var ctx = new Fakes.FakeHttpContext(); (ctx.Request as Fakes.FakeHttpRequest).AddQuery("a", "2").AddQuery("b", "3").AddQuery("c", "4").AddQuery("d", "5"); await invoker.Invoke(ctx, controller.Actions.First(x => x.HttpMethod == actionMethod), null); string body = ctx.Response.ReadBody(); Assert.Equal(expectedResult, body); }
private async Task AssertNotSetResponseCode(ClaimsPrincipal user, int expectedStatusCode) { IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.SecureController2)); var controller = discoverer.GetControllers(null).Single(); IActionInvoker invoker = new ActionInvoker( new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object) , new JsonSerializer()); var httpCtx = new Fakes.FakeHttpContext(); httpCtx.User = user; var action = controller.Actions.First(x => x.Name == "get14"); await invoker.Invoke(httpCtx, action, null); int statusCode = httpCtx.Response.StatusCode; Assert.Equal(expectedStatusCode, statusCode); }
public void InvokeHandlesMethodsWithTheSameName() { var called = false; var item = new TroublesomeItem { Name = "ghost", DoSomethingAction = () => called = true }; var server = new Server("Test", item); var invoker = new ActionInvoker(server); var arguments = new InvokeArguments { Action = "DoSomething", Data = "<Blank xmlns=\"urn:cruisecontrol:common\" />" }; var result = invoker.Invoke("urn:ccnet:test:ghost", arguments); Assert.AreEqual(RemoteResultCode.Success, result.ResultCode); Assert.IsTrue(called); }
public async Task CanGetParameterFromService() { IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.ServiceProvidedParameterController)); var ctrl = discoverer.GetControllers(null).Single(); var action = ctrl.Actions.Single(); var mb = new ModelBinderCollection(new JsonSerializer(), GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever()); var httpCtx = new Fakes.FakeHttpContext(); (httpCtx.Request as Fakes.FakeHttpRequest).AddQuery("i", "1"); object[] parameters = mb.GetParameterValues(httpCtx.Request, action); Assert.Equal(2, parameters.Length); Assert.True(typeof(Controllers.IIncrementService).IsAssignableFrom(parameters[1].GetType())); ActionInvoker invoker = new ActionInvoker(new ControllerBuilder(GetServiceProvider()), mb, new JsonSerializer()); await invoker.Invoke(httpCtx, action); var result = httpCtx.Response.ReadBody(); Assert.Equal("2", result); }
public void InvokeInvokesMethod() { var testItem = new TestItem("Baby"); var server = new Server("Test", testItem); var invoker = new ActionInvoker(server); var arguments = new InvokeArguments { Action = "DoSomething", Data = "<Blank xmlns=\"urn:cruisecontrol:common\" />" }; var result = invoker.Invoke("urn:ccnet:test:baby", arguments); Assert.AreEqual(RemoteResultCode.Success, result.ResultCode); Assert.IsNotNull(result); Assert.IsNotNull(result.Data); var message = MessageSerialiser.Deserialise(result.Data); Assert.IsInstanceOf <Messages.Blank>(message); Assert.IsTrue(testItem.WasInvoked); }
public async Task Should_return_empty_response_if_no_writers_apply( [Values(null, HttpStatusCode.OK)] HttpStatusCode?statusCode) { var requestGraph = RequestGraph.CreateFor <IHandler>(x => x.Response()); if (statusCode.HasValue) { requestGraph.Configuration.DefaultStatusCode = statusCode.Value; } var invoker = new ActionInvoker(requestGraph.GetRequestContext(), requestGraph.RequestBinders, requestGraph.ResponseWriters, requestGraph.Configuration); var handler = Substitute.For <IHandler>(); handler.Response().ReturnsForAnyArgs(x => "response"); var response = await invoker.Invoke(handler); response.StatusCode.ShouldEqual(requestGraph.Configuration.DefaultStatusCode); }
private async Task AssertSecureControllerAccess(ClaimsPrincipal user, string method, int expectedStatusCode, IAuthorizationPolicyStore policyStore = null) { var ctrl = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.SecureController)).GetControllers(null).Single(); if (policyStore != null) { object[] methodCallProps = { policyStore }; typeof(ControllerContext) .GetTypeInfo() .GetProperty("AuthPolicyStore", BindingFlags.Instance | BindingFlags.NonPublic) .SetMethod.Invoke(ctrl, methodCallProps); } var actionCtx = ctrl.Actions.Single(x => string.Compare(method, x.Name, StringComparison.OrdinalIgnoreCase) == 0); var invoker = new ActionInvoker(new ControllerBuilder((new Moq.Mock <IServiceProvider>()).Object), new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object), new JsonSerializer()); var httpCtx = new Fakes.FakeHttpContext(); httpCtx.User = user; httpCtx.Request.Path = "/api/secure/" + method; await invoker.Invoke(httpCtx, actionCtx); Assert.Equal(expectedStatusCode, httpCtx.Response.StatusCode); }
public async Task Should_call_handler_with_first_writer_that_applies() { var requestGraph = RequestGraph.CreateFor <IHandler>(x => x.Response()); requestGraph.AddResponseWriter1(x => $"{x.Response}1".CreateTextResponse().ToTaskResult(), instanceAppliesTo: x => false); requestGraph.AddResponseWriter2(x => $"{x.Response}2".CreateTextResponse().ToTaskResult()); var invoker = new ActionInvoker(requestGraph.GetRequestContext(), requestGraph.RequestBinders, requestGraph.ResponseWriters, requestGraph.Configuration); var handler = Substitute.For <IHandler>(); handler.Response().ReturnsForAnyArgs(x => "response"); var response = await invoker.Invoke(handler); response.StatusCode.ShouldEqual(HttpStatusCode.OK); var responseText = await response.Content.ReadAsStringAsync(); responseText.ShouldEqual("response2"); }
public async Task Should_call_action(ActionMethod actionMethod) { var requestGraph = RequestGraph.CreateFor(actionMethod); var requestContext = requestGraph.GetRequestContext(); requestGraph.AddResponseWriter1(c => c.Response.ToString().CreateTextResponse().ToTaskResult()); requestGraph.AddRequestBinder1(c => SetArguments(c, (a, p) => a[p.Position] = $"value{p.Position}")); requestGraph.AddRequestBinder2(c => SetArguments(c, (a, p) => a[p.Position] += $"-{p.Position}")); var invoker = new ActionInvoker(requestContext, requestGraph.RequestBinders, requestGraph.ResponseWriters, requestGraph.Configuration); var handler = Substitute.For <IHandler>(); handler.Response().ReturnsForAnyArgs(x => "response"); handler.ResponseAsync().ReturnsForAnyArgs(x => "response".ToTaskResult()); handler.ParamsAndResponse(null).ReturnsForAnyArgs(x => "response"); handler.ParamsAndResponseAsync(null).ReturnsForAnyArgs(x => "response".ToTaskResult()); var response = await invoker.Invoke(handler); var expectedArguments = actionMethod.Method.Parameters.Select(p => $"value{p.Position}-{p.Position}").Cast <object>().ToArray(); await actionMethod.Invoke(handler.Received(1), expectedArguments); if (requestContext.Route.HasResponse) { response.StatusCode.ShouldEqual(HttpStatusCode.OK); var responseText = await response.Content.ReadAsStringAsync(); responseText.ShouldEqual("response"); } else { response.StatusCode.ShouldEqual(HttpStatusCode.NoContent); } }