Skip to content

Commit

Permalink
Attempt at supporting trailing slashes
Browse files Browse the repository at this point in the history
  • Loading branch information
mderriey committed Mar 6, 2024
1 parent ad775b2 commit 35398a1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
7 changes: 7 additions & 0 deletions src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
28 changes: 21 additions & 7 deletions test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -467,22 +467,36 @@ public async Task VerifyDiagramFromSampleOpenAPI()
await Verifier.Verify(diagram);
}

[Fact]
public void SupportsTrailingSlashesInPath()
public static TheoryData<string, string[], string, string> SupportsTrailingSlashesInPathData => new TheoryData<string, string[], string, string>
{
// 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);
}
}
}

0 comments on commit 35398a1

Please sign in to comment.