Exemple #1
0
        public void Get_SimpleExpectationSetUpInHeader_HeaderParameterUsableInReturnStatement()
        {
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl      = "http://localhost:9101/";
            RestApi      restEndpoint = service.RestEndpoint(BaseUrl);

            IRouteTemplate <SomeTupleReturnValue> get = restEndpoint.AddGet <SomeTupleReturnValue>("/list/{id}");

            restEndpoint.Configure(get).With(Parameter.HeaderParameter <DateTime>("Today").Equals(dt => dt.Day == 3).And(Parameter.RouteParameter <int>("id").Any())).Returns <DateTime, int>((today, id) => new SomeTupleReturnValue {
                One = today, Two = id
            });

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            client.DefaultRequestHeaders.Add("Today", new DateTime(2000, 1, 3).ToString());

            Task <string> getAsync = client.GetStringAsync("list/1");

            string result = WaitVerifyNoExceptionsAndGetResult(getAsync);

            client.Dispose();
            service.Dispose();

            Assert.That(result, Is.EqualTo("{\"One\":\"2000-01-03T00:00:00\",\"Two\":1}"));
        }
Exemple #2
0
        private void WriteResponse(HttpListenerContext context)
        {
            context.Response.ContentEncoding = Encoding.UTF8;

            var requestWrapper = new RequestWrapper(context.Request);

            IRouteTemplate route = _routeTable.FirstOrDefault(definition => definition.Matches(requestWrapper));

            if (route != null)
            {
                object returnValue;
                if (!route.TryInvocation(requestWrapper, out returnValue))
                {
                    returnValue = null;
                }

                string serializeObject = JsonConvert.SerializeObject(returnValue);
                WriteStringToResponse(context.Response, serializeObject);
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                WriteStringToResponse(context.Response, "Not Found");
            }
        }
 public ParameterInRouteEqualsValue(IRouteTemplate routeOwningUrl, T expectedValue, string parameterName, ParameterLocation parameterLocation)
 {
     _routeOwningUrl    = routeOwningUrl;
     _expectedValue     = expectedValue;
     _parameterName     = parameterName;
     _parameterLocation = parameterLocation;
 }
