Exemplo n.º 1
0
        public void When_matcher_is_asked_to_return_a_request_handler_that_is_set_up_that_handler_is_returned()
        {
            const string testResponse = "test-response";

            var routeHandlers = new Dictionary <RouteBase, Func <OwinRequest, object> >
            {
                {
                    new RegexRoute("foo/"), r =>
                    {
                        return(testResponse);
                    }
                }
            };

            var matcher = new RouteMatcher(routeHandlers);

            var request = OwinRequest.Create();

            request.Path = "foo/";

            Assert.That(matcher.HasMatch(request), Is.True);
            var handler = matcher.GetMatch(request);

            Assert.That(handler(request).ToString(), Is.EqualTo(testResponse));
        }
Exemplo n.º 2
0
        public void Test_paths()
        {
            var routeHandlers = new Dictionary<RouteBase, Func<OwinRequest, object>>
                                    {
                                        //the order they are added gives precedence currently and so most greedy should be added last.
                                        //flask adds a weighting for complexity and most complex are evaluated first. will revisit
                                        {new RegexRoute("/"), r => { return "default"; }},
                                        {new RegexRoute("/special"), r => { return "special"; }},
                                        {new RegexRoute("/<int:year>"), r => { return "date"; }},
                                        {new RegexRoute("/Talk:<path:name>"), r => { return "talk"; }},
                                        {new RegexRoute("/User:<username>"), r => { return "user"; }},
                                        {new RegexRoute("/User:<username>/<path:name>"), r => { return "userpage"; }},
                                        {new RegexRoute("/Files/<path:file>"), r => { return "files"; }},

                                        {new RegexRoute("/<path:name>/silly/<path:name2>/edit"), r => { return "editsillypage"; }},
                                        {new RegexRoute("/<path:name>/silly/<path:name2>"), r => { return "sillypage"; }},

                                        {new RegexRoute("/<path:name>/edit"), r => { return "editpage"; }},
                                        {new RegexRoute("/<path:name>"), r => { return "page"; }}
                                    };
            var matcher = new RouteMatcher(routeHandlers);

            AssertPathMatches(matcher, "/" , "default");
            AssertPathMatches(matcher, "/Special", "special");
            AssertPathMatches(matcher, "/2014", "date");
            AssertPathMatches(matcher, "/Some/Page", "page");
            AssertPathMatches(matcher, "/Some/Page/edit", "editpage");
            AssertPathMatches(matcher, "/Foo/silly/bar", "sillypage");
            AssertPathMatches(matcher, "/Foo/silly/bar/edit", "editsillypage");
            AssertPathMatches(matcher, "/Talk:Foo/Bar", "talk");
            AssertPathMatches(matcher, "/User:thomas", "user");
            AssertPathMatches(matcher, "/User:thomas/projects/werkzeug", "userpage");
            AssertPathMatches(matcher, "/Files/downloads/werkzeug/0.2.zip", "files");
        }
Exemplo n.º 3
0
        public void MatchedRoute_HasCorrectParameters(string route, string path, params string[] parameters)
        {
            if (parameters.Length % 2 != 0)
            {
                throw new InvalidOperationException("Parameters should be in name, value pairs.");
            }

            RouteMatcher.ClearCache();

            var parameterCount = parameters.Length / 2;

            Assert.IsTrue(RouteMatcher.TryParse(route, false, out var matcher));
            Assert.AreEqual(parameterCount, matcher.ParameterNames.Count);
            for (var i = 0; i < parameterCount; i++)
            {
                Assert.AreEqual(parameters[2 * i], matcher.ParameterNames[i]);
            }

            var match = matcher.Match(path);

            Assert.IsNotNull(match);
            var keys   = match.Keys.ToArray();
            var values = match.Values.ToArray();

            Assert.AreEqual(parameterCount, keys.Length);
            Assert.AreEqual(parameterCount, values.Length);
            for (var i = 0; i < parameterCount; i++)
            {
                Assert.AreEqual(parameters[2 * i], keys[i]);
                Assert.AreEqual(parameters[(2 * i) + 1], values[i]);
            }
        }
        public async Task Setup_MessagesExistInMessageStore_MessagesAreReceivedByClient()
        {
            var serializer   = new Serializer();
            var routeMatcher = new RouteMatcher();
            var dispatcher   = new DefaultDispatcher();
            var messageStore = new Mock <IMessageStore>();

            var client = new Mock <IClient>();

            client.Setup(c => c.ReachedMaxConcurrency).Returns(false);
            client.Setup(c => c.Enqueue(It.IsAny <SerializedPayload>())).Returns(new AsyncPayloadTicket());

            var sampleMessage = RandomGenerator.GetMessage("TEST");
            var topicMessage  = sampleMessage.ToTopicMessage(sampleMessage.Route);

            messageStore.Setup(ms => ms.GetAll()).Returns(new List <Guid> {
                sampleMessage.Id
            });
            messageStore.Setup(ms => ms.TryGetValue(sampleMessage.Id, out topicMessage)).Returns(true);

            var topic = new Topic(dispatcher,
                                  messageStore.Object,
                                  routeMatcher,
                                  serializer,
                                  NullLogger <Topic> .Instance
                                  );

            topic.Setup("TEST", "TEST");

            topic.ClientSubscribed(client.Object);

            await topic.ReadNextMessage();

            client.Verify(c => c.Enqueue(It.IsAny <SerializedPayload>()));
        }
