private void RunTest( string template, RouteValueDictionary defaults, RouteValueDictionary ambientValues, RouteValueDictionary values, string expected, UrlEncoder encoder = null) { // Arrange var binderFactory = encoder == null ? BinderFactory : new RoutePatternBinderFactory(encoder, new DefaultObjectPoolProvider()); var binder = new TemplateBinder(binderFactory.Create(template, defaults ?? new RouteValueDictionary())); // Act & Assert var result = binder.GetValues(ambientValues, values); if (result == null) { if (expected == null) { return; } else { Assert.NotNull(result); } } var boundTemplate = binder.BindValues(result.AcceptedValues); if (expected == null) { Assert.Null(boundTemplate); } else { Assert.NotNull(boundTemplate); // We want to chop off the query string and compare that using an unordered comparison var expectedParts = new PathAndQuery(expected); var actualParts = new PathAndQuery(boundTemplate); Assert.Equal(expectedParts.Path, actualParts.Path); if (expectedParts.Parameters == null) { Assert.Null(actualParts.Parameters); } else { Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count); foreach (var kvp in expectedParts.Parameters) { string value; Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out value)); Assert.Equal(kvp.Value, value); } } } }
/// <summary> /// /// </summary> /// <param name="url">完整的url地址</param> public Url(string url) { if (url.IsNullOrWhiteSpace()) { throw new BusinessException("url is not empty"); } if (!url.StartsWith("http://") && !url.StartsWith("https://")) { throw new System.Exception("Please enter the correct url"); } var uri = new Uri(url); Host = uri.Host; Authority = uri.Authority; Scheme = uri.Scheme.ToLowers(); IsHttps = Scheme.Equals("https", StringComparison.CurrentCultureIgnoreCase); PathAndQuery = uri.PathAndQuery; Path = PathAndQuery.Split('?').GetSafeString(0).Trim(); RequestUrl = url.Split('?').GetSafeString(0).Trim(); if (url.Split('?').Length > 1) { UrlParameter = new UrlParameter(url.Split('?').GetSafeString(1).Trim()); } else { UrlParameter = new UrlParameter(); } }
public async Task UploadAllPathsAsync_TestFilesDirectory_FilesDetected() { var counter = 0; _fixture.ObjectFileParser = new ObjectFileParser(_fixture.Metrics, Options.Create(new ObjectFileParserOptions()), Substitute.For <ILogger <ObjectFileParser> >(), new FatBinaryReader()); _fixture.HttpMessageHandler = new TestMessageHandler((message, token) => { if (message.RequestUri !.PathAndQuery.EndsWith("upload")) { Interlocked.Increment(ref counter); } return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.Created))); }); _fixture.SymbolClient = new SymbolClient( Substitute.For <IHub>(), new SymbolClientOptions { BaseAddress = _fixture.ServiceUri, UserAgent = "UnitTest/0.0.0" }, Substitute.For <ILogger <SymbolClient> >(), new HttpClient(_fixture.HttpMessageHandler)); var sut = _fixture.GetSut(); await sut.UploadAllPathsAsync("friendly name", BatchType.IOS, new[] { "TestFiles" }, CancellationToken.None); // number of valid test files in TestFiles Assert.Equal(12, counter); }
private void RunTest( string pattern, DispatcherValueCollection defaults, DispatcherValueCollection ambientValues, DispatcherValueCollection values, string expected, UrlEncoder encoder = null) { // Arrange var binderFactory = encoder == null ? BinderFactory : new RoutePatternBinderFactory(encoder, new DefaultObjectPoolProvider()); var binder = binderFactory.Create(pattern, defaults ?? new DispatcherValueCollection()); // Act & Assert (var acceptedValues, var combinedValues) = binder.GetValues(ambientValues, values); if (acceptedValues == null) { if (expected == null) { return; } else { Assert.NotNull(acceptedValues); } } var result = binder.BindValues(acceptedValues); if (expected == null) { Assert.Null(result); } else { Assert.NotNull(result); // We want to chop off the query string and compare that using an unordered comparison var expectedParts = new PathAndQuery(expected); var actualParts = new PathAndQuery(result); Assert.Equal(expectedParts.Path, actualParts.Path); if (expectedParts.Parameters == null) { Assert.Null(actualParts.Parameters); } else { Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count); foreach (var kvp in expectedParts.Parameters) { Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out var value)); Assert.Equal(kvp.Value, value); } } } }
private static void RunTest( string template, IReadOnlyDictionary <string, object> defaults, IDictionary <string, object> ambientValues, IDictionary <string, object> values, string expected) { // Arrange var binder = new TemplateBinder(TemplateParser.Parse(template), defaults); // Act & Assert var result = binder.GetValues(ambientValues, values); if (result == null) { if (expected == null) { return; } else { Assert.NotNull(result); } } var boundTemplate = binder.BindValues(result.AcceptedValues); if (expected == null) { Assert.Null(boundTemplate); } else { Assert.NotNull(boundTemplate); // We want to chop off the query string and compare that using an unordered comparison var expectedParts = new PathAndQuery(expected); var actualParts = new PathAndQuery(boundTemplate); Assert.Equal(expectedParts.Path, actualParts.Path); if (expectedParts.Parameters == null) { Assert.Null(actualParts.Parameters); } else { Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count); foreach (var kvp in expectedParts.Parameters) { string value; Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out value)); Assert.Equal(kvp.Value, value); } } } }
public static string CreateActionKey(string url) { var absolutePath = PathAndQuery.CreateUri(url)?.AbsolutePath; absolutePath = absolutePath?.Trim().TrimStart('/'); var routeKey = $"routepath_{absolutePath}".Replace("/", "_").Replace("\\", "_"); return(CreateMD5Hash(routeKey)); }
public static string CreateActionKey(string?controllerPath, string?actionUrl) { var absolutePath = PathAndQuery.CreateUri(actionUrl)?.AbsolutePath; controllerPath = controllerPath?.Trim().TrimStart('/'); absolutePath = absolutePath?.Trim().TrimStart('/'); string?routeKey; if (string.IsNullOrWhiteSpace(controllerPath)) { routeKey = $"routepath_{absolutePath}".Replace("/", "_").Replace("\\", "_"); } else { routeKey = $"routepath_{controllerPath}_{absolutePath}".Replace("/", "_").Replace("\\", "_"); } return(CreateMD5Hash(routeKey)); }
public static IDictionary <string, object> GetParameters(this string url, string referrer = null) { var result = new Dictionary <string, object>(); try { var pathAndQuery = new PathAndQuery(); pathAndQuery.Parse(url); if (pathAndQuery.QueryParameters is not null && pathAndQuery.QueryParameters.Any()) { foreach (var item in pathAndQuery.QueryParameters) { if (!result.ContainsKey(item.Key)) { result.Add(item.Key, item.Value); } } } } catch { } if (!string.IsNullOrEmpty(referrer)) { if (result.ContainsKey(RequestConstants.Referrer)) { var guidStr = Guid.NewGuid().ToString(); result.Add($"{RequestConstants.Referrer}_{guidStr}", referrer); } else { result.Add(RequestConstants.Referrer, referrer); } } return(result); }
/// <summary> /// /// </summary> /// <param name="url">完整的url地址</param> /// <param name="isUseHttps">是否是https,默认自动识别</param> public Url(string url, bool?isUseHttps) { if (string.IsNullOrEmpty(url)) { throw new BusinessException("url is not empty", HttpStatus.Err.Id); } var uri = new Uri(url); Host = uri.Host; Scheme = uri.Scheme.ToLowers(); IsHttps = isUseHttps ?? Scheme.Equals("https", StringComparison.CurrentCultureIgnoreCase); PathAndQuery = uri.PathAndQuery; Path = PathAndQuery.Split('?')[0].Trim(); RequestUrl = url.Split('?')[0].Trim(); RequestUrl = FormatUrl(RequestUrl, IsHttps); if (url.Split('?').Length > 1) { UrlParameter = new UrlParameter(url.Split('?')[1].Trim()); } else { UrlParameter = new UrlParameter(); } }
private static void RunTest( string template, IReadOnlyDictionary<string, object> defaults, IDictionary<string, object> ambientValues, IDictionary<string, object> values, string expected) { // Arrange var binder = new TemplateBinder(TemplateParser.Parse(template), defaults); // Act & Assert var result = binder.GetValues(ambientValues, values); if (result == null) { if (expected == null) { return; } else { Assert.NotNull(result); } } var boundTemplate = binder.BindValues(result.AcceptedValues); if (expected == null) { Assert.Null(boundTemplate); } else { Assert.NotNull(boundTemplate); // We want to chop off the query string and compare that using an unordered comparison var expectedParts = new PathAndQuery(expected); var actualParts = new PathAndQuery(boundTemplate); Assert.Equal(expectedParts.Path, actualParts.Path); if (expectedParts.Parameters == null) { Assert.Null(actualParts.Parameters); } else { Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count); foreach (var kvp in expectedParts.Parameters) { string value; Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out value)); Assert.Equal(kvp.Value, value); } } } }
/// <summary> /// Validates a URL against this trust root. /// </summary> /// <param name="url">The URL to check.</param> /// <returns>Whether the given URL is within this trust root.</returns> internal bool Contains(Uri url) { if (url.Scheme != Scheme) { return(false); } if (url.Port != Port) { return(false); } if (!DomainWildcard) { if (url.Host != Host) { return(false); } } else { Debug.Assert(!string.IsNullOrEmpty(Host), "The host part of the Regex should evaluate to at least one char for successful parsed trust roots."); string[] host_parts = Host.Split('.'); string[] url_parts = url.Host.Split('.'); // If the domain containing the wildcard has more parts than the URL to match against, // it naturally can't be valid. // Unless *.example.com actually matches example.com too. if (host_parts.Length > url_parts.Length) { return(false); } // Compare last part first and move forward. // Maybe could be done by using EndsWith, but piecewies helps ensure that // *.my.com doesn't match ohmeohmy.com but can still match my.com. for (int i = 0; i < host_parts.Length; i++) { string hostPart = host_parts[host_parts.Length - 1 - i]; string urlPart = url_parts[url_parts.Length - 1 - i]; if (!string.Equals(hostPart, urlPart, StringComparison.OrdinalIgnoreCase)) { return(false); } } } // If path matches or is specified to root ... // (deliberately case sensitive to protect security on case sensitive systems) if (PathAndQuery.Equals(url.PathAndQuery, StringComparison.Ordinal) || PathAndQuery.Equals("/", StringComparison.Ordinal)) { return(true); } // If trust root has a longer path, the return URL must be invalid. if (PathAndQuery.Length > url.PathAndQuery.Length) { return(false); } // The following code assures that http://example.com/directory isn't below http://example.com/dir, // but makes sure http://example.com/dir/ectory is below http://example.com/dir int path_len = PathAndQuery.Length; string url_prefix = url.PathAndQuery.Substring(0, path_len); if (PathAndQuery != url_prefix) { return(false); } // If trust root includes a query string ... if (PathAndQuery.Contains("?")) { // ... make sure return URL begins with a new argument return(url.PathAndQuery[path_len] == '&'); } // Or make sure a query string is introduced or a path below trust root return(PathAndQuery.EndsWith("/", StringComparison.Ordinal) || url.PathAndQuery[path_len] == '?' || url.PathAndQuery[path_len] == '/'); }
public UriData(string uriString) : base(uriString) { _slicePath = PathAndQuery.Remove(0, 1); }
private static void RunTest( string template, RouteValueDictionary defaults, RouteValueDictionary ambientValues, RouteValueDictionary values, string expected, UrlEncoder encoder = null) { // Arrange encoder = encoder ?? new UrlTestEncoder(); var binder = new TemplateBinder( encoder, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy(encoder)), TemplateParser.Parse(template), defaults); // Act & Assert var result = binder.GetValues(ambientValues, values); if (result == null) { if (expected == null) { return; } else { Assert.NotNull(result); } } var boundTemplate = binder.BindValues(result.AcceptedValues); if (expected == null) { Assert.Null(boundTemplate); } else { Assert.NotNull(boundTemplate); // We want to chop off the query string and compare that using an unordered comparison var expectedParts = new PathAndQuery(expected); var actualParts = new PathAndQuery(boundTemplate); Assert.Equal(expectedParts.Path, actualParts.Path); if (expectedParts.Parameters == null) { Assert.Null(actualParts.Parameters); } else { Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count); foreach (var kvp in expectedParts.Parameters) { string value; Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out value)); Assert.Equal(kvp.Value, value); } } } }
public async Task PrintsWeatherConditionsAndSavesToStorage() { var args = "weather --city Vilnius,Athens,Tbilisi,Yerevan".Split(' '); using var application = new CommandLineApplication(args); var weatherData = new WeatherConditions[] { new("Vilnius", -10.5, 11, "Cloudy"), new("Athens", 18.7, 2, "Sunny"), new("Tbilisi", 15.1, 4, "Sunny"), new("Yerevan", 25.9, 25, "Rainy") }; var handler = application.FakeHttpClientHandler; var callToAuthorize = A.CallTo(() => handler.SendAsyncOverride( A <HttpRequestMessage> .That.Matches(message => message.Method == HttpMethod.Post && message.RequestUri !.ToString().EndsWith("api/authorize")), A <CancellationToken> ._)); callToAuthorize.ReturnsLazily((HttpRequestMessage _, CancellationToken _) => { // ReSharper disable once ConvertToLambdaExpression return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(@"{""bearer"":""1234567890""}") }); }); var callToGetWeatherData = A.CallTo(() => handler.SendAsyncOverride( A <HttpRequestMessage> .That.Matches(message => message.Method == HttpMethod.Get && message.Headers.Authorization !.Scheme == "bearer" && message.Headers.Authorization !.Parameter == "1234567890"), A <CancellationToken> ._)); callToGetWeatherData.ReturnsLazily((HttpRequestMessage m, CancellationToken _) => { var city = m.RequestUri !.PathAndQuery.Split('/').Last(); var data = weatherData.Single(w => w.City == city); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(data)) }); }); // Let's give enough time to complete the work of the background service. application.CancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(2)); var returnCode = await application.RunAsync(); Assert.Equal(0, returnCode); callToAuthorize.MustHaveHappened(4, Times.Exactly); callToGetWeatherData.MustHaveHappened(4, Times.Exactly); await AssertDatabase(weatherData); AssertConsoleOutput(application.StandardOutput); }