public void MatchPathToUriTemplates(string uri, string key) { // Arrange var table = new UriTemplateMatcher(); table.Add("root", "/"); table.Add("foo", "/foo/{bar}"); table.Add("kit", "/baz/kit"); table.Add("fooxy3", "/foo?x={x}&y={y}"); table.Add("baz", "/baz/{bar}"); table.Add("blob", "/baz/{bar}/blob"); table.Add("goo", "/{goo}/{bar}/blob"); table.Add("set", "/settings/{id}"); table.Add("state", "/games/{gametitle}/{gameid}/State/{stateid}"); table.Add("org", "/organization/{id}/settings/iteminsights"); table.Add("gamessetup", "/games/{gametitle}/Setup/{gamesid}"); // Act var result = table.Match(new Uri(uri, UriKind.RelativeOrAbsolute)); // Assert if (string.IsNullOrEmpty(key)) { Assert.Null(result); } else { Assert.Equal(key, result?.Key); } Assert.NotNull(table["goo"]); Assert.Null(table["goo1"]); }
public void ThrowArgumentNullExceptionForEmptyOrNullTemplateValueInAdd() { // Arrange var table = new UriTemplateMatcher(); // Act and Assert Assert.Throws <ArgumentNullException>(() => table.Add("set", "")); Assert.Throws <ArgumentNullException>(() => table.Add("set", null)); }
public void ThrowArgumentNullExceptionForEmptyOrNullKeyValueInAdd() { // Arrange var table = new UriTemplateMatcher(); // Act and Assert Assert.Throws <ArgumentNullException>(() => table.Add("", "/settings/{id}")); Assert.Throws <ArgumentNullException>(() => table.Add(null, "/settings/{id}")); }
public void ThrowArgumentNullExceptionForEmptyOrNullKeyIndexerInTemplateTable() { // Arrange var table = new UriTemplateMatcher(); // Act and Assert Assert.Throws <ArgumentNullException>(() => table[""]); Assert.Throws <ArgumentNullException>(() => table[null]); }
public void ThrowArgumentNullExceptionForNullUriValueInMatch() { // Arrange var table = new UriTemplateMatcher(); table.Add("goo", "/{goo}/{bar}/blob"); table.Add("set", "/settings/{id}"); table.Add("org", "/organization/{id}/settings/iteminsights"); // Act and Assert Assert.Throws <ArgumentNullException>(() => table.Match(null)); }
/// <summary> /// Populates the template table with the request urls and the scopes table with the permission scopes. /// </summary> private void SeedPermissionsTables() { _urlTemplateMatcher = new UriTemplateMatcher(); _scopesListTable = new Dictionary <int, object>(); HashSet <string> uniqueRequestUrlsTable = new HashSet <string>(); int count = 0; foreach (string permissionFilePath in _permissionsBlobNames) { string relativePermissionPath = FileServiceHelper.GetLocalizedFilePathSource(_permissionsContainerName, permissionFilePath); string jsonString = _fileUtility.ReadFromFile(relativePermissionPath).GetAwaiter().GetResult(); if (!string.IsNullOrEmpty(jsonString)) { JObject permissionsObject = JObject.Parse(jsonString); if (permissionsObject.Count < 1) { throw new InvalidOperationException($"The permissions data sources cannot be empty." + $"Check the source file or check whether the file path is properly set. File path: " + $"{relativePermissionPath}"); } JToken apiPermissions = permissionsObject.First.First; foreach (JProperty property in apiPermissions) { // Remove any '(...)' from the request url and set to lowercase for uniformity string requestUrl = Regex.Replace(property.Name.ToLower(), @"\(.*?\)", string.Empty); if (uniqueRequestUrlsTable.Add(requestUrl)) { count++; // Add the request url _urlTemplateMatcher.Add(count.ToString(), requestUrl); // Add the permission scopes _scopesListTable.Add(count, property.Value); } } _permissionsRefreshed = true; } } }
/// <summary> /// Create predicate function based on passed query parameters /// </summary> /// <param name="operationIds">Comma delimited list of operationIds or * for all operations.</param> /// <param name="tags">Comma delimited list of tags or a single regex.</param> /// <param name="url">Url path to match with Operation Ids.</param> /// <param name="graphVersion">Version of Microsoft Graph.</param> /// <param name="forceRefresh">Don't read from in-memory cache.</param> /// <returns>A predicate</returns> public static async Task <Func <OpenApiOperation, bool> > CreatePredicate(string operationIds, string tags, string url, OpenApiDocument source, bool forceRefresh = false) { if (url != null && (operationIds != null || tags != null)) { throw new InvalidOperationException("Cannot filter by url and either operationIds and tags at the same time."); } else if (operationIds != null && tags != null) { throw new InvalidOperationException("Cannot filter by operationIds and tags at the same time."); } Func <OpenApiOperation, bool> predicate; if (operationIds != null) { if (operationIds == "*") { predicate = (o) => true; // All operations } else { var operationIdsArray = operationIds.Split(','); predicate = (o) => operationIdsArray.Contains(o.OperationId); } } else if (tags != null) { var tagsArray = tags.Split(','); if (tagsArray.Length == 1) { var regex = new Regex(tagsArray[0]); predicate = (o) => o.Tags.Any(t => regex.IsMatch(t.Name)); } else { predicate = (o) => o.Tags.Any(t => tagsArray.Contains(t.Name)); } } else if (url != null) { /* Extract the respective Operation Id(s) that match the provided url path */ if (!_openApiOperationsTable.Any() || forceRefresh) { _uriTemplateTable = new UriTemplateMatcher(); _openApiOperationsTable = new Dictionary <int, OpenApiOperation[]>(); await PopulateReferenceTablesAync(source); } url = url.Replace('-', '_'); TemplateMatch resultMatch = _uriTemplateTable.Match(new Uri(url.ToLower(), UriKind.RelativeOrAbsolute)); if (resultMatch == null) { throw new ArgumentException("The url supplied could not be found."); } /* Fetch the corresponding Operations Id(s) for the matched url */ OpenApiOperation[] openApiOps = _openApiOperationsTable[int.Parse(resultMatch.Key)]; string[] operationIdsArray = openApiOps.Select(x => x.OperationId).ToArray(); predicate = (o) => operationIdsArray.Contains(o.OperationId); } else { throw new InvalidOperationException("Either operationIds, tags or url need to be specified."); } return(predicate); }