Exemplo n.º 5
0
        public void Test_paths()
        {
            var routeHandlers = new Dictionary <RouteBase, Func <OwinRequest, object> >
            {
                //the order they are added gives precedence currently and so most greedy should be added last.
                //flask adds a weighting for complexity and most complex are evaluated first. will revisit
                { new RegexRoute("/"), r => { return("default"); } },
                { new RegexRoute("/special"), r => { return("special"); } },
                { new RegexRoute("/<int:year>"), r => { return("date"); } },
                { new RegexRoute("/Talk:<path:name>"), r => { return("talk"); } },
                { new RegexRoute("/User:<username>"), r => { return("user"); } },
                { new RegexRoute("/User:<username>/<path:name>"), r => { return("userpage"); } },
                { new RegexRoute("/Files/<path:file>"), r => { return("files"); } },

                { new RegexRoute("/<path:name>/silly/<path:name2>/edit"), r => { return("editsillypage"); } },
                { new RegexRoute("/<path:name>/silly/<path:name2>"), r => { return("sillypage"); } },

                { new RegexRoute("/<path:name>/edit"), r => { return("editpage"); } },
                { new RegexRoute("/<path:name>"), r => { return("page"); } }
            };
            var matcher = new RouteMatcher(routeHandlers);

            AssertPathMatches(matcher, "/", "default");
            AssertPathMatches(matcher, "/Special", "special");
            AssertPathMatches(matcher, "/2014", "date");
            AssertPathMatches(matcher, "/Some/Page", "page");
            AssertPathMatches(matcher, "/Some/Page/edit", "editpage");
            AssertPathMatches(matcher, "/Foo/silly/bar", "sillypage");
            AssertPathMatches(matcher, "/Foo/silly/bar/edit", "editsillypage");
            AssertPathMatches(matcher, "/Talk:Foo/Bar", "talk");
            AssertPathMatches(matcher, "/User:thomas", "user");
            AssertPathMatches(matcher, "/User:thomas/projects/werkzeug", "userpage");
            AssertPathMatches(matcher, "/Files/downloads/werkzeug/0.2.zip", "files");
        }
        public async Task OnMessage_SubscriptionIsAddedAfterTheMessage_ClientEnqueueIsCalled()
        {
            var messageStore = new InMemoryMessageStore();
            var serializer   = new Serializer();
            var routeMatcher = new RouteMatcher();
            var dispatcher   = new DefaultDispatcher();

            var mockClient = new Mock <IClient>();

            mockClient.Setup(c => c.ReachedMaxConcurrency).Returns(false);
            mockClient.Setup(c => c.Enqueue(It.IsAny <SerializedPayload>())).Returns(new AsyncPayloadTicket());

            var activeSessionId = Guid.NewGuid();

            mockClient.Setup(c => c.Id).Returns(activeSessionId);

            var topic = new Topic(dispatcher,
                                  messageStore,
                                  routeMatcher,
                                  serializer,
                                  NullLogger <Topic> .Instance
                                  );

            topic.Setup("TEST", "TEST");

            var sampleMessage = RandomGenerator.GetMessage("TEST");

            topic.OnMessage(sampleMessage);

            topic.ClientSubscribed(mockClient.Object);

            await topic.ReadNextMessage();

            mockClient.Verify(cs => cs.Enqueue(It.IsAny <SerializedPayload>()));
        }