Exemple #4
0
        public void Post_JustASimplePostWithNoBody_MessagesAreSent()
        {
            // Arrange
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl = "http://localhost:9101/";
            RestApi      api     = service.RestEndpoint(BaseUrl);

            IRouteTemplate post = api.AddPost("/order/{id}/shares");

            api.Configure(post).With(Parameter.RouteParameter <int>("id").Equals(1)).Send <IOrderWasPlaced>(msg => { msg.OrderNumber = 1; }, "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <HttpResponseMessage> postAsync = client.PostAsync("/order/1/shares", new StringContent(""));

            HttpResponseMessage message = WaitVerifyNoExceptionsAndGetResult(postAsync);

            client.Dispose();
            service.Dispose();

            do
            {
                Thread.Sleep(100);
            } while (MsmqHelpers.GetMessageCount("shippingservice") == 0);

            Assert.That(message.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(MsmqHelpers.GetMessageCount("shippingservice"), Is.EqualTo(1));
        }
Exemple #5
0
        public void Get_SimpleExpectationSetUpInHeaderHeaderVariableIsMissing_ReturnsDefaultValue()
        {
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl      = "http://localhost:9101/";
            RestApi      restEndpoint = service.RestEndpoint(BaseUrl);

            IRouteTemplate <bool> get = restEndpoint.AddGet <bool>("/list");

            restEndpoint.Configure(get).With(Parameter.HeaderParameter <DateTime>("Today").Equals(dt => dt.Day == 3)).Returns(true)
            .Send <IOrderWasPlaced>(msg => msg.OrderedProduct = "stockings", "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <string> getAsync = client.GetStringAsync("list");

            string result = WaitVerifyNoExceptionsAndGetResult(getAsync);

            client.Dispose();
            service.Dispose();

            Assert.That(result, Is.EqualTo("null"));
            Assert.That(MsmqHelpers.GetMessageCount("shippingservice"), Is.EqualTo(0), "shipping service recieved events");
        }
Exemple #6
0
        public void Post_PostWitBody_BodyIsPassedDownTheChain()
        {
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl = "http://localhost:9101/";
            RestApi      api     = service.RestEndpoint(BaseUrl);

            IRouteTemplate post = api.AddPost("/order");

            api.Configure(post).With(Body.AsDynamic().IsEqualTo(body => body.orderId == 1))
            .Send <IOrderWasPlaced, dynamic>((msg, body) =>
            {
                msg.OrderNumber = body.orderId;
            }, "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <HttpResponseMessage> postAsync = client.PostAsync("/order", new StringContent("{\"orderId\":\"1\"}", Encoding.UTF8, "application/json"));

            HttpResponseMessage message = WaitVerifyNoExceptionsAndGetResult(postAsync);

            MsmqHelpers.WaitForMessages("shippingservice");

            client.Dispose();
            service.Dispose();

            Assert.That(MsmqHelpers.PickMessageBody("shippingservice"), Is.StringContaining("1"));
            Assert.That(message.StatusCode, Is.EqualTo(HttpStatusCode.OK));
        }
        public ILambdaRouteInfo GetRouteInfo(IRouteTemplate template)
        {
            const string errMsg = "Could not find controller.";

            try
            {
                var resource   = string.IsNullOrWhiteSpace(template.Resource) ? "default" : template.Resource;
                var path       = template.Path;
                var parameters = template.PathParameters != null && template.PathParameters.Any()
                    ? template.PathParameters
                    : new Dictionary <string, string>();

                var verbs = template.Verbs != null && template.Verbs.Any()
                    ? template.Verbs
                    : new string[] { };

                var aggregate = RouteInfoStrategy.GetRouteInfo()
                                .Where(lambdaRoute => lambdaRoute.RouteAttribute != null)
                                .FirstOrDefault(
                    lambdaRouteInfo => IsMatch(lambdaRouteInfo, resource, path, parameters, verbs));

                if (aggregate != null)
                {
                    return(aggregate);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Caught exception: {ex.Message}");
                throw;
            }

            Console.WriteLine($"Error: {errMsg}");
            throw new Exception(errMsg);
        }
Exemple #8
0
        public void Post_PostWitBodyAndRouteParameters_BodyAndParametersFromRequestAreBound()
        {
            // Arrange
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl = "http://localhost:9101/";
            RestApi      api     = service.RestEndpoint(BaseUrl);

            IRouteTemplate post = api.AddPost("/order/{id}");

            api.Configure(post).With(Body.AsDynamic().IsEqualTo(body => body.orderId == 1).And(Parameter.RouteParameter <int>("id").Equals(2))).Returns(3);

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <HttpResponseMessage> postAsync = client.PostAsync("/order/2", new StringContent("{\"orderId\":\"1\"}", Encoding.UTF8, "application/json"));

            HttpResponseMessage message = WaitVerifyNoExceptionsAndGetResult(postAsync);

            Task <string> readAsStringAsync = message.Content.ReadAsStringAsync();

            readAsStringAsync.Wait();

            client.Dispose();
            service.Dispose();

            Assert.That(message.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(readAsStringAsync.Result, Is.EqualTo("3"));
        }
Exemple #9
0
        public void Post_DoesNotMatchSetup_DoesNotSendMessages()
        {
            // Arrange
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl = "http://localhost:9101/";
            RestApi      api     = service.RestEndpoint(BaseUrl);

            IRouteTemplate post = api.AddPost("/order/{id}/shares");

            api.Configure(post).With(Parameter.RouteParameter <int>("id").Equals(1)).Send <IOrderWasPlaced>(msg => { msg.OrderNumber = 1; }, "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <HttpResponseMessage> postAsync = client.PostAsync("/order/2/shares", new StringContent(""));

            WaitVerifyNoExceptions(postAsync);

            client.Dispose();
            service.Dispose();

            Thread.Sleep(2000);

            Assert.That(MsmqHelpers.GetMessageCount("shippingservice"), Is.EqualTo(0), "shipping service recieved events");
        }
Exemple #10
0
        public void Get_InvokingEndpointAndExpectationMet_MessageIsSentToQueue()
        {
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl      = "http://localhost:9101/";
            RestApi      restEndpoint = service.RestEndpoint(BaseUrl);

            IRouteTemplate <bool> get = restEndpoint.AddGet <bool>("/list");

            restEndpoint.Configure(get).With(Parameter.Any()).Returns(true)
            .Send <IOrderWasPlaced>(msg => msg.OrderedProduct = "stockings", "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <string> getAsync = client.GetStringAsync("list");

            string result = WaitVerifyNoExceptionsAndGetResult(getAsync);

            do
            {
                Thread.Sleep(100);
            } while (MsmqHelpers.GetMessageCount("shippingservice") == 0);

            client.Dispose();
            service.Dispose();

            Assert.That(result, Is.EqualTo("true"));
            Assert.That(MsmqHelpers.GetMessageCount("shippingservice"), Is.EqualTo(1), "shipping service did not recieve send");
        }
 public ParameterInRouteEqualsPredicate(IRouteTemplate routeOwningUrl, Func <T, bool> predicate, ParameterLocation parameterLocation, string parameterName)
 {
     _routeOwningUrl    = routeOwningUrl;
     _predicate         = predicate;
     _parameterLocation = parameterLocation;
     _parameterName     = parameterName;
 }
Exemple #12
0
        public void Get_SimpleExpectationSetUpInvokingEndpointAndExpectationMetInDifferentOrder_RestApiReturnsMatch()
        {
            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl      = "http://localhost:9101/";
            RestApi      restEndpoint = service.RestEndpoint(BaseUrl);

            IRouteTemplate <bool> get = restEndpoint.AddGet <bool>("/order/{id}?foo&bar");

            restEndpoint.Configure(get).With(Parameter.RouteParameter <int>("id").Equals(1)
                                             .And(Parameter.QueryParameter <string>("foo").Equals("howdy"))
                                             .And(Parameter.QueryParameter <string>("bar").Equals("partner"))).Returns(true);

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            Task <string> getAsync = client.GetStringAsync("/order/1?bar=partner&foo=howdy");

            string result = WaitVerifyNoExceptionsAndGetResult(getAsync);

            client.Dispose();
            service.Dispose();

            Assert.That(result, Is.EqualTo("true"));
        }
Exemple #13
0
 protected RouteBase(HttpMethod httpMethod, IRouteTemplate routeTemplate, bool enabled, string name, string description)
 {
     HttpMethod    = httpMethod;
     RouteTemplate = routeTemplate;
     Name          = name;
     Description   = description;
     Enabled       = enabled;
 }
Exemple #14
0
 public Route(Func <IHttpContext, Task> action, HttpMethod method, IRouteTemplate routeTemplate, bool enabled = true, string name = null, string description = null)
     : base(method, routeTemplate, enabled, name, description)
 {
     RouteAction = action;
     Name        = (string.IsNullOrWhiteSpace(name))
         ? action.Method.Name
         : name;
 }
Exemple #15
0
        public void Get_SimpleExpectationSetUpInHeader_HeaderParameterPassedDownTheInheritanceChain()
        {
            MsmqHelpers.Purge("shippingservice");

            ServiceStub service = Configure.Stub().NServiceBusSerializers().Restful().Create(@".\Private$\orderservice");

            const string BaseUrl      = "http://localhost:9101/";
            RestApi      restEndpoint = service.RestEndpoint(BaseUrl);

            IRouteTemplate <bool> get = restEndpoint.AddGet <bool>("/list");

            restEndpoint.Configure(get).With(Parameter.HeaderParameter <DateTime>("Today").Equals(dt => dt.Day == 3)).Returns(true)
            .Send <IOrderWasPlaced, DateTime>((msg, today) => msg.OrderedProduct = today.ToString(), "shippingservice");

            service.Start();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            client.DefaultRequestHeaders.Add("Today", new DateTime(2000, 1, 3).ToString());

            Task <string> getAsync = client.GetStringAsync("list");

            string result = WaitVerifyNoExceptionsAndGetResult(getAsync);

            client.Dispose();
            service.Dispose();

            do
            {
                Thread.Sleep(100);
            } while (MsmqHelpers.GetMessageCount("shippingservice") == 0);

            Assert.That(result, Is.EqualTo("true"));
            Assert.That(MsmqHelpers.PickMessageBody("shippingservice"), Is.StringContaining(new DateTime(2000, 1, 3).ToString()), "shipping service recieved events");
        }
 public CapturedRouteInvocation(RequestWrapper request, IRouteTemplate routeOwningUrl)
 {
     _request        = request;
     _routeOwningUrl = routeOwningUrl;
 }
 IInvocationMatcher IPostInvocationConfiguration.CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return new LogicalAndOfInvocations(_predicates.Select(predicate => predicate.AsPostConfiguration().CreateInvocationInspector(routeToConfigure)));
 }
 public IInvocationMatcher CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return this;
 }
 IInvocationMatcher IPostInvocationConfiguration.CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return _lastStep.AsPostConfiguration().CreateInvocationInspector(routeToConfigure);
 }
 public RouteInvocationTriggeringSequenceOfEvents(IRouteTemplate routeOwningUrl, IInvocationMatcher matcher, TriggeredMessageSequence sequence)
 {
     _routeOwningUrl = routeOwningUrl;
     _matcher = matcher;
     _sequence = sequence;
 }
 public IInvocationMatcher CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return(this);
 }
Exemple #22
0
 public InvokeGetConfiguration <R> Configure <R>(IRouteTemplate <R> route)
 {
     return(new InvokeGetConfiguration <R>(route, _service));
 }
 public RouteInvocationTriggeringSequenceOfEvents(IRouteTemplate routeOwningUrl, IInvocationMatcher matcher, TriggeredMessageSequence sequence)
 {
     _routeOwningUrl = routeOwningUrl;
     _matcher        = matcher;
     _sequence       = sequence;
 }
Exemple #24
0
 public InvokePostConfiguration(IRouteTemplate route, ServiceStub service)
 {
     _route   = route;
     _service = service;
 }
 IInvocationMatcher IPostInvocationConfiguration.CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return new LogicalOrOfInvocations(Left.AsPostConfiguration().CreateInvocationInspector(routeToConfigure), Right.AsPostConfiguration().CreateInvocationInspector(routeToConfigure));
 }
Exemple #26
0
 public InvokeGetConfiguration(IRouteTemplate <R> routeToConfigure, ServiceStub service)
 {
     _routeToConfigure = routeToConfigure;
     _service          = service;
 }
 public InvokePostConfiguration(IRouteTemplate route, ServiceStub service)
 {
     _route = route;
     _service = service;
 }
Exemple #28
0
 IInvocationMatcher IPostInvocationConfiguration.CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return(new LogicalAndOfInvocations(_predicates.Select(predicate => predicate.AsPostConfiguration().CreateInvocationInspector(routeToConfigure))));
 }
 public IInvocationMatcher CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return new BodyAsDynamicEqualsPredicate(_bodyEvaluator);
 }
