From 35398a180542bfa9d36964ce4fa2003cd6e1a443 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micka=C3=ABl=20Derriey?= Date: Wed, 6 Mar 2024 15:35:38 +0100 Subject: [PATCH] Attempt at supporting trailing slashes --- .../Services/OpenApiUrlTreeNode.cs | 7 +++++ .../Services/OpenApiUrlTreeNodeTests.cs | 28 ++++++++++++++----- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 53a79c8a4..38b571112 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -150,6 +150,13 @@ public OpenApiUrlTreeNode Attach(string path, } var segments = path.Split('/'); + if (path.EndsWith("/")) + { + // Remove the last element, which is empty, and append the trailing slash to the new last element + // This is to support URLs with trailing slashes + Array.Resize(ref segments, segments.Length - 1); + segments[segments.Length - 1] += "/"; + } return Attach(segments: segments, pathItem: pathItem, diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs index 76e1c5f31..5303d7390 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs @@ -467,22 +467,36 @@ public async Task VerifyDiagramFromSampleOpenAPI() await Verifier.Verify(diagram); } - [Fact] - public void SupportsTrailingSlashesInPath() + public static TheoryData SupportsTrailingSlashesInPathData => new TheoryData + { + // Path, children up to second to leaf, last expected leaf node name, expected leaf node path + { "/cars/{car-id}/build/", ["cars", "{car-id}"], "build/", @"\cars\{car-id}\build/" }, + { "/cars/", [], "cars/", @"\cars/" }, + }; + + [Theory] + [MemberData(nameof(SupportsTrailingSlashesInPathData))] + public void SupportsTrailingSlashesInPath(string path, string[] childrenBeforeLastNode, string expectedLeafNodeName, string expectedLeafNodePath) { var openApiDocument = new OpenApiDocument { Paths = new() { - ["/cars/{car-id}/build/"] = new() + [path] = new() } }; - var label1 = "trailing-slash"; - var rootNode = OpenApiUrlTreeNode.Create(openApiDocument, label1); - var buildNode = rootNode.Children["cars"].Children["{car-id}"].Children["build"]; + var label = "trailing-slash"; + var rootNode = OpenApiUrlTreeNode.Create(openApiDocument, label); + + var secondToLeafNode = rootNode; + foreach (var childName in childrenBeforeLastNode) + { + secondToLeafNode = secondToLeafNode.Children[childName]; + } - // Should buildNode have a path of "build/" or should it have a child with an empty string key? + Assert.True(secondToLeafNode.Children.TryGetValue(expectedLeafNodeName, out var lastNode)); + Assert.Equal(expectedLeafNodePath, lastNode.Path); } } }