Exemplo n.º 7
0
        public SingleItemRequest DecodeItemLink(string link)
        {
            try
            {
                var uri          = new Uri(link);
                var routeMatcher = new RouteMatcher();
                var values       = routeMatcher.Match(aliexpressItemLinkTemplate, uri.LocalPath);

                var singleItem = new SingleItemRequest()
                {
                    Source = "Aliexpress"
                };

                singleItem.Title = values.ContainsKey("itemTitle") ? values["itemTitle"].ToString() : String.Empty;
                singleItem.ID    = values.ContainsKey("itemid") ? values["itemid"].ToString() : String.Empty;
                singleItem.Link  = link;

                return(singleItem);
            }
            catch (Exception e)
            {
                return(new SingleItemRequest()
                {
                    Link = link
                });
            }
        }
Exemplo n.º 8
0
    private (string, string, string) GetRouteMatchedTagParser(SiteArticleDefinition definition, string routeToMatch)
    {
        if (definition is null)
        {
            Log.Debug("SiteDefinition is null. Falling back to adaptive parser.");
            return("adaptive-parser", "", "");
        }

        if (definition.RouteTemplates?.Length > 0)
        {
            var matcher = new RouteMatcher();
            foreach (var articleRoute in definition.RouteTemplates)
            {
                if (matcher.Match(articleRoute.Template, "/" + routeToMatch) != null)
                {
                    Log.Information("Matched route {routeName} on template {template}", articleRoute.Name, articleRoute.Template);
                    return(articleRoute.Parser, articleRoute.ArticleSelector, articleRoute.ParagraphSelector);
                }
            }

            // Might have forgotten to create a **catch-all template, fall back to adaptive parser
            Log.Warning("Missing **catch-all template. Falling back to adaptive parser.");
            return("adaptive-parser", "", "");
        }
        else
        {
            // No route templates defined, fall back to older style definition or adpative parser
            Log.Debug("No route templates defined. falling back to {@parser}", definition);
            return(string.IsNullOrEmpty(definition.Parser) ? "adaptive-parser" : definition.Parser,
                   definition.ArticleSelector, definition.ParagraphSelector);
        }
    }
Exemplo n.º 9
0
        public void CanMatchImageTransformRequest(string httpMethod, Uri requestUri, TransformType expectedTransformType, Coordinates expectedCoordinates)
        {
            var matched = RouteMatcher.TryMatchImageTransformRequest(httpMethod, requestUri, out var transformType, out var coords);

            Assert.IsTrue(matched, "Request didn't match");
            Assert.AreEqual(expectedTransformType, transformType);
            Assert.AreEqual(expectedTransformType, transformType);
        }
Exemplo n.º 10
0
        [TestCase("/abc/{id}/{name?}/")]  // No segment of a base route can be optional.
        public void InvalidBaseRoute_IsNotValid(string route)
        {
            RouteMatcher.ClearCache();

            Assert.IsFalse(Route.IsValid(route, true));
            Assert.Throws <FormatException>(() => RouteMatcher.Parse(route, true));
            Assert.IsFalse(RouteMatcher.TryParse(route, true, out _));
        }
Exemplo n.º 11
0
        [TestCase("/abc/{width}/{height}/")] // 2 parameters, different segments.
        public void ValidBaseRoute_IsValid(string route)
        {
            RouteMatcher.ClearCache();

            Assert.IsTrue(Route.IsValid(route, true));
            Assert.DoesNotThrow(() => RouteMatcher.Parse(route, true));
            Assert.IsTrue(RouteMatcher.TryParse(route, true, out _));
        }