Exemple #30
0
 IInvocationMatcher IPostInvocationConfiguration.CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return(new LogicalOrOfInvocations(Left.AsPostConfiguration().CreateInvocationInspector(routeToConfigure), Right.AsPostConfiguration().CreateInvocationInspector(routeToConfigure)));
 }
Exemple #31
0
 public ReturnFromGetInvocationConfiguration(IInvocationMatcher matcher, IRouteTemplate <R> route, ServiceStub service)
 {
     _matcher = matcher;
     _route   = route;
     _service = service;
 }
Exemple #32
0
 public InvokePostConfiguration Configure(IRouteTemplate route)
 {
     return(new InvokePostConfiguration(route, _service));
 }
 public IInvocationMatcher CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return(new ParameterInRouteEqualsValue <T>(routeToConfigure, _expectedValue, _parameterName, _parameterLocation));
 }
 public IInvocationMatcher CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return(new BodyAsDynamicEqualsPredicate(_bodyEvaluator));
 }
Exemple #35
0
 public IInvocationMatcher CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return(new ParameterInRouteEqualsPredicate <T>(routeToConfigure, _predicate, _parameterLocation, _parameterName));
 }
 IInvocationMatcher IPostInvocationConfiguration.CreateInvocationInspector(IRouteTemplate routeToConfigure)
 {
     return(_lastStep.AsPostConfiguration().CreateInvocationInspector(routeToConfigure));
 }