Exemplo n.º 12
0
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (context.Request.Method != HttpMethods.Get)
            {
                await next(context);

                return;
            }

            var routeMatcher = new RouteMatcher();

            if (!routeMatcher.TryMatch(CreateRouteTemplate(), context.Request.Path, out RouteValueDictionary routeValues))
            {
                await next(context);

                return;
            }

            var schema = routeValues["schema"].ToString();

            var xsdFileInformationByUriSegment = _xsdFileInformationProvider.XsdFileInformationByUriSegment(schema);

            if (xsdFileInformationByUriSegment == default)
            {
                context.Response.StatusCode = StatusCodes.Status404NotFound;
                return;
            }

            string assemblyName          = xsdFileInformationByUriSegment.AssemblyName;
            string fullQualifiedFileName = $"Artifacts/Schemas/{routeValues["file"]}.xsd";

            var embeddedFileProvider = _embeddedFileProviderByAssemblyName.GetOrAdd(
                assemblyName, key => new EmbeddedFileProvider(_assembliesProvider.Get(assemblyName)));

            context.Response.ContentType = "application/xml";
            context.Response.StatusCode  = StatusCodes.Status200OK;

            await context.Response.SendFileAsync(embeddedFileProvider.GetFileInfo(fullQualifiedFileName));

            string CreateRouteTemplate()
            {
                string template = $"metadata/";

                if (_apiSettings.GetApiMode() == ApiMode.YearSpecific)
                {
                    template += RouteConstants.SchoolYearFromRoute;
                }

                if (_apiSettings.GetApiMode() == ApiMode.InstanceYearSpecific)
                {
                    template += RouteConstants.InstanceIdFromRoute;
                    template += RouteConstants.SchoolYearFromRoute;
                }

                return(template + "xsd/{schema}/{file}.xsd");
            }
        }
Exemplo n.º 13
0
        private static void AssertPathMatches(RouteMatcher matcher, string path, string expectedResponse)
        {
            var request = OwinRequest.Create();

            request.Path = path;

            var match = matcher.GetMatch(request);

            Assert.That(match(request).ToString(), Is.EqualTo(expectedResponse), "invalid match for path:" + path);
        }
Exemplo n.º 14
0
        public void When_matcher_is_asked_to_match_a_path_that_is_not_set_up_no_match_is_found()
        {
            var routeHandlers = new Dictionary<RouteBase, Func<OwinRequest, object>>();

            var matcher = new RouteMatcher(routeHandlers);

            var request = OwinRequest.Create();
            request.Path = "foo/";

            Assert.That(matcher.HasMatch(request), Is.False);
        }
Exemplo n.º 15
0
        [TestCase("/abc/{id}/{date?}", "id", "date")]          // 2 parameters, different segments, 1 optional.
        public void RouteParameters_HaveCorrectNames(string route, params string[] parameterNames)
        {
            RouteMatcher.ClearCache();

            Assert.IsTrue(RouteMatcher.TryParse(route, false, out var matcher));
            Assert.AreEqual(parameterNames.Length, matcher !.ParameterNames.Count);
            for (var i = 0; i < parameterNames.Length; i++)
            {
                Assert.AreEqual(parameterNames[i], matcher.ParameterNames[i]);
            }
        }
Exemplo n.º 16
0
        public void MatchedBaseRoute_HasCorrectSubPath(string route, string path, string subPath)
        {
            RouteMatcher.ClearCache();

            Assert.IsTrue(RouteMatcher.TryParse(route, true, out var matcher));

            var match = matcher !.Match(path);

            Assert.IsNotNull(match);
            Assert.AreEqual(subPath, match.SubPath);
        }
Exemplo n.º 17
0
        public ApiAuthorizedMiddleware(RequestDelegate next, IOptions <ApiAuthorizedOptions> options, IRouter router)
        {
            this._next    = next;
            this._options = options.Value;

            _routeMatcher = new RouteMatcher();



            this._router = router;
        }
Exemplo n.º 18
0
        public void When_matcher_is_asked_to_match_a_path_that_is_not_set_up_no_match_is_found()
        {
            var routeHandlers = new Dictionary <RouteBase, Func <OwinRequest, object> >();

            var matcher = new RouteMatcher(routeHandlers);

            var request = OwinRequest.Create();

            request.Path = "foo/";

            Assert.That(matcher.HasMatch(request), Is.False);
        }
Exemplo n.º 19
0
        public void When_matcher_is_asked_to_match_a_path_that_is_set_up_match_is_found()
        {
            var routeHandlers = new Dictionary<RouteBase, Func<OwinRequest, object>>();
            routeHandlers.Add(new RegexRoute("foo/"), r => { return "test-response"; });

            var matcher = new RouteMatcher(routeHandlers);

            var request = OwinRequest.Create();
            request.Path = "foo/";

            Assert.That(matcher.HasMatch(request), Is.True);
        }
        public void TestMatches()
        {
            using (var routeMatcher = new RouteMatcher())
            {
                object actual      = string.Empty;
                string expected    = "zh-CN";
                var    template    = "api/Locale/Get/{locale}";
                var    routeValues = routeMatcher.Matches(template, $"/api/Locale/Get/{expected}");
                routeValues.TryGetValue("locale", out actual);

                Assert.AreEqual(expected, actual);
            }
        }
Exemplo n.º 21
0
        public void When_matcher_is_asked_to_return_a_request_handler_that_is_not_set_up_null_is_returned()
        {
            var matcher = new RouteMatcher(new Dictionary <RouteBase, Func <OwinRequest, object> > {
            });

            var request = OwinRequest.Create();

            request.Path = "foo/";

            Assert.That(matcher.HasMatch(request), Is.False);
            var handler = matcher.GetMatch(request);

            Assert.That(handler, Is.Null);
        }
Exemplo n.º 22
0
        private static int IndexOfRouteParameter(RouteMatcher matcher, string name)
        {
            var names = matcher.ParameterNames;

            for (var i = 0; i < names.Count; i++)
            {
                if (names[i] == name)
                {
                    return(i);
                }
            }

            return(-1);
        }
Exemplo n.º 23
0
        public void When_matcher_is_asked_to_match_a_path_that_is_set_up_match_is_found()
        {
            var routeHandlers = new Dictionary <RouteBase, Func <OwinRequest, object> >();

            routeHandlers.Add(new RegexRoute("foo/"), r => { return("test-response"); });

            var matcher = new RouteMatcher(routeHandlers);

            var request = OwinRequest.Create();

            request.Path = "foo/";

            Assert.That(matcher.HasMatch(request), Is.True);
        }
Exemplo n.º 24
0
        public bool Match(HttpContext context)
        {
            var routeMatcher = new RouteMatcher();

            var result = routeMatcher.Match(route, context.Request.Path);

            if (result != null)
            {
                context.Features[typeof(IRouteValuesFeature)] = new RouteValuesFeature(result);

                return(true);
            }

            return(false);
        }
Exemplo n.º 25
0
        public void When_matcher_is_asked_to_match_a_request_that_has_many_paths_set_up_the_most_specific_route_which_matches_wins()
        {
            var routeHandlers = new Dictionary <RouteBase, Func <OwinRequest, object> >
            {
                { new RegexRoute("foo/"), r => { return("test-response-default"); } },
                { new RegexRoute("foo/", "GET"), r => { return("test-response-get"); } },
                { new RegexRoute("foo/", "POST"), r => { return("test-response-post"); } }
            };

            var matcher = new RouteMatcher(routeHandlers);

            var request = OwinRequest.Create();

            request.Path   = "foo/";
            request.Method = "POST";

            Assert.That(matcher.HasMatch(request), Is.True);
            Assert.That(matcher.GetMatch(request)(request).ToString(), Is.EqualTo("test-response-post"));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Enables correlation/request ids for the API request/responses.
        /// </summary>
        /// <param name="naosOptions"></param>
        public static NaosApplicationContextOptions UseCommandEndpoints(this NaosApplicationContextOptions naosOptions)
        {
            EnsureArg.IsNotNull(naosOptions, nameof(naosOptions));

            var routeMatcher = new RouteMatcher();

            foreach (var registration in naosOptions.Context.Application.ApplicationServices.GetServices <CommandRequestRegistration>().Safe()
                     .Where(r => !r.Route.IsNullOrEmpty()))
            {
                naosOptions.Context.Application.UseMiddleware <CommandRequestMiddleware>(
                    Options.Create(new CommandRequestMiddlewareOptions
                {
                    Registration = registration,
                    RouteMatcher = routeMatcher
                }));
                naosOptions.Context.Messages.Add($"naos application builder: command requests added (route={registration.Route}, method={registration.RequestMethod}, type={registration.CommandType.PrettyName()})");
            }

            return(naosOptions);
        }
Exemplo n.º 27
0
        public void VariousPathMatches()
        {
            // arrange
            var sut = new RouteMatcher();

            // act/assert
            sut.Match("/api/customers", "/api/customers").ShouldNotBeNull();
            sut.Match("api/customers", "/api/customers").ShouldNotBeNull();
            sut.Match("/api/customers", "api/customers").ShouldNotBeNull();
            sut.Match("api/customers", "api/customers").ShouldNotBeNull();
            sut.Match("/api/customers", "/api/customers/1234567").ShouldBeNull();
            sut.Match("/api/customers/{id}", "/api/customers/1234567").ShouldNotBeNull();
            sut.Match("/api/customers/{id}", "/api/customers/1234567").ContainsKey("id").ShouldBeTrue();
            sut.Match("/api/customers/{id}", "/api/customers/1234567")["id"].ShouldBe("1234567");
            sut.Match("/api/customers/{id}", "/api/customers/1234567/orders").ShouldBeNull();
            sut.Match("/api/customers/{id}/orders", "/api/customers/1234567/orders").ShouldNotBeNull();
            sut.Match("/api/customers/{id}/orders/{orderId}", "/api/customers/1234567/orders/778899").ShouldNotBeNull();
            sut.Match("/api/customers/{id}/orders/{orderId}", "/api/customers/1234567/orders/778899")["orderId"].ShouldBe("778899");
            sut.Match("/api/customers/{id:int}", "/api/customers/1234567")["id"].ShouldBe(1234567);
        }
Exemplo n.º 28
0
        public void OnMessage_AnyCondition_MessageIsAddedToMessageStore()
        {
            var messageStore = new Mock <IMessageStore>();
            var serializer   = new Serializer();
            var routeMatcher = new RouteMatcher();
            var dispatcher   = new DefaultDispatcher();

            var topic = new Topic(dispatcher,
                                  messageStore.Object,
                                  routeMatcher,
                                  serializer,
                                  NullLogger <Topic> .Instance
                                  );

            topic.Setup("TEST", "TEST");

            var sampleMessage = RandomGenerator.GetMessage("TEST");

            topic.OnMessage(sampleMessage);

            messageStore.Verify(ms => ms.Add(It.IsAny <TopicMessage>()));
        }
Exemplo n.º 29
0
        public void VariousPathAndQueryStringMatches()
        {
            // arrange
            var sut = new RouteMatcher();

            // act/assert
            var query     = new QueryCollection(Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery("?sorted=date"));
            var noopQuery = new QueryCollection(Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery("?sorted=noop"));

            sut.Match("/api/customers/{id}/orders?sorted=date", "/api/customers/1234567/orders", query).ShouldNotBeNull();
            sut.Match("/api/customers/{id}/orders?sorted=date", "api/customers/1234567/orders", query).ShouldNotBeNull();
            sut.Match("api/customers/{id}/orders?sorted=date", "/api/customers/1234567/orders", query).ShouldNotBeNull();
            sut.Match("api/customers/{id}/orders?sorted=date", "api/customers/1234567/orders", query).ShouldNotBeNull();
            sut.Match("/api/customers/{id}/orders?sorted=date", "/api/customers/1234567/orders?sorted=date", query).ShouldNotBeNull();
            sut.Match("/api/customers/{id}/orders?sorted=date", "/api/customers/1234567/orders").ShouldBeNull();
            sut.Match("/api/customers/{id}/orders?sorted=date", "/api/customers/1234567/orders", noopQuery).ShouldBeNull();
            sut.Match("/api/customers/{id}/orders?sorted=date", "/api/customers/1234567/orders", query).ContainsKey("id").ShouldBeTrue();
            sut.Match("/api/customers/{id}/orders?sorted=date", "/api/customers/1234567/orders", query)["id"].ShouldBe("1234567");
            //sut.Match("/api/customers/{id}/orders?orderId={orderId}", "/api/customers/1234567/orders?orderId=778899", query).ContainsKey("orderId").ShouldBeTrue();
            //sut.Match("/api/customers/{id}/orders?orderId={orderId}", "/api/customers/1234567/orders?orderId=778899", query)["orderId"].ShouldBe("778899");
            //sut.Match("/api/customers/{id}/orders/{orderId}", "/api/customers/1234567/orders/778899")["orderId"].ShouldBe(778899);
        }
Exemplo n.º 30
0
        public void OnAck_AnyCondition_MessageIsDeleted()
        {
            var serializer   = new Serializer();
            var routeMatcher = new RouteMatcher();
            var dispatcher   = new DefaultDispatcher();
            var messageStore = new Mock <IMessageStore>();

            var topic = new Topic(dispatcher,
                                  messageStore.Object,
                                  routeMatcher,
                                  serializer,
                                  NullLogger <Topic> .Instance
                                  );

            topic.Setup("TEST", "TEST");

            var sampleMessage = RandomGenerator.GetMessage("TEST");

            topic.OnMessage(sampleMessage);

            topic.OnStatusChanged(sampleMessage.Id, true);
            messageStore.Verify(ms => ms.Delete(sampleMessage.Id));
        }
Exemplo n.º 31
0
        public async Task OnNack_AnyCondition_RequeueMessage()
        {
            var serializer   = new Serializer();
            var routeMatcher = new RouteMatcher();
            var dispatcher   = new DefaultDispatcher();
            var messageStore = new InMemoryMessageStore();

            var client = new Mock <IClient>();

            client.Setup(c => c.ReachedMaxConcurrency).Returns(false);
            client.Setup(c => c.Enqueue(It.IsAny <SerializedPayload>())).Returns(new AsyncPayloadTicket());

            var topic = new Topic(dispatcher,
                                  messageStore,
                                  routeMatcher,
                                  serializer,
                                  NullLogger <Topic> .Instance
                                  );

            topic.Setup("TEST", "TEST");

            topic.ClientSubscribed(client.Object);

            var sampleMessage = RandomGenerator.GetMessage("TEST");

            topic.OnMessage(sampleMessage);

            await topic.ReadNextMessage();

            client.Verify(ms => ms.Enqueue(It.IsAny <SerializedPayload>()));

            topic.OnStatusChanged(sampleMessage.Id, false);

            await topic.ReadNextMessage();

            client.Verify(ms => ms.Enqueue(It.IsAny <SerializedPayload>()));
        }
Exemplo n.º 32
0
        private static void AssertPathMatches(RouteMatcher matcher, string path, string expectedResponse)
        {
            var request = OwinRequest.Create();
            request.Path = path;

            var match = matcher.GetMatch(request);
            Assert.That(match(request).ToString(), Is.EqualTo(expectedResponse), "invalid match for path:" + path);
        }
Exemplo n.º 33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WebModuleBase"/> class.
 /// </summary>
 /// <param name="baseRoute">The base route served by this module.</param>
 /// <exception cref="ArgumentNullException"><paramref name="baseRoute"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentException"><paramref name="baseRoute"/> is not a valid base route.</exception>
 /// <seealso cref="IWebModule.BaseRoute"/>
 /// <seealso cref="Validate.Route"/>
 protected WebModuleBase(string baseRoute)
 {
     BaseRoute     = Validate.Route(nameof(baseRoute), baseRoute, true);
     _routeMatcher = RouteMatcher.Parse(baseRoute, true);
     LogSource     = GetType().Name;
 }
Exemplo n.º 34
0
        public void When_matcher_is_asked_to_return_a_request_handler_that_is_not_set_up_null_is_returned()
        {
            var matcher = new RouteMatcher(new Dictionary<RouteBase, Func<OwinRequest, object>> { });

            var request = OwinRequest.Create();
            request.Path = "foo/";

            Assert.That(matcher.HasMatch(request), Is.False);
            var handler = matcher.GetMatch(request);
            Assert.That(handler, Is.Null);
        }
Exemplo n.º 35
0
        public void When_matcher_is_asked_to_return_a_request_handler_that_is_set_up_that_handler_is_returned()
        {
            const string testResponse = "test-response";

            var routeHandlers = new Dictionary<RouteBase, Func<OwinRequest, object>>
                                    {
                                        {
                                            new RegexRoute("foo/"), r =>
                                                        {
                                                            return testResponse;
                                                        }
                                        }
                                    };

            var matcher = new RouteMatcher(routeHandlers);

            var request = OwinRequest.Create();
            request.Path = "foo/";

            Assert.That(matcher.HasMatch(request), Is.True);
            var handler = matcher.GetMatch(request);
            Assert.That(handler(request).ToString(), Is.EqualTo(testResponse));
        }
Exemplo n.º 36
0
        public void When_matcher_is_asked_to_match_a_request_that_has_many_paths_set_up_the_most_specific_route_which_matches_wins()
        {
            var routeHandlers = new Dictionary<RouteBase, Func<OwinRequest, object>>
                                    {
                                        {new RegexRoute("foo/"), r => { return "test-response-default"; }},
                                        {new RegexRoute("foo/", "GET"), r => { return "test-response-get"; }},
                                        {new RegexRoute("foo/", "POST"), r => { return "test-response-post"; }}
                                    };

            var matcher = new RouteMatcher(routeHandlers);

            var request = OwinRequest.Create();
            request.Path = "foo/";
            request.Method = "POST";

            Assert.That(matcher.HasMatch(request), Is.True);
            Assert.That(matcher.GetMatch(request)(request).ToString(), Is.EqualTo("test-response-post"));
        }
Exemplo n.º 37
0
        private OpenApiMetadataRequest CreateOpenApiMetadataRequest(string path)
        {
            // need to build the request model manually as binding does not exist in the middleware pipeline.
            // this is less effort that rewriting the open api metadata cache.
            var openApiMetadataRequest = new OpenApiMetadataRequest();

            var matcher = new RouteMatcher();

            foreach (var routeInformation in _routeInformations)
            {
                string routeTemplate = routeInformation.GetRouteInformation()
                                       .Template;

                if (matcher.TryMatch(routeTemplate, path, out RouteValueDictionary values))
                {
                    if (values.ContainsKey("document"))
                    {
                        // the route for resources/descriptors is the same format as the schema endpoint.
                        // we need to validate that it is a schema instead.
                        string documentName = values["document"]
                                              .ToString();

                        if (_schemaNameMaps.Value.Any(x => x.UriSegment.EqualsIgnoreCase(documentName)))
                        {
                            openApiMetadataRequest.SchemaName = documentName;
                        }

                        if (documentName.EqualsIgnoreCase("resources") || documentName.EqualsIgnoreCase("descriptors"))
                        {
                            openApiMetadataRequest.ResourceType = documentName;
                        }
                    }

                    if (values.ContainsKey("schoolYearFromRoute"))
                    {
                        string schoolYear = values["schoolYearFromRoute"]
                                            .ToString();

                        if (int.TryParse(schoolYear, out int schoolYearFromRoute))
                        {
                            openApiMetadataRequest.SchoolYearFromRoute = schoolYearFromRoute;
                        }
                    }

                    if (values.ContainsKey("instanceIdFromRoute"))
                    {
                        var instance   = values["instanceIdFromRoute"];
                        var instanceId = instance as string;

                        if (!string.IsNullOrEmpty(instanceId))
                        {
                            openApiMetadataRequest.InstanceIdFromRoute = instanceId;
                        }
                    }

                    if (values.ContainsKey("organizationCode"))
                    {
                        openApiMetadataRequest.SchemaName = values["organizationCode"]
                                                            .ToString();
                    }

                    if (values.ContainsKey("compositeCategoryName"))
                    {
                        openApiMetadataRequest.CompositeCategoryName = values["compositeCategoryName"]
                                                                       .ToString();
                    }

                    if (values.ContainsKey("profileName"))
                    {
                        openApiMetadataRequest.ProfileName = values["profileName"]
                                                             .ToString();
                    }

                    if (values.ContainsKey("other"))
                    {
                        openApiMetadataRequest.OtherName = values["other"]
                                                           .ToString();
                    }
                }
            }

            return(openApiMetadataRequest);